idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
15,700
@ SuppressWarnings ( "deprecation" ) public static boolean hasNewNetworkConfig ( final Configuration config ) { return config . contains ( TaskManagerOptions . NETWORK_BUFFERS_MEMORY_FRACTION ) || config . contains ( TaskManagerOptions . NETWORK_BUFFERS_MEMORY_MIN ) || config . contains ( TaskManagerOptions . NETWORK_BUFFERS_MEMORY_MAX ) || ! config . contains ( TaskManagerOptions . NETWORK_NUM_BUFFERS ) ; }
Returns whether the new network buffer memory configuration is present in the configuration object i . e . at least one new parameter is given or the old one is not present .
15,701
@ SuppressWarnings ( "deprecation" ) private static int calculateNumberOfNetworkBuffers ( Configuration configuration , long maxJvmHeapMemory ) { final int numberOfNetworkBuffers ; if ( ! hasNewNetworkConfig ( configuration ) ) { numberOfNetworkBuffers = configuration . getInteger ( TaskManagerOptions . NETWORK_NUM_BUFFERS ) ; checkOldNetworkConfig ( numberOfNetworkBuffers ) ; } else { if ( configuration . contains ( TaskManagerOptions . NETWORK_NUM_BUFFERS ) ) { LOG . info ( "Ignoring old (but still present) network buffer configuration via {}." , TaskManagerOptions . NETWORK_NUM_BUFFERS . key ( ) ) ; } final long networkMemorySize = calculateNewNetworkBufferMemory ( configuration , maxJvmHeapMemory ) ; long numberOfNetworkBuffersLong = networkMemorySize / getPageSize ( configuration ) ; if ( numberOfNetworkBuffersLong > Integer . MAX_VALUE ) { throw new IllegalArgumentException ( "The given number of memory bytes (" + networkMemorySize + ") corresponds to more than MAX_INT pages." ) ; } numberOfNetworkBuffers = ( int ) numberOfNetworkBuffersLong ; } return numberOfNetworkBuffers ; }
Calculates the number of network buffers based on configuration and jvm heap size .
15,702
public static int getPageSize ( Configuration configuration ) { final int pageSize = checkedDownCast ( MemorySize . parse ( configuration . getString ( TaskManagerOptions . MEMORY_SEGMENT_SIZE ) ) . getBytes ( ) ) ; ConfigurationParserUtils . checkConfigParameter ( pageSize >= MemoryManager . MIN_PAGE_SIZE , pageSize , TaskManagerOptions . MEMORY_SEGMENT_SIZE . key ( ) , "Minimum memory segment size is " + MemoryManager . MIN_PAGE_SIZE ) ; ConfigurationParserUtils . checkConfigParameter ( MathUtils . isPowerOf2 ( pageSize ) , pageSize , TaskManagerOptions . MEMORY_SEGMENT_SIZE . key ( ) , "Memory segment size must be a power of 2." ) ; return pageSize ; }
Parses the configuration to get the page size and validates the value .
15,703
public SplitDataProperties < T > splitsOrderedBy ( int [ ] orderFields , Order [ ] orders ) { if ( orderFields == null || orders == null ) { throw new InvalidProgramException ( "OrderFields or Orders may not be null." ) ; } else if ( orderFields . length == 0 ) { throw new InvalidProgramException ( "OrderFields may not be empty." ) ; } else if ( orders . length == 0 ) { throw new InvalidProgramException ( "Orders may not be empty" ) ; } else if ( orderFields . length != orders . length ) { throw new InvalidProgramException ( "Number of OrderFields and Orders must match." ) ; } if ( this . splitGroupKeys != null ) { throw new InvalidProgramException ( "DataSource may either be grouped or sorted." ) ; } this . splitOrdering = new Ordering ( ) ; for ( int i = 0 ; i < orderFields . length ; i ++ ) { int pos = orderFields [ i ] ; int [ ] flatKeys = this . getAllFlatKeys ( new int [ ] { pos } ) ; for ( int key : flatKeys ) { for ( int okey : splitOrdering . getFieldPositions ( ) ) { if ( key == okey ) { throw new InvalidProgramException ( "Duplicate field in the field expression " + pos ) ; } } this . splitOrdering . appendOrdering ( key , null , orders [ i ] ) ; } } return this ; }
Defines that the data within an input split is sorted on the fields defined by the field positions in the specified orders . All records of an input split must be emitted by the input format in the defined order .
15,704
public SplitDataProperties < T > splitsOrderedBy ( String orderFields , Order [ ] orders ) { if ( orderFields == null || orders == null ) { throw new InvalidProgramException ( "OrderFields or Orders may not be null." ) ; } String [ ] orderKeysA = orderFields . split ( ";" ) ; if ( orderKeysA . length == 0 ) { throw new InvalidProgramException ( "OrderFields may not be empty." ) ; } else if ( orders . length == 0 ) { throw new InvalidProgramException ( "Orders may not be empty" ) ; } else if ( orderKeysA . length != orders . length ) { throw new InvalidProgramException ( "Number of OrderFields and Orders must match." ) ; } if ( this . splitGroupKeys != null ) { throw new InvalidProgramException ( "DataSource may either be grouped or sorted." ) ; } this . splitOrdering = new Ordering ( ) ; for ( int i = 0 ; i < orderKeysA . length ; i ++ ) { String keyExp = orderKeysA [ i ] ; Keys . ExpressionKeys < T > ek = new Keys . ExpressionKeys < > ( keyExp , this . type ) ; int [ ] flatKeys = ek . computeLogicalKeyPositions ( ) ; for ( int key : flatKeys ) { for ( int okey : splitOrdering . getFieldPositions ( ) ) { if ( key == okey ) { throw new InvalidProgramException ( "Duplicate field in field expression " + keyExp ) ; } } this . splitOrdering . appendOrdering ( key , null , orders [ i ] ) ; } } return this ; }
Defines that the data within an input split is sorted on the fields defined by the field expressions in the specified orders . Multiple field expressions must be separated by the semicolon ; character . All records of an input split must be emitted by the input format in the defined order .
15,705
public static < T > T copy ( T from , Kryo kryo , TypeSerializer < T > serializer ) { try { return kryo . copy ( from ) ; } catch ( KryoException ke ) { try { byte [ ] byteArray = InstantiationUtil . serializeToByteArray ( serializer , from ) ; return InstantiationUtil . deserializeFromByteArray ( serializer , byteArray ) ; } catch ( IOException ioe ) { throw new RuntimeException ( "Could not copy object by serializing/deserializing" + " it." , ioe ) ; } } }
Tries to copy the given record from using the provided Kryo instance . If this fails then the record from is copied by serializing it into a byte buffer and deserializing it from there .
15,706
public void open ( InputSplit ignored ) throws IOException { this . session = cluster . connect ( ) ; this . resultSet = session . execute ( query ) ; }
Opens a Session and executes the query .
15,707
private void redistributeBuffers ( ) throws IOException { assert Thread . holdsLock ( factoryLock ) ; final int numAvailableMemorySegment = totalNumberOfMemorySegments - numTotalRequiredBuffers ; if ( numAvailableMemorySegment == 0 ) { for ( LocalBufferPool bufferPool : allBufferPools ) { bufferPool . setNumBuffers ( bufferPool . getNumberOfRequiredMemorySegments ( ) ) ; } return ; } long totalCapacity = 0 ; for ( LocalBufferPool bufferPool : allBufferPools ) { int excessMax = bufferPool . getMaxNumberOfMemorySegments ( ) - bufferPool . getNumberOfRequiredMemorySegments ( ) ; totalCapacity += Math . min ( numAvailableMemorySegment , excessMax ) ; } if ( totalCapacity == 0 ) { return ; } final int memorySegmentsToDistribute = MathUtils . checkedDownCast ( Math . min ( numAvailableMemorySegment , totalCapacity ) ) ; long totalPartsUsed = 0 ; int numDistributedMemorySegment = 0 ; for ( LocalBufferPool bufferPool : allBufferPools ) { int excessMax = bufferPool . getMaxNumberOfMemorySegments ( ) - bufferPool . getNumberOfRequiredMemorySegments ( ) ; if ( excessMax == 0 ) { continue ; } totalPartsUsed += Math . min ( numAvailableMemorySegment , excessMax ) ; final int mySize = MathUtils . checkedDownCast ( memorySegmentsToDistribute * totalPartsUsed / totalCapacity - numDistributedMemorySegment ) ; numDistributedMemorySegment += mySize ; bufferPool . setNumBuffers ( bufferPool . getNumberOfRequiredMemorySegments ( ) + mySize ) ; } assert ( totalPartsUsed == totalCapacity ) ; assert ( numDistributedMemorySegment == memorySegmentsToDistribute ) ; }
Must be called from synchronized block
15,708
public void close ( ) throws IOException { Throwable ex = null ; synchronized ( this ) { if ( closed ) { return ; } closed = true ; if ( recordsOutFile != null ) { try { recordsOutFile . close ( ) ; recordsOutFile = null ; } catch ( Throwable t ) { LOG . error ( "Cannot close the large records spill file." , t ) ; ex = ex == null ? t : ex ; } } if ( keysOutFile != null ) { try { keysOutFile . close ( ) ; keysOutFile = null ; } catch ( Throwable t ) { LOG . error ( "Cannot close the large records key spill file." , t ) ; ex = ex == null ? t : ex ; } } if ( recordsReader != null ) { try { recordsReader . close ( ) ; recordsReader = null ; } catch ( Throwable t ) { LOG . error ( "Cannot close the large records reader." , t ) ; ex = ex == null ? t : ex ; } } if ( keysReader != null ) { try { keysReader . close ( ) ; keysReader = null ; } catch ( Throwable t ) { LOG . error ( "Cannot close the large records key reader." , t ) ; ex = ex == null ? t : ex ; } } if ( recordsChannel != null ) { try { ioManager . deleteChannel ( recordsChannel ) ; recordsChannel = null ; } catch ( Throwable t ) { LOG . error ( "Cannot delete the large records spill file." , t ) ; ex = ex == null ? t : ex ; } } if ( keysChannel != null ) { try { ioManager . deleteChannel ( keysChannel ) ; keysChannel = null ; } catch ( Throwable t ) { LOG . error ( "Cannot delete the large records key spill file." , t ) ; ex = ex == null ? t : ex ; } } if ( keySorter != null ) { try { keySorter . close ( ) ; keySorter = null ; } catch ( Throwable t ) { LOG . error ( "Cannot properly dispose the key sorter and clean up its temporary files." , t ) ; ex = ex == null ? t : ex ; } } memManager . release ( memory ) ; recordCounter = 0 ; } if ( ex != null ) { throw new IOException ( "An error occurred cleaning up spill files in the large record handler." , ex ) ; } }
Closes all structures and deletes all temporary files . Even in the presence of failures this method will try and continue closing files and deleting temporary files .
15,709
private AggregateOperator < T > aggregate ( Aggregations agg , int field , String callLocationName ) { return new AggregateOperator < T > ( this , agg , field , callLocationName ) ; }
private helper that allows to set a different call location name
15,710
public ArrayList < MemorySegment > resetOverflowBuckets ( ) { this . numOverflowSegments = 0 ; this . nextOverflowBucket = 0 ; ArrayList < MemorySegment > result = new ArrayList < MemorySegment > ( this . overflowSegments . length ) ; for ( int i = 0 ; i < this . overflowSegments . length ; i ++ ) { if ( this . overflowSegments [ i ] != null ) { result . add ( this . overflowSegments [ i ] ) ; } } this . overflowSegments = new MemorySegment [ 2 ] ; return result ; }
resets overflow bucket counters and returns freed memory and should only be used for resizing
15,711
public final long appendRecord ( T record ) throws IOException { long pointer = this . writeView . getCurrentPointer ( ) ; try { this . serializer . serialize ( record , this . writeView ) ; this . recordCounter ++ ; return pointer ; } catch ( EOFException e ) { this . writeView . resetTo ( pointer ) ; throw e ; } }
Inserts the given object into the current buffer . This method returns a pointer that can be used to address the written record in this partition .
15,712
public void overwriteRecordAt ( long pointer , T record ) throws IOException { long tmpPointer = this . writeView . getCurrentPointer ( ) ; this . writeView . resetTo ( pointer ) ; this . serializer . serialize ( record , this . writeView ) ; this . writeView . resetTo ( tmpPointer ) ; }
UNSAFE!! overwrites record causes inconsistency or data loss for overwriting everything but records of the exact same size
15,713
public void allocateSegments ( int numberOfSegments ) { while ( getBlockCount ( ) < numberOfSegments ) { MemorySegment next = this . availableMemory . nextSegment ( ) ; if ( next != null ) { this . partitionPages . add ( next ) ; } else { return ; } } }
attempts to allocate specified number of segments and should only be used by compaction partition fails silently if not enough segments are available since next compaction could still succeed
15,714
public static BinaryInMemorySortBuffer createBuffer ( NormalizedKeyComputer normalizedKeyComputer , AbstractRowSerializer < BaseRow > inputSerializer , BinaryRowSerializer serializer , RecordComparator comparator , List < MemorySegment > memory ) throws IOException { checkArgument ( memory . size ( ) >= MIN_REQUIRED_BUFFERS ) ; int totalNumBuffers = memory . size ( ) ; ListMemorySegmentPool pool = new ListMemorySegmentPool ( memory ) ; ArrayList < MemorySegment > recordBufferSegments = new ArrayList < > ( 16 ) ; return new BinaryInMemorySortBuffer ( normalizedKeyComputer , inputSerializer , serializer , comparator , recordBufferSegments , new SimpleCollectingOutputView ( recordBufferSegments , pool , pool . pageSize ( ) ) , pool , totalNumBuffers ) ; }
Create a memory sorter in insert way .
15,715
public void serializeRecord ( T record ) throws IOException { if ( CHECKED ) { if ( dataBuffer . hasRemaining ( ) ) { throw new IllegalStateException ( "Pending serialization of previous record." ) ; } } serializationBuffer . clear ( ) ; lengthBuffer . clear ( ) ; record . write ( serializationBuffer ) ; int len = serializationBuffer . length ( ) ; lengthBuffer . putInt ( 0 , len ) ; dataBuffer = serializationBuffer . wrapAsByteBuffer ( ) ; }
Serializes the complete record to an intermediate data serialization buffer .
15,716
public SerializationResult copyToBufferBuilder ( BufferBuilder targetBuffer ) { targetBuffer . append ( lengthBuffer ) ; targetBuffer . append ( dataBuffer ) ; targetBuffer . commit ( ) ; return getSerializationResult ( targetBuffer ) ; }
Copies an intermediate data serialization buffer into the target BufferBuilder .
15,717
private void enqueueAvailableReader ( final NetworkSequenceViewReader reader ) throws Exception { if ( reader . isRegisteredAsAvailable ( ) || ! reader . isAvailable ( ) ) { return ; } boolean triggerWrite = availableReaders . isEmpty ( ) ; registerAvailableReader ( reader ) ; if ( triggerWrite ) { writeAndFlushNextMessageIfPossible ( ctx . channel ( ) ) ; } }
Try to enqueue the reader once receiving credit notification from the consumer or receiving non - empty reader notification from the producer .
15,718
public void invoke ( IN value ) { try { byte [ ] msg = schema . serialize ( value ) ; if ( publishOptions == null ) { channel . basicPublish ( "" , queueName , null , msg ) ; } else { boolean mandatory = publishOptions . computeMandatory ( value ) ; boolean immediate = publishOptions . computeImmediate ( value ) ; Preconditions . checkState ( ! ( returnListener == null && ( mandatory || immediate ) ) , "Setting mandatory and/or immediate flags to true requires a ReturnListener." ) ; String rk = publishOptions . computeRoutingKey ( value ) ; String exchange = publishOptions . computeExchange ( value ) ; channel . basicPublish ( exchange , rk , mandatory , immediate , publishOptions . computeProperties ( value ) , msg ) ; } } catch ( IOException e ) { if ( logFailuresOnly ) { LOG . error ( "Cannot send RMQ message {} at {}" , queueName , rmqConnectionConfig . getHost ( ) , e ) ; } else { throw new RuntimeException ( "Cannot send RMQ message " + queueName + " at " + rmqConnectionConfig . getHost ( ) , e ) ; } } }
Called when new data arrives to the sink and forwards it to RMQ .
15,719
public void setInputType ( TypeInformation < ? > type , ExecutionConfig executionConfig ) { if ( ! type . isTupleType ( ) ) { throw new InvalidProgramException ( "The " + ScalaCsvOutputFormat . class . getSimpleName ( ) + " can only be used to write tuple data sets." ) ; } }
The purpose of this method is solely to check whether the data type to be processed is in fact a tuple type .
15,720
public static < X > Pattern < X , X > begin ( final String name ) { return new Pattern < > ( name , null , ConsumingStrategy . STRICT , AfterMatchSkipStrategy . noSkip ( ) ) ; }
Starts a new pattern sequence . The provided name is the one of the initial pattern of the new sequence . Furthermore the base type of the event sequence is set .
15,721
public < S extends F > Pattern < T , S > subtype ( final Class < S > subtypeClass ) { Preconditions . checkNotNull ( subtypeClass , "The class cannot be null." ) ; if ( condition == null ) { this . condition = new SubtypeCondition < F > ( subtypeClass ) ; } else { this . condition = new RichAndCondition < > ( condition , new SubtypeCondition < F > ( subtypeClass ) ) ; } @ SuppressWarnings ( "unchecked" ) Pattern < T , S > result = ( Pattern < T , S > ) this ; return result ; }
Applies a subtype constraint on the current pattern . This means that an event has to be of the given subtype in order to be matched .
15,722
public Pattern < T , F > until ( IterativeCondition < F > untilCondition ) { Preconditions . checkNotNull ( untilCondition , "The condition cannot be null" ) ; if ( this . untilCondition != null ) { throw new MalformedPatternException ( "Only one until condition can be applied." ) ; } if ( ! quantifier . hasProperty ( Quantifier . QuantifierProperty . LOOPING ) ) { throw new MalformedPatternException ( "The until condition is only applicable to looping states." ) ; } ClosureCleaner . clean ( untilCondition , true ) ; this . untilCondition = untilCondition ; return this ; }
Applies a stop condition for a looping state . It allows cleaning the underlying state .
15,723
public Pattern < T , F > within ( Time windowTime ) { if ( windowTime != null ) { this . windowTime = windowTime ; } return this ; }
Defines the maximum time interval in which a matching pattern has to be completed in order to be considered valid . This interval corresponds to the maximum time gap between first and the last event .
15,724
public Pattern < T , T > next ( final String name ) { return new Pattern < > ( name , this , ConsumingStrategy . STRICT , afterMatchSkipStrategy ) ; }
Appends a new pattern to the existing one . The new pattern enforces strict temporal contiguity . This means that the whole pattern sequence matches only if an event which matches this pattern directly follows the preceding matching event . Thus there cannot be any events in between two matching events .
15,725
public Pattern < T , T > notNext ( final String name ) { if ( quantifier . hasProperty ( Quantifier . QuantifierProperty . OPTIONAL ) ) { throw new UnsupportedOperationException ( "Specifying a pattern with an optional path to NOT condition is not supported yet. " + "You can simulate such pattern with two independent patterns, one with and the other without " + "the optional part." ) ; } return new Pattern < > ( name , this , ConsumingStrategy . NOT_NEXT , afterMatchSkipStrategy ) ; }
Appends a new pattern to the existing one . The new pattern enforces that there is no event matching this pattern right after the preceding matched event .
15,726
public Pattern < T , T > notFollowedBy ( final String name ) { if ( quantifier . hasProperty ( Quantifier . QuantifierProperty . OPTIONAL ) ) { throw new UnsupportedOperationException ( "Specifying a pattern with an optional path to NOT condition is not supported yet. " + "You can simulate such pattern with two independent patterns, one with and the other without " + "the optional part." ) ; } return new Pattern < > ( name , this , ConsumingStrategy . NOT_FOLLOW , afterMatchSkipStrategy ) ; }
Appends a new pattern to the existing one . The new pattern enforces that there is no event matching this pattern between the preceding pattern and succeeding this one .
15,727
public Pattern < T , F > times ( int times ) { checkIfNoNotPattern ( ) ; checkIfQuantifierApplied ( ) ; Preconditions . checkArgument ( times > 0 , "You should give a positive number greater than 0." ) ; this . quantifier = Quantifier . times ( quantifier . getConsumingStrategy ( ) ) ; this . times = Times . of ( times ) ; return this ; }
Specifies exact number of times that this pattern should be matched .
15,728
public Pattern < T , F > times ( int from , int to ) { checkIfNoNotPattern ( ) ; checkIfQuantifierApplied ( ) ; this . quantifier = Quantifier . times ( quantifier . getConsumingStrategy ( ) ) ; if ( from == 0 ) { this . quantifier . optional ( ) ; from = 1 ; } this . times = Times . of ( from , to ) ; return this ; }
Specifies that the pattern can occur between from and to times .
15,729
public Pattern < T , F > timesOrMore ( int times ) { checkIfNoNotPattern ( ) ; checkIfQuantifierApplied ( ) ; this . quantifier = Quantifier . looping ( quantifier . getConsumingStrategy ( ) ) ; this . times = Times . of ( times ) ; return this ; }
Specifies that this pattern can occur the specified times at least . This means at least the specified times and at most infinite number of events can be matched to this pattern .
15,730
public static < T , F extends T > GroupPattern < T , F > begin ( final Pattern < T , F > group , final AfterMatchSkipStrategy afterMatchSkipStrategy ) { return new GroupPattern < > ( null , group , ConsumingStrategy . STRICT , afterMatchSkipStrategy ) ; }
Starts a new pattern sequence . The provided pattern is the initial pattern of the new sequence .
15,731
public GroupPattern < T , F > next ( Pattern < T , F > group ) { return new GroupPattern < > ( this , group , ConsumingStrategy . STRICT , afterMatchSkipStrategy ) ; }
Appends a new group pattern to the existing one . The new pattern enforces strict temporal contiguity . This means that the whole pattern sequence matches only if an event which matches this pattern directly follows the preceding matching event . Thus there cannot be any events in between two matching events .
15,732
public void replace ( String pathInZooKeeper , int expectedVersion , T state ) throws Exception { checkNotNull ( pathInZooKeeper , "Path in ZooKeeper" ) ; checkNotNull ( state , "State" ) ; final String path = normalizePath ( pathInZooKeeper ) ; RetrievableStateHandle < T > oldStateHandle = get ( path , false ) ; RetrievableStateHandle < T > newStateHandle = storage . store ( state ) ; boolean success = false ; try { byte [ ] serializedStateHandle = InstantiationUtil . serializeObject ( newStateHandle ) ; client . setData ( ) . withVersion ( expectedVersion ) . forPath ( path , serializedStateHandle ) ; success = true ; } catch ( KeeperException . NoNodeException e ) { throw new ConcurrentModificationException ( "ZooKeeper unexpectedly modified" , e ) ; } finally { if ( success ) { oldStateHandle . discardState ( ) ; } else { newStateHandle . discardState ( ) ; } } }
Replaces a state handle in ZooKeeper and discards the old state handle .
15,733
public Collection < String > getAllPaths ( ) throws Exception { final String path = "/" ; while ( true ) { Stat stat = client . checkExists ( ) . forPath ( path ) ; if ( stat == null ) { return Collections . emptyList ( ) ; } else { try { return client . getChildren ( ) . forPath ( path ) ; } catch ( KeeperException . NoNodeException ignored ) { } } } }
Return a list of all valid paths for state handles .
15,734
@ SuppressWarnings ( "unchecked" ) public List < Tuple2 < RetrievableStateHandle < T > , String > > getAllAndLock ( ) throws Exception { final List < Tuple2 < RetrievableStateHandle < T > , String > > stateHandles = new ArrayList < > ( ) ; boolean success = false ; retry : while ( ! success ) { stateHandles . clear ( ) ; Stat stat = client . checkExists ( ) . forPath ( "/" ) ; if ( stat == null ) { break ; } else { int initialCVersion = stat . getCversion ( ) ; List < String > children = client . getChildren ( ) . forPath ( "/" ) ; for ( String path : children ) { path = "/" + path ; try { final RetrievableStateHandle < T > stateHandle = getAndLock ( path ) ; stateHandles . add ( new Tuple2 < > ( stateHandle , path ) ) ; } catch ( KeeperException . NoNodeException ignored ) { continue retry ; } catch ( IOException ioException ) { LOG . warn ( "Could not get all ZooKeeper children. Node {} contained " + "corrupted data. Ignoring this node." , path , ioException ) ; } } int finalCVersion = client . checkExists ( ) . forPath ( "/" ) . getCversion ( ) ; success = initialCVersion == finalCVersion ; } } return stateHandles ; }
Gets all available state handles from ZooKeeper and locks the respective state nodes .
15,735
public void releaseAndTryRemoveAll ( ) throws Exception { Collection < String > children = getAllPaths ( ) ; Exception exception = null ; for ( String child : children ) { try { releaseAndTryRemove ( '/' + child ) ; } catch ( Exception e ) { exception = ExceptionUtils . firstOrSuppressed ( e , exception ) ; } } if ( exception != null ) { throw new Exception ( "Could not properly release and try removing all state nodes." , exception ) ; } }
Releases all lock nodes of this ZooKeeperStateHandleStores and tries to remove all state nodes which are not locked anymore .
15,736
public void release ( String pathInZooKeeper ) throws Exception { final String path = normalizePath ( pathInZooKeeper ) ; try { client . delete ( ) . forPath ( getLockPath ( path ) ) ; } catch ( KeeperException . NoNodeException ignored ) { } catch ( Exception e ) { throw new Exception ( "Could not release the lock: " + getLockPath ( pathInZooKeeper ) + '.' , e ) ; } }
Releases the lock from the node under the given ZooKeeper path . If no lock exists then nothing happens .
15,737
public void releaseAll ( ) throws Exception { Collection < String > children = getAllPaths ( ) ; Exception exception = null ; for ( String child : children ) { try { release ( child ) ; } catch ( Exception e ) { exception = ExceptionUtils . firstOrSuppressed ( e , exception ) ; } } if ( exception != null ) { throw new Exception ( "Could not properly release all state nodes." , exception ) ; } }
Releases all lock nodes of this ZooKeeperStateHandleStore .
15,738
public void deleteChildren ( ) throws Exception { final String path = "/" + client . getNamespace ( ) ; LOG . info ( "Removing {} from ZooKeeper" , path ) ; ZKPaths . deleteChildren ( client . getZookeeperClient ( ) . getZooKeeper ( ) , path , true ) ; }
Recursively deletes all children .
15,739
@ SuppressWarnings ( "unchecked" ) private RetrievableStateHandle < T > get ( String pathInZooKeeper , boolean lock ) throws Exception { checkNotNull ( pathInZooKeeper , "Path in ZooKeeper" ) ; final String path = normalizePath ( pathInZooKeeper ) ; if ( lock ) { try { client . create ( ) . withMode ( CreateMode . EPHEMERAL ) . forPath ( getLockPath ( path ) ) ; } catch ( KeeperException . NodeExistsException ignored ) { } } boolean success = false ; try { byte [ ] data = client . getData ( ) . forPath ( path ) ; try { RetrievableStateHandle < T > retrievableStateHandle = InstantiationUtil . deserializeObject ( data , Thread . currentThread ( ) . getContextClassLoader ( ) ) ; success = true ; return retrievableStateHandle ; } catch ( IOException | ClassNotFoundException e ) { throw new IOException ( "Failed to deserialize state handle from ZooKeeper data from " + path + '.' , e ) ; } } finally { if ( ! success && lock ) { release ( path ) ; } } }
Gets a state handle from ZooKeeper and optionally locks it .
15,740
public void set ( int index ) { Preconditions . checkArgument ( index < bitLength && index >= 0 ) ; int byteIndex = ( index & BYTE_POSITION_MASK ) >>> 3 ; byte current = memorySegment . get ( offset + byteIndex ) ; current |= ( 1 << ( index & BYTE_INDEX_MASK ) ) ; memorySegment . put ( offset + byteIndex , current ) ; }
Sets the bit at specified index .
15,741
public final void coGroup ( Iterable < IN1 > first , Iterable < IN2 > second , Collector < OUT > out ) throws Exception { streamer . streamBufferWithGroups ( first . iterator ( ) , second . iterator ( ) , out ) ; }
Calls the external python function .
15,742
void registerColumnFamily ( String columnFamilyName , ColumnFamilyHandle handle ) { MetricGroup group = metricGroup . addGroup ( columnFamilyName ) ; for ( String property : options . getProperties ( ) ) { RocksDBNativeMetricView gauge = new RocksDBNativeMetricView ( handle , property ) ; group . gauge ( property , gauge ) ; } }
Register gauges to pull native metrics for the column family .
15,743
private void setProperty ( ColumnFamilyHandle handle , String property , RocksDBNativeMetricView metricView ) { if ( metricView . isClosed ( ) ) { return ; } try { synchronized ( lock ) { if ( rocksDB != null ) { long value = rocksDB . getLongProperty ( handle , property ) ; metricView . setValue ( value ) ; } } } catch ( RocksDBException e ) { metricView . close ( ) ; LOG . warn ( "Failed to read native metric %s from RocksDB" , property , e ) ; } }
Updates the value of metricView if the reference is still valid .
15,744
public String getMessage ( ) { String ret = super . getMessage ( ) ; if ( fileName != null ) { ret += ( " in " + fileName ) ; if ( lineNumber != - 1 ) { ret += " at line number " + lineNumber ; } if ( columnNumber != - 1 ) { ret += " at column number " + columnNumber ; } } return ret ; }
Returns a message containing the String passed to a constructor as well as line and column numbers and filename if any of these are known .
15,745
public static int bernstein ( String key ) { int hash = 0 ; int i ; for ( i = 0 ; i < key . length ( ) ; ++ i ) { hash = 33 * hash + key . charAt ( i ) ; } return hash ; }
Bernstein s hash
15,746
public String nextTo ( String delimiters ) throws JSONException { char c ; StringBuilder sb = new StringBuilder ( ) ; for ( ; ; ) { c = this . next ( ) ; if ( delimiters . indexOf ( c ) >= 0 || c == 0 || c == '\n' || c == '\r' ) { if ( c != 0 ) { this . back ( ) ; } return sb . toString ( ) . trim ( ) ; } sb . append ( c ) ; } }
Get the text up but not including one of the specified delimiter characters or the end of line whichever comes first .
15,747
private static String transThree ( String s ) { String value = "" ; if ( s . startsWith ( "0" ) ) { value = transTwo ( s . substring ( 1 ) ) ; } else if ( s . substring ( 1 ) . equals ( "00" ) ) { value = parseFirst ( s . substring ( 0 , 1 ) ) + " HUNDRED" ; } else { value = parseFirst ( s . substring ( 0 , 1 ) ) + " HUNDRED AND " + transTwo ( s . substring ( 1 ) ) ; } return value ; }
s . length = 3
15,748
private static void appendDigits ( final Appendable buffer , final int value ) throws IOException { buffer . append ( ( char ) ( value / 10 + '0' ) ) ; buffer . append ( ( char ) ( value % 10 + '0' ) ) ; }
Appends two digits to the given buffer .
15,749
private static void appendFullDigits ( final Appendable buffer , int value , int minFieldWidth ) throws IOException { if ( value < 10000 ) { int nDigits = 4 ; if ( value < 1000 ) { -- nDigits ; if ( value < 100 ) { -- nDigits ; if ( value < 10 ) { -- nDigits ; } } } for ( int i = minFieldWidth - nDigits ; i > 0 ; -- i ) { buffer . append ( '0' ) ; } switch ( nDigits ) { case 4 : buffer . append ( ( char ) ( value / 1000 + '0' ) ) ; value %= 1000 ; case 3 : if ( value >= 100 ) { buffer . append ( ( char ) ( value / 100 + '0' ) ) ; value %= 100 ; } else { buffer . append ( '0' ) ; } case 2 : if ( value >= 10 ) { buffer . append ( ( char ) ( value / 10 + '0' ) ) ; value %= 10 ; } else { buffer . append ( '0' ) ; } case 1 : buffer . append ( ( char ) ( value + '0' ) ) ; } } else { final char [ ] work = new char [ MAX_DIGITS ] ; int digit = 0 ; while ( value != 0 ) { work [ digit ++ ] = ( char ) ( value % 10 + '0' ) ; value = value / 10 ; } while ( digit < minFieldWidth ) { buffer . append ( '0' ) ; -- minFieldWidth ; } while ( -- digit >= 0 ) { buffer . append ( work [ digit ] ) ; } } }
Appends all digits to the given buffer .
15,750
private void readObject ( final ObjectInputStream in ) throws IOException , ClassNotFoundException { in . defaultReadObject ( ) ; final Calendar definingCalendar = Calendar . getInstance ( timeZone , locale ) ; init ( definingCalendar ) ; }
Create the object after serialization . This implementation reinitializes the transient properties .
15,751
private static Map < String , Integer > appendDisplayNames ( final Calendar cal , final Locale locale , final int field , final StringBuilder regex ) { final Map < String , Integer > values = new HashMap < > ( ) ; final Map < String , Integer > displayNames = cal . getDisplayNames ( field , Calendar . ALL_STYLES , locale ) ; final TreeSet < String > sorted = new TreeSet < > ( LONGER_FIRST_LOWERCASE ) ; for ( final Map . Entry < String , Integer > displayName : displayNames . entrySet ( ) ) { final String key = displayName . getKey ( ) . toLowerCase ( locale ) ; if ( sorted . add ( key ) ) { values . put ( key , displayName . getValue ( ) ) ; } } for ( final String symbol : sorted ) { simpleQuote ( regex , symbol ) . append ( '|' ) ; } return values ; }
Get the short and long values displayed for a field
15,752
private Strategy getStrategy ( final char f , final int width , final Calendar definingCalendar ) { switch ( f ) { default : throw new IllegalArgumentException ( "Format '" + f + "' not supported" ) ; case 'D' : return DAY_OF_YEAR_STRATEGY ; case 'E' : return getLocaleSpecificStrategy ( Calendar . DAY_OF_WEEK , definingCalendar ) ; case 'F' : return DAY_OF_WEEK_IN_MONTH_STRATEGY ; case 'G' : return getLocaleSpecificStrategy ( Calendar . ERA , definingCalendar ) ; case 'H' : return HOUR_OF_DAY_STRATEGY ; case 'K' : return HOUR_STRATEGY ; case 'M' : return width >= 3 ? getLocaleSpecificStrategy ( Calendar . MONTH , definingCalendar ) : NUMBER_MONTH_STRATEGY ; case 'S' : return MILLISECOND_STRATEGY ; case 'W' : return WEEK_OF_MONTH_STRATEGY ; case 'a' : return getLocaleSpecificStrategy ( Calendar . AM_PM , definingCalendar ) ; case 'd' : return DAY_OF_MONTH_STRATEGY ; case 'h' : return HOUR12_STRATEGY ; case 'k' : return HOUR24_OF_DAY_STRATEGY ; case 'm' : return MINUTE_STRATEGY ; case 's' : return SECOND_STRATEGY ; case 'u' : return DAY_OF_WEEK_STRATEGY ; case 'w' : return WEEK_OF_YEAR_STRATEGY ; case 'y' : case 'Y' : return width > 2 ? LITERAL_YEAR_STRATEGY : ABBREVIATED_YEAR_STRATEGY ; case 'X' : return ISO8601TimeZoneStrategy . getStrategy ( width ) ; case 'Z' : if ( width == 2 ) { return ISO8601TimeZoneStrategy . ISO_8601_3_STRATEGY ; } case 'z' : return getLocaleSpecificStrategy ( Calendar . ZONE_OFFSET , definingCalendar ) ; } }
Obtain a Strategy given a field from a SimpleDateFormat pattern
15,753
private static ConcurrentMap < Locale , Strategy > getCache ( final int field ) { synchronized ( caches ) { if ( caches [ field ] == null ) { caches [ field ] = new ConcurrentHashMap < > ( 3 ) ; } return caches [ field ] ; } }
Get a cache of Strategies for a particular field
15,754
private Strategy getLocaleSpecificStrategy ( final int field , final Calendar definingCalendar ) { final ConcurrentMap < Locale , Strategy > cache = getCache ( field ) ; Strategy strategy = cache . get ( locale ) ; if ( strategy == null ) { strategy = field == Calendar . ZONE_OFFSET ? new TimeZoneStrategy ( locale ) : new CaseInsensitiveTextStrategy ( field , definingCalendar , locale ) ; final Strategy inCache = cache . putIfAbsent ( locale , strategy ) ; if ( inCache != null ) { return inCache ; } } return strategy ; }
Construct a Strategy that parses a Text field
15,755
private F getDateTimeInstance ( final Integer dateStyle , final Integer timeStyle , final TimeZone timeZone , Locale locale ) { if ( locale == null ) { locale = Locale . getDefault ( ) ; } final String pattern = getPatternForStyle ( dateStyle , timeStyle , locale ) ; return getInstance ( pattern , timeZone , locale ) ; }
This must remain private see LANG - 884
15,756
public Object nextMeta ( ) throws JSONException { char c ; char q ; do { c = next ( ) ; } while ( Character . isWhitespace ( c ) ) ; switch ( c ) { case 0 : throw syntaxError ( "Misshaped meta tag" ) ; case '<' : return XML . LT ; case '>' : return XML . GT ; case '/' : return XML . SLASH ; case '=' : return XML . EQ ; case '!' : return XML . BANG ; case '?' : return XML . QUEST ; case '"' : case '\'' : q = c ; for ( ; ; ) { c = next ( ) ; if ( c == 0 ) { throw syntaxError ( "Unterminated string" ) ; } if ( c == q ) { return Boolean . TRUE ; } } default : for ( ; ; ) { c = next ( ) ; if ( Character . isWhitespace ( c ) ) { return Boolean . TRUE ; } switch ( c ) { case 0 : case '<' : case '>' : case '/' : case '=' : case '!' : case '?' : case '"' : case '\'' : back ( ) ; return Boolean . TRUE ; } } } }
Returns the next XML meta token . This is used for skipping over &lt ; ! ... &gt ; and &lt ; ? ... ?&gt ; structures .
15,757
public boolean skipPast ( String to ) throws JSONException { boolean b ; char c ; int i ; int j ; int offset = 0 ; int length = to . length ( ) ; char [ ] circle = new char [ length ] ; for ( i = 0 ; i < length ; i += 1 ) { c = next ( ) ; if ( c == 0 ) { return false ; } circle [ i ] = c ; } for ( ; ; ) { j = offset ; b = true ; for ( i = 0 ; i < length ; i += 1 ) { if ( circle [ j ] != to . charAt ( i ) ) { b = false ; break ; } j += 1 ; if ( j >= length ) { j -= length ; } } if ( b ) { return true ; } c = next ( ) ; if ( c == 0 ) { return false ; } circle [ offset ] = c ; offset += 1 ; if ( offset >= length ) { offset -= length ; } } }
Skip characters until past the requested string . If it is not found we are left at the end of the source with a result of false .
15,758
public String filter ( final String input ) { reset ( ) ; String s = input ; debug ( "************************************************" ) ; debug ( " INPUT: " + input ) ; s = escapeComments ( s ) ; debug ( " escapeComments: " + s ) ; s = balanceHTML ( s ) ; debug ( " balanceHTML: " + s ) ; s = checkTags ( s ) ; debug ( " checkTags: " + s ) ; s = processRemoveBlanks ( s ) ; debug ( "processRemoveBlanks: " + s ) ; s = validateEntities ( s ) ; debug ( " validateEntites: " + s ) ; debug ( "************************************************\n\n" ) ; return s ; }
given a user submitted input String filter out any invalid or restricted html .
15,759
public void dumpRequest ( Map < String , Object > result ) { exchange . getQueryParameters ( ) . forEach ( ( k , v ) -> { if ( config . getRequestFilteredQueryParameters ( ) . contains ( k ) ) { String queryParameterValue = config . isMaskEnabled ( ) ? Mask . maskRegex ( v . getFirst ( ) , "queryParameter" , k ) : v . getFirst ( ) ; queryParametersMap . put ( k , queryParameterValue ) ; } } ) ; this . putDumpInfoTo ( result ) ; }
impl of dumping request query parameter to result
15,760
protected void putDumpInfoTo ( Map < String , Object > result ) { if ( this . queryParametersMap . size ( ) > 0 ) { result . put ( DumpConstants . QUERY_PARAMETERS , queryParametersMap ) ; } }
put queryParametersMap to result .
15,761
public void sendMail ( String to , String subject , String content ) throws MessagingException { Properties props = new Properties ( ) ; props . put ( "mail.smtp.user" , emailConfg . getUser ( ) ) ; props . put ( "mail.smtp.host" , emailConfg . getHost ( ) ) ; props . put ( "mail.smtp.port" , emailConfg . getPort ( ) ) ; props . put ( "mail.smtp.starttls.enable" , "true" ) ; props . put ( "mail.smtp.debug" , emailConfg . getDebug ( ) ) ; props . put ( "mail.smtp.auth" , emailConfg . getAuth ( ) ) ; props . put ( "mail.smtp.ssl.trust" , emailConfg . host ) ; SMTPAuthenticator auth = new SMTPAuthenticator ( emailConfg . getUser ( ) , ( String ) secret . get ( SecretConstants . EMAIL_PASSWORD ) ) ; Session session = Session . getInstance ( props , auth ) ; MimeMessage message = new MimeMessage ( session ) ; message . setFrom ( new InternetAddress ( emailConfg . getUser ( ) ) ) ; message . addRecipient ( Message . RecipientType . TO , new InternetAddress ( to ) ) ; message . setSubject ( subject ) ; message . setContent ( content , "text/html" ) ; Transport . send ( message ) ; if ( logger . isInfoEnabled ( ) ) logger . info ( "An email has been sent to " + to + " with subject " + subject ) ; }
Send email with a string content .
15,762
public void sendMailWithAttachment ( String to , String subject , String content , String filename ) throws MessagingException { Properties props = new Properties ( ) ; props . put ( "mail.smtp.user" , emailConfg . getUser ( ) ) ; props . put ( "mail.smtp.host" , emailConfg . getHost ( ) ) ; props . put ( "mail.smtp.port" , emailConfg . getPort ( ) ) ; props . put ( "mail.smtp.starttls.enable" , "true" ) ; props . put ( "mail.smtp.debug" , emailConfg . getDebug ( ) ) ; props . put ( "mail.smtp.auth" , emailConfg . getAuth ( ) ) ; props . put ( "mail.smtp.ssl.trust" , emailConfg . host ) ; SMTPAuthenticator auth = new SMTPAuthenticator ( emailConfg . getUser ( ) , ( String ) secret . get ( SecretConstants . EMAIL_PASSWORD ) ) ; Session session = Session . getInstance ( props , auth ) ; MimeMessage message = new MimeMessage ( session ) ; message . setFrom ( new InternetAddress ( emailConfg . getUser ( ) ) ) ; message . addRecipient ( Message . RecipientType . TO , new InternetAddress ( to ) ) ; message . setSubject ( subject ) ; BodyPart messageBodyPart = new MimeBodyPart ( ) ; messageBodyPart . setText ( content ) ; Multipart multipart = new MimeMultipart ( ) ; multipart . addBodyPart ( messageBodyPart ) ; messageBodyPart = new MimeBodyPart ( ) ; DataSource source = new FileDataSource ( filename ) ; messageBodyPart . setDataHandler ( new DataHandler ( source ) ) ; messageBodyPart . setFileName ( filename ) ; multipart . addBodyPart ( messageBodyPart ) ; message . setContent ( multipart ) ; Transport . send ( message ) ; if ( logger . isInfoEnabled ( ) ) logger . info ( "An email has been sent to " + to + " with subject " + subject ) ; }
Send email with a string content and attachment
15,763
private static void handleSingletonClass ( String key , String value ) throws Exception { Object object = handleValue ( value ) ; if ( key . contains ( "," ) ) { String [ ] interfaces = key . split ( "," ) ; for ( String anInterface : interfaces ) { serviceMap . put ( anInterface , object ) ; } } else { serviceMap . put ( key , object ) ; } }
For each singleton definition create object with the initializer class and method and push it into the service map with the key of the class name .
15,764
private static void handleSingletonList ( String key , List < Object > value ) throws Exception { List < String > interfaceClasses = new ArrayList ( ) ; if ( key . contains ( "," ) ) { String [ ] interfaces = key . split ( "," ) ; interfaceClasses . addAll ( Arrays . asList ( interfaces ) ) ; } else { interfaceClasses . add ( key ) ; } if ( value != null && value . size ( ) == 1 ) { handleSingleImpl ( interfaceClasses , value ) ; } else { handleMultipleImpl ( interfaceClasses , value ) ; } }
For each singleton definition create object for the interface with the implementation class and push it into the service map with key and implemented object .
15,765
public static < T > T getBean ( Class < T > interfaceClass , Class typeClass ) { Object object = serviceMap . get ( interfaceClass . getName ( ) + "<" + typeClass . getName ( ) + ">" ) ; if ( object == null ) return null ; if ( object instanceof Object [ ] ) { return ( T ) Array . get ( object , 0 ) ; } else { return ( T ) object ; } }
Get a cached singleton object from service map by interface class and generic type class . The serviceMap is constructed from service . yml which defines interface and generic type to implementation mapping .
15,766
public static < T > T [ ] getBeans ( Class < T > interfaceClass ) { Object object = serviceMap . get ( interfaceClass . getName ( ) ) ; if ( object == null ) return null ; if ( object instanceof Object [ ] ) { return ( T [ ] ) object ; } else { Object array = Array . newInstance ( interfaceClass , 1 ) ; Array . set ( array , 0 , object ) ; return ( T [ ] ) array ; } }
Get a list of cached singleton objects from service map by interface class . If there is only one object in the serviceMap then construct the list with this only object .
15,767
public byte [ ] toByteArray ( ) { final byte [ ] b = new byte [ this . len ] ; if ( this . len > 0 ) { System . arraycopy ( this . array , 0 , b , 0 , this . len ) ; } return b ; }
Converts the content of this buffer to an array of bytes .
15,768
public String getLastPathSegment ( ) { if ( StringUtils . isBlank ( path ) ) { return StringUtils . EMPTY ; } String segment = path ; segment = StringUtils . substringAfterLast ( segment , "/" ) ; return segment ; }
Gets the last URL path segment without the query string . If there are segment to return an empty string will be returned instead .
15,769
public boolean isPortDefault ( ) { return ( PROTOCOL_HTTPS . equalsIgnoreCase ( protocol ) && port == DEFAULT_HTTPS_PORT ) || ( PROTOCOL_HTTP . equalsIgnoreCase ( protocol ) && port == DEFAULT_HTTP_PORT ) ; }
Whether this URL uses the default port for the protocol . The default port is 80 for http protocol and 443 for https . Other protocols are not supported and this method will always return false for them .
15,770
public static String toAbsolute ( String baseURL , String relativeURL ) { String relURL = relativeURL ; if ( relURL . startsWith ( "//" ) ) { return StringUtils . substringBefore ( baseURL , "//" ) + "//" + StringUtils . substringAfter ( relURL , "//" ) ; } if ( relURL . startsWith ( "/" ) ) { return getRoot ( baseURL ) + relURL ; } if ( relURL . startsWith ( "?" ) || relURL . startsWith ( "#" ) ) { return baseURL . replaceFirst ( "(.*?)([\\?\\#])(.*)" , "$1" ) + relURL ; } if ( ! relURL . contains ( "://" ) ) { String base = baseURL . replaceFirst ( "(.*?)([\\?\\#])(.*)" , "$1" ) ; if ( StringUtils . countMatches ( base , '/' ) > 2 ) { base = base . replaceFirst ( "(.*/)(.*)" , "$1" ) ; } if ( base . endsWith ( "/" ) ) { relURL = base + relURL ; } else { relURL = base + "/" + relURL ; } } return relURL ; }
Converts a relative URL to an absolute one based on the supplied base URL . The base URL is assumed to be a valid URL . Behavior is unexpected when base URL is invalid .
15,771
public static String generateRandomCodeVerifier ( SecureRandom entropySource , int entropyBytes ) { byte [ ] randomBytes = new byte [ entropyBytes ] ; entropySource . nextBytes ( randomBytes ) ; return Base64 . getUrlEncoder ( ) . withoutPadding ( ) . encodeToString ( randomBytes ) ; }
Generates a random code verifier string using the provided entropy source and the specified number of bytes of entropy .
15,772
public static void addProvidersToPathHandler ( PathResourceProvider [ ] pathResourceProviders , PathHandler pathHandler ) { if ( pathResourceProviders != null && pathResourceProviders . length > 0 ) { for ( PathResourceProvider pathResourceProvider : pathResourceProviders ) { if ( pathResourceProvider . isPrefixPath ( ) ) { pathHandler . addPrefixPath ( pathResourceProvider . getPath ( ) , new ResourceHandler ( pathResourceProvider . getResourceManager ( ) ) ) ; } else { pathHandler . addExactPath ( pathResourceProvider . getPath ( ) , new ResourceHandler ( pathResourceProvider . getResourceManager ( ) ) ) ; } } } }
Helper to add given PathResourceProviders to a PathHandler .
15,773
public static List < PredicatedHandler > getPredicatedHandlers ( PredicatedHandlersProvider [ ] predicatedHandlersProviders ) { List < PredicatedHandler > predicatedHandlers = new ArrayList < > ( ) ; if ( predicatedHandlersProviders != null && predicatedHandlersProviders . length > 0 ) { for ( PredicatedHandlersProvider predicatedHandlersProvider : predicatedHandlersProviders ) { predicatedHandlers . addAll ( predicatedHandlersProvider . getPredicatedHandlers ( ) ) ; } } return predicatedHandlers ; }
Helper for retrieving all PredicatedHandlers from the given list of PredicatedHandlersProviders .
15,774
public static boolean isResourcePath ( String requestPath , PathResourceProvider [ ] pathResourceProviders ) { boolean isResourcePath = false ; if ( pathResourceProviders != null && pathResourceProviders . length > 0 ) { for ( PathResourceProvider pathResourceProvider : pathResourceProviders ) { if ( ( pathResourceProvider . isPrefixPath ( ) && requestPath . startsWith ( pathResourceProvider . getPath ( ) ) ) || ( ! pathResourceProvider . isPrefixPath ( ) && requestPath . equals ( pathResourceProvider . getPath ( ) ) ) ) { isResourcePath = true ; } } } return isResourcePath ; }
Helper to check if a given requestPath could resolve to a PathResourceProvider .
15,775
public static Result < TokenResponse > getTokenResult ( TokenRequest tokenRequest , String envTag ) { final AtomicReference < Result < TokenResponse > > reference = new AtomicReference < > ( ) ; final Http2Client client = Http2Client . getInstance ( ) ; final CountDownLatch latch = new CountDownLatch ( 1 ) ; final ClientConnection connection ; try { if ( tokenRequest . getServerUrl ( ) != null ) { connection = client . connect ( new URI ( tokenRequest . getServerUrl ( ) ) , Http2Client . WORKER , Http2Client . SSL , Http2Client . BUFFER_POOL , tokenRequest . enableHttp2 ? OptionMap . create ( UndertowOptions . ENABLE_HTTP2 , true ) : OptionMap . EMPTY ) . get ( ) ; } else if ( tokenRequest . getServiceId ( ) != null ) { Cluster cluster = SingletonServiceFactory . getBean ( Cluster . class ) ; String url = cluster . serviceToUrl ( "https" , tokenRequest . getServiceId ( ) , envTag , null ) ; connection = client . connect ( new URI ( url ) , Http2Client . WORKER , Http2Client . SSL , Http2Client . BUFFER_POOL , tokenRequest . enableHttp2 ? OptionMap . create ( UndertowOptions . ENABLE_HTTP2 , true ) : OptionMap . EMPTY ) . get ( ) ; } else { logger . error ( "Error: both server_url and serviceId are not configured in client.yml for " + tokenRequest . getClass ( ) ) ; throw new ClientException ( "both server_url and serviceId are not configured in client.yml for " + tokenRequest . getClass ( ) ) ; } } catch ( Exception e ) { logger . error ( "cannot establish connection:" , e ) ; return Failure . of ( new Status ( ESTABLISH_CONNECTION_ERROR , tokenRequest . getServerUrl ( ) != null ? tokenRequest . getServerUrl ( ) : tokenRequest . getServiceId ( ) ) ) ; } try { IClientRequestComposable requestComposer = ClientRequestComposerProvider . getInstance ( ) . getComposer ( ClientRequestComposerProvider . ClientRequestComposers . CLIENT_CREDENTIAL_REQUEST_COMPOSER ) ; connection . getIoThread ( ) . execute ( new TokenRequestAction ( tokenRequest , requestComposer , connection , reference , latch ) ) ; latch . await ( 4 , TimeUnit . SECONDS ) ; } catch ( Exception e ) { logger . error ( "IOException: " , e ) ; return Failure . of ( new Status ( FAIL_TO_SEND_REQUEST ) ) ; } finally { IoUtils . safeClose ( connection ) ; } return reference . get ( ) == null ? Failure . of ( new Status ( GET_TOKEN_TIMEOUT ) ) : reference . get ( ) ; }
Get an access token from the token service . A Result of TokenResponse will be returned if the invocation is successfully . Otherwise a Result of Status will be returned .
15,776
public static String getKey ( KeyRequest keyRequest , String envTag ) throws ClientException { final Http2Client client = Http2Client . getInstance ( ) ; final CountDownLatch latch = new CountDownLatch ( 1 ) ; final ClientConnection connection ; try { if ( keyRequest . getServerUrl ( ) != null ) { connection = client . connect ( new URI ( keyRequest . getServerUrl ( ) ) , Http2Client . WORKER , Http2Client . SSL , Http2Client . BUFFER_POOL , keyRequest . enableHttp2 ? OptionMap . create ( UndertowOptions . ENABLE_HTTP2 , true ) : OptionMap . EMPTY ) . get ( ) ; } else if ( keyRequest . getServiceId ( ) != null ) { Cluster cluster = SingletonServiceFactory . getBean ( Cluster . class ) ; String url = cluster . serviceToUrl ( "https" , keyRequest . getServiceId ( ) , envTag , null ) ; connection = client . connect ( new URI ( url ) , Http2Client . WORKER , Http2Client . SSL , Http2Client . BUFFER_POOL , keyRequest . enableHttp2 ? OptionMap . create ( UndertowOptions . ENABLE_HTTP2 , true ) : OptionMap . EMPTY ) . get ( ) ; } else { logger . error ( "Error: both server_url and serviceId are not configured in client.yml for " + keyRequest . getClass ( ) ) ; throw new ClientException ( "both server_url and serviceId are not configured in client.yml for " + keyRequest . getClass ( ) ) ; } } catch ( Exception e ) { throw new ClientException ( e ) ; } final AtomicReference < ClientResponse > reference = new AtomicReference < > ( ) ; try { ClientRequest request = new ClientRequest ( ) . setPath ( keyRequest . getUri ( ) ) . setMethod ( Methods . GET ) ; if ( keyRequest . getClientId ( ) != null ) { request . getRequestHeaders ( ) . put ( Headers . AUTHORIZATION , getBasicAuthHeader ( keyRequest . getClientId ( ) , keyRequest . getClientSecret ( ) ) ) ; } request . getRequestHeaders ( ) . put ( Headers . HOST , "localhost" ) ; adjustNoChunkedEncoding ( request , "" ) ; connection . sendRequest ( request , client . createClientCallback ( reference , latch ) ) ; latch . await ( ) ; } catch ( Exception e ) { logger . error ( "Exception: " , e ) ; throw new ClientException ( e ) ; } finally { IoUtils . safeClose ( connection ) ; } return reference . get ( ) . getAttachment ( Http2Client . RESPONSE_BODY ) ; }
Get the certificate from key distribution service of OAuth 2 . 0 provider with the kid .
15,777
private static Result < Jwt > renewCCTokenSync ( final Jwt jwt ) { logger . trace ( "In renew window and token is already expired." ) ; if ( ! jwt . isRenewing ( ) || System . currentTimeMillis ( ) > jwt . getExpiredRetryTimeout ( ) ) { jwt . setRenewing ( true ) ; jwt . setEarlyRetryTimeout ( System . currentTimeMillis ( ) + Jwt . getExpiredRefreshRetryDelay ( ) ) ; Result < Jwt > result = getCCTokenRemotely ( jwt ) ; jwt . setRenewing ( false ) ; return result ; } else { if ( logger . isTraceEnabled ( ) ) logger . trace ( "Circuit breaker is tripped and not timeout yet!" ) ; return Failure . of ( new Status ( STATUS_CLIENT_CREDENTIALS_TOKEN_NOT_AVAILABLE ) ) ; } }
renew Client Credential token synchronously . When success will renew the Jwt jwt passed in . When fail will return Status code so that can be handled by caller .
15,778
private static void renewCCTokenAsync ( final Jwt jwt ) { logger . trace ( "In renew window but token is not expired yet." ) ; if ( ! jwt . isRenewing ( ) || System . currentTimeMillis ( ) > jwt . getEarlyRetryTimeout ( ) ) { jwt . setRenewing ( true ) ; jwt . setEarlyRetryTimeout ( System . currentTimeMillis ( ) + jwt . getEarlyRefreshRetryDelay ( ) ) ; logger . trace ( "Retrieve token async is called while token is not expired yet" ) ; ScheduledExecutorService executor = Executors . newSingleThreadScheduledExecutor ( ) ; executor . schedule ( ( ) -> { Result < Jwt > result = getCCTokenRemotely ( jwt ) ; if ( result . isFailure ( ) ) { logger . error ( "Async retrieve token error with status: {}" , result . getError ( ) . toString ( ) ) ; } jwt . setRenewing ( false ) ; } , 50 , TimeUnit . MILLISECONDS ) ; executor . shutdown ( ) ; } }
renew the given Jwt jwt asynchronously . When fail it will swallow the exception so no need return type to be handled by caller .
15,779
private static Result < Jwt > getCCTokenRemotely ( final Jwt jwt ) { TokenRequest tokenRequest = new ClientCredentialsRequest ( ) ; setScope ( tokenRequest , jwt ) ; Result < TokenResponse > result = OauthHelper . getTokenResult ( tokenRequest ) ; if ( result . isSuccess ( ) ) { TokenResponse tokenResponse = result . getResult ( ) ; jwt . setJwt ( tokenResponse . getAccessToken ( ) ) ; jwt . setExpire ( System . currentTimeMillis ( ) + tokenResponse . getExpiresIn ( ) * 1000 ) ; logger . info ( "Get client credentials token {} with expire_in {} seconds" , jwt , tokenResponse . getExpiresIn ( ) ) ; jwt . setScopes ( tokenResponse . getScope ( ) ) ; return Success . of ( jwt ) ; } else { logger . info ( "Get client credentials token fail with status: {}" , result . getError ( ) . toString ( ) ) ; return Failure . of ( result . getError ( ) ) ; } }
get Client Credential token from auth server
15,780
private static String escapeXml ( String nonEscapedXmlStr ) { StringBuilder escapedXML = new StringBuilder ( ) ; for ( int i = 0 ; i < nonEscapedXmlStr . length ( ) ; i ++ ) { char c = nonEscapedXmlStr . charAt ( i ) ; switch ( c ) { case '<' : escapedXML . append ( "&lt;" ) ; break ; case '>' : escapedXML . append ( "&gt;" ) ; break ; case '\"' : escapedXML . append ( "&quot;" ) ; break ; case '&' : escapedXML . append ( "&amp;" ) ; break ; case '\'' : escapedXML . append ( "&apos;" ) ; break ; default : if ( c > 0x7e ) { escapedXML . append ( "&#" + ( ( int ) c ) + ";" ) ; } else { escapedXML . append ( c ) ; } } } return escapedXML . toString ( ) ; }
Instead of including a large library just for escaping xml using this util . it should be used in very rare cases because the server should not return xml format message
15,781
public static void adjustNoChunkedEncoding ( ClientRequest request , String requestBody ) { String fixedLengthString = request . getRequestHeaders ( ) . getFirst ( Headers . CONTENT_LENGTH ) ; String transferEncodingString = request . getRequestHeaders ( ) . getLast ( Headers . TRANSFER_ENCODING ) ; if ( transferEncodingString != null ) { request . getRequestHeaders ( ) . remove ( Headers . TRANSFER_ENCODING ) ; } if ( fixedLengthString != null && Long . parseLong ( fixedLengthString ) > 0 ) { return ; } if ( ! StringUtils . isEmpty ( requestBody ) ) { long contentLength = requestBody . getBytes ( UTF_8 ) . length ; request . getRequestHeaders ( ) . put ( Headers . CONTENT_LENGTH , contentLength ) ; } }
this method is to support sending a server which doesn t support chunked transfer encoding .
15,782
private void attachFormDataBody ( final HttpServerExchange exchange ) throws IOException { Object data ; FormParserFactory formParserFactory = FormParserFactory . builder ( ) . build ( ) ; FormDataParser parser = formParserFactory . createParser ( exchange ) ; if ( parser != null ) { FormData formData = parser . parseBlocking ( ) ; data = BodyConverter . convert ( formData ) ; exchange . putAttachment ( REQUEST_BODY , data ) ; } }
Method used to parse the body into FormData and attach it into exchange
15,783
private void attachJsonBody ( final HttpServerExchange exchange , String string ) throws IOException { Object body ; if ( string != null ) { string = string . trim ( ) ; if ( string . startsWith ( "{" ) ) { body = Config . getInstance ( ) . getMapper ( ) . readValue ( string , new TypeReference < Map < String , Object > > ( ) { } ) ; } else if ( string . startsWith ( "[" ) ) { body = Config . getInstance ( ) . getMapper ( ) . readValue ( string , new TypeReference < List < Object > > ( ) { } ) ; } else { setExchangeStatus ( exchange , CONTENT_TYPE_MISMATCH , "application/json" ) ; return ; } exchange . putAttachment ( REQUEST_BODY , body ) ; } }
Method used to parse the body into a Map or a List and attach it into exchange
15,784
public static String maskString ( String input , String key ) { String output = input ; Map < String , Object > stringConfig = ( Map < String , Object > ) config . get ( MASK_TYPE_STRING ) ; if ( stringConfig != null ) { Map < String , Object > keyConfig = ( Map < String , Object > ) stringConfig . get ( key ) ; if ( keyConfig != null ) { Set < String > patterns = keyConfig . keySet ( ) ; for ( String pattern : patterns ) { output = output . replaceAll ( pattern , ( String ) keyConfig . get ( pattern ) ) ; } } } return output ; }
Mask the input string with a list of patterns indexed by key in string section in mask . json This is usually used to mask header values query parameters and uri parameters
15,785
public static String maskJson ( String input , String key ) { DocumentContext ctx = JsonPath . parse ( input ) ; return maskJson ( ctx , key ) ; }
Replace values in JSON using json path
15,786
public void skipWhiteSpace ( final CharSequence buf , final ParserCursor cursor ) { Args . notNull ( buf , "Char sequence" ) ; Args . notNull ( cursor , "Parser cursor" ) ; int pos = cursor . getPos ( ) ; final int indexFrom = cursor . getPos ( ) ; final int indexTo = cursor . getUpperBound ( ) ; for ( int i = indexFrom ; i < indexTo ; i ++ ) { final char current = buf . charAt ( i ) ; if ( ! isWhitespace ( current ) ) { break ; } pos ++ ; } cursor . updatePos ( pos ) ; }
Skips semantically insignificant whitespace characters and moves the cursor to the closest non - whitespace character .
15,787
public void copyContent ( final CharSequence buf , final ParserCursor cursor , final BitSet delimiters , final StringBuilder dst ) { Args . notNull ( buf , "Char sequence" ) ; Args . notNull ( cursor , "Parser cursor" ) ; Args . notNull ( dst , "String builder" ) ; int pos = cursor . getPos ( ) ; final int indexFrom = cursor . getPos ( ) ; final int indexTo = cursor . getUpperBound ( ) ; for ( int i = indexFrom ; i < indexTo ; i ++ ) { final char current = buf . charAt ( i ) ; if ( ( delimiters != null && delimiters . get ( current ) ) || isWhitespace ( current ) ) { break ; } pos ++ ; dst . append ( current ) ; } cursor . updatePos ( pos ) ; }
Transfers content into the destination buffer until a whitespace character or any of the given delimiters is encountered .
15,788
public void copyQuotedContent ( final CharSequence buf , final ParserCursor cursor , final StringBuilder dst ) { Args . notNull ( buf , "Char sequence" ) ; Args . notNull ( cursor , "Parser cursor" ) ; Args . notNull ( dst , "String builder" ) ; if ( cursor . atEnd ( ) ) { return ; } int pos = cursor . getPos ( ) ; int indexFrom = cursor . getPos ( ) ; final int indexTo = cursor . getUpperBound ( ) ; char current = buf . charAt ( pos ) ; if ( current != DQUOTE ) { return ; } pos ++ ; indexFrom ++ ; boolean escaped = false ; for ( int i = indexFrom ; i < indexTo ; i ++ , pos ++ ) { current = buf . charAt ( i ) ; if ( escaped ) { if ( current != DQUOTE && current != ESCAPE ) { dst . append ( ESCAPE ) ; } dst . append ( current ) ; escaped = false ; } else { if ( current == DQUOTE ) { pos ++ ; break ; } if ( current == ESCAPE ) { escaped = true ; } else if ( current != CR && current != LF ) { dst . append ( current ) ; } } } cursor . updatePos ( pos ) ; }
Transfers content enclosed with quote marks into the destination buffer .
15,789
static void logResult ( Map < String , Object > result , DumpConfig config ) { Consumer < String > loggerFunc = getLoggerFuncBasedOnLevel ( config . getLogLevel ( ) ) ; if ( config . isUseJson ( ) ) { logResultUsingJson ( result , loggerFunc ) ; } else { int startLevel = - 1 ; StringBuilder sb = new StringBuilder ( "Http request/response information:" ) ; _logResult ( result , startLevel , config . getIndentSize ( ) , sb ) ; loggerFunc . accept ( sb . toString ( ) ) ; } }
A help method to log result pojo
15,790
private static < T > void _logResult ( T result , int level , int indentSize , StringBuilder info ) { if ( result instanceof Map ) { level += 1 ; int finalLevel = level ; ( ( Map ) result ) . forEach ( ( k , v ) -> { info . append ( "\n" ) ; info . append ( getTabBasedOnLevel ( finalLevel , indentSize ) ) . append ( k . toString ( ) ) . append ( ":" ) ; _logResult ( v , finalLevel , indentSize , info ) ; } ) ; } else if ( result instanceof List ) { int finalLevel = level ; ( ( List ) result ) . forEach ( element -> _logResult ( element , finalLevel , indentSize , info ) ) ; } else if ( result instanceof String ) { info . append ( " " ) . append ( result ) ; } else if ( result != null ) { try { logger . warn ( getTabBasedOnLevel ( level , indentSize ) + "{}" , result ) ; } catch ( Exception e ) { logger . error ( "Cannot handle this type: {}" , result . getClass ( ) . getTypeName ( ) ) ; } } }
this method actually append result to result string
15,791
private static String getTabBasedOnLevel ( int level , int indentSize ) { StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < level ; i ++ ) { for ( int j = 0 ; j < indentSize ; j ++ ) { sb . append ( " " ) ; } } return sb . toString ( ) ; }
calculate indent for formatting
15,792
private URL removeUnnecessaryParmas ( URL url ) { url . getParameters ( ) . remove ( URLParamType . codec . getName ( ) ) ; return url ; }
client doesn t need to know codec .
15,793
public void dumpResponse ( Map < String , Object > result ) { this . statusCodeResult = String . valueOf ( exchange . getStatusCode ( ) ) ; this . putDumpInfoTo ( result ) ; }
impl of dumping response status code to result
15,794
protected void putDumpInfoTo ( Map < String , Object > result ) { if ( StringUtils . isNotBlank ( this . statusCodeResult ) ) { result . put ( DumpConstants . STATUS_CODE , this . statusCodeResult ) ; } }
put this . statusCodeResult to result
15,795
public static String getUUID ( ) { UUID id = UUID . randomUUID ( ) ; ByteBuffer bb = ByteBuffer . wrap ( new byte [ 16 ] ) ; bb . putLong ( id . getMostSignificantBits ( ) ) ; bb . putLong ( id . getLeastSignificantBits ( ) ) ; return Base64 . encodeBase64URLSafeString ( bb . array ( ) ) ; }
Generate UUID across the entire app and it is used for correlationId .
15,796
public static String quote ( final String value ) { if ( value == null ) { return null ; } String result = value ; if ( ! result . startsWith ( "\"" ) ) { result = "\"" + result ; } if ( ! result . endsWith ( "\"" ) ) { result = result + "\"" ; } return result ; }
Quote the given string if needed
15,797
public String serviceToUrl ( String protocol , String serviceId , String tag , String requestKey ) { URL url = loadBalance . select ( discovery ( protocol , serviceId , tag ) , requestKey ) ; if ( logger . isDebugEnabled ( ) ) logger . debug ( "final url after load balance = " + url ) ; return protocol + "://" + url . getHost ( ) + ":" + url . getPort ( ) ; }
Implement serviceToUrl with client side service discovery .
15,798
private String getServerTlsFingerPrint ( ) { String fingerPrint = null ; Map < String , Object > serverConfig = Config . getInstance ( ) . getJsonMapConfigNoCache ( "server" ) ; Map < String , Object > secretConfig = Config . getInstance ( ) . getJsonMapConfigNoCache ( "secret" ) ; String keystoreName = ( String ) serverConfig . get ( "keystoreName" ) ; String serverKeystorePass = ( String ) secretConfig . get ( "serverKeystorePass" ) ; if ( keystoreName != null ) { try ( InputStream stream = Config . getInstance ( ) . getInputStreamFromFile ( keystoreName ) ) { KeyStore loadedKeystore = KeyStore . getInstance ( "JKS" ) ; loadedKeystore . load ( stream , serverKeystorePass . toCharArray ( ) ) ; X509Certificate cert = ( X509Certificate ) loadedKeystore . getCertificate ( "server" ) ; if ( cert != null ) { fingerPrint = FingerPrintUtil . getCertFingerPrint ( cert ) ; } else { logger . error ( "Unable to find the certificate with alias name as server in the keystore" ) ; } } catch ( Exception e ) { logger . error ( "Unable to load server keystore " , e ) ; } } return fingerPrint ; }
We can get it from server module but we don t want mutual dependency . So get it from config and keystore directly
15,799
private void doCustomServerIdentityCheck ( X509Certificate cert ) throws CertificateException { if ( EndpointIdentificationAlgorithm . APIS == identityAlg ) { APINameChecker . verifyAndThrow ( trustedNameSet , cert ) ; } }
check server identify as per tls . trustedNames in client . yml .