Input: The implementation of { @link ControlledFragmentHandler } that reassembles and forwards whole messages . [CODESPLIT] public Action onFragment ( final DirectBuffer buffer , final int offset , final int length , final Header header ) { final byte flags = header . flags ( ) ; Action action = Action . CONTINUE ; if ( ( flags & UNFRAGMENTED ) == UNFRAGMENTED ) { action = delegate . onFragment ( buffer , offset , length , header ) ; } else { if ( ( flags & BEGIN_FRAG_FLAG ) == BEGIN_FRAG_FLAG ) { builder . reset ( ) . append ( buffer , offset , length ) ; } else { final int limit = builder . limit ( ) ; builder . append ( buffer , offset , length ) ; if ( ( flags & END_FRAG_FLAG ) == END_FRAG_FLAG ) { final int msgLength = builder . limit ( ) ; action = delegate . onFragment ( builder . buffer ( ) , 0 , msgLength , header ) ; if ( Action . ABORT == action ) { builder . limit ( limit ) ; } else { builder . reset ( ) ; } } } } return action ; }


Input: Take a snapshot of all the counters and group them by streams . [CODESPLIT] public Map < StreamCompositeKey , List < StreamPosition > > snapshot ( ) { final Map < StreamCompositeKey , List < StreamPosition > > streams = new HashMap <> ( ) ; counters . forEach ( ( counterId , typeId , keyBuffer , label ) -> { if ( ( typeId >= PUBLISHER_LIMIT_TYPE_ID && typeId <= RECEIVER_POS_TYPE_ID ) || typeId == SENDER_LIMIT_TYPE_ID || typeId == PER_IMAGE_TYPE_ID || typeId == PUBLISHER_POS_TYPE_ID ) { final StreamCompositeKey key = new StreamCompositeKey ( keyBuffer . getInt ( SESSION_ID_OFFSET ) , keyBuffer . getInt ( STREAM_ID_OFFSET ) , keyBuffer . getStringAscii ( CHANNEL_OFFSET ) ) ; final StreamPosition position = new StreamPosition ( keyBuffer . getLong ( REGISTRATION_ID_OFFSET ) , counters . getCounterValue ( counterId ) , typeId ) ; streams . computeIfAbsent ( key , ( ignore ) - > new ArrayList <> ( ) ) . add ( position ) ; } } ) ; return streams ; }


Input: Print a snapshot of the stream positions to a { @link PrintStream } . <p > Each stream will be printed on its own line . [CODESPLIT] public int print ( final PrintStream out ) { final Map < StreamCompositeKey , List < StreamPosition > > streams = snapshot ( ) ; final StringBuilder builder = new StringBuilder ( ) ; for ( final Map . Entry < StreamCompositeKey , List < StreamPosition > > entry : streams . entrySet ( ) ) { builder . setLength ( 0 ) ; final StreamCompositeKey key = entry . getKey ( ) ; builder . append ( "sessionId=" ) . append ( key . sessionId ( ) ) . append ( " streamId=" ) . append ( key . streamId ( ) ) . append ( " channel=" ) . append ( key . channel ( ) ) . append ( " :" ) ; for ( final StreamPosition streamPosition : entry . getValue ( ) ) { builder . append ( ' ' ) . append ( labelName ( streamPosition . typeId ( ) ) ) . append ( ' ' ) . append ( streamPosition . id ( ) ) . append ( ' ' ) . append ( streamPosition . value ( ) ) ; } out . println ( builder ) ; } return streams . size ( ) ; }


Input: Generate a new randomized delay value in the units of { @code maxBackoffT }} . [CODESPLIT] public double generateNewOptimalDelay ( ) { final double x = uniformRandom ( randMax ) + baseX ; return constantT * Math . log ( x * factorT ) ; }


Input: { [CODESPLIT] public long onStatusMessage ( final StatusMessageFlyweight flyweight , final InetSocketAddress receiverAddress , final long senderLimit , final int initialTermId , final int positionBitsToShift , final long timeNs ) { final long position = computePosition ( flyweight . consumptionTermId ( ) , flyweight . consumptionTermOffset ( ) , positionBitsToShift , initialTermId ) ; lastPosition = Math . max ( lastPosition , position ) ; timeOfLastStatusMessage = timeNs ; return Math . max ( senderLimit , position + flyweight . receiverWindowLength ( ) ) ; }


Input: { [CODESPLIT] public long onIdle ( final long timeNs , final long senderLimit , final long senderPosition , final boolean isEos ) { if ( isEos && shouldLinger ) { if ( lastPosition >= senderPosition || ( ( timeOfLastStatusMessage + RECEIVER_TIMEOUT_NS ) - timeNs < 0 ) ) { shouldLinger = false ; } } return senderLimit ; }


Input: Reset the poller to dispatch the descriptors returned from a query . [CODESPLIT] public void reset ( final long correlationId , final int recordCount , final RecordingDescriptorConsumer consumer ) { this . correlationId = correlationId ; this . consumer = consumer ; this . remainingRecordCount = recordCount ; isDispatchComplete = false ; }


Input: Read a { @link LossReport } contained in the buffer . This can be done concurrently . [CODESPLIT] public static int read ( final AtomicBuffer buffer , final EntryConsumer entryConsumer ) { final int capacity = buffer . capacity ( ) ; int recordsRead = 0 ; int offset = 0 ; while ( offset < capacity ) { final long observationCount = buffer . getLongVolatile ( offset + OBSERVATION_COUNT_OFFSET ) ; if ( observationCount <= 0 ) { break ; } ++ recordsRead ; final String channel = buffer . getStringAscii ( offset + CHANNEL_OFFSET ) ; final String source = buffer . getStringAscii ( offset + CHANNEL_OFFSET + SIZE_OF_INT + channel . length ( ) ) ; entryConsumer . accept ( observationCount , buffer . getLong ( offset + TOTAL_BYTES_LOST_OFFSET ) , buffer . getLong ( offset + FIRST_OBSERVATION_OFFSET ) , buffer . getLong ( offset + LAST_OBSERVATION_OFFSET ) , buffer . getInt ( offset + SESSION_ID_OFFSET ) , buffer . getInt ( offset + STREAM_ID_OFFSET ) , channel , source ) ; final int recordLength = CHANNEL_OFFSET + ( SIZE_OF_INT * 2 ) + channel . length ( ) + source . length ( ) ; offset += BitUtil . align ( recordLength , ENTRY_ALIGNMENT ) ; } return recordsRead ; }


Input: Return an initialised default Data Frame Header . [CODESPLIT] public static UnsafeBuffer createDefaultHeader ( final int sessionId , final int streamId , final int termId ) { final UnsafeBuffer buffer = new UnsafeBuffer ( BufferUtil . allocateDirectAligned ( HEADER_LENGTH , CACHE_LINE_LENGTH ) ) ; buffer . putByte ( VERSION_FIELD_OFFSET , CURRENT_VERSION ) ; buffer . putByte ( FLAGS_FIELD_OFFSET , ( byte ) BEGIN_AND_END_FLAGS ) ; buffer . putShort ( TYPE_FIELD_OFFSET , ( short ) HDR_TYPE_DATA , LITTLE_ENDIAN ) ; buffer . putInt ( SESSION_ID_FIELD_OFFSET , sessionId , LITTLE_ENDIAN ) ; buffer . putInt ( STREAM_ID_FIELD_OFFSET , streamId , LITTLE_ENDIAN ) ; buffer . putInt ( TERM_ID_FIELD_OFFSET , termId , LITTLE_ENDIAN ) ; buffer . putLong ( RESERVED_VALUE_OFFSET , DEFAULT_RESERVE_VALUE ) ; return buffer ; }


Input: Fill the key buffer . [CODESPLIT] public CounterMessageFlyweight keyBuffer ( final DirectBuffer keyBuffer , final int keyOffset , final int keyLength ) { buffer . putInt ( KEY_LENGTH_OFFSET , keyLength ) ; if ( null != keyBuffer && keyLength > 0 ) { buffer . putBytes ( keyBufferOffset ( ) , keyBuffer , keyOffset , keyLength ) ; } return this ; }


Input: Fill the label buffer . [CODESPLIT] public CounterMessageFlyweight labelBuffer ( final DirectBuffer labelBuffer , final int labelOffset , final int labelLength ) { buffer . putInt ( labelOffset ( ) , labelLength ) ; buffer . putBytes ( labelBufferOffset ( ) , labelBuffer , labelOffset , labelLength ) ; return this ; }


Input: Poll the { @link Image } s under the subscription for available message fragments . <p > Each fragment read will be a whole message if it is under MTU length . If larger than MTU then it will come as a series of fragments ordered within a session . <p > To assemble messages that span multiple fragments then use { @link FragmentAssembler } . [CODESPLIT] public int poll ( final FragmentHandler fragmentHandler , final int fragmentLimit ) { final Image [ ] images = this . images ; final int length = images . length ; int fragmentsRead = 0 ; int startingIndex = roundRobinIndex ++ ; if ( startingIndex >= length ) { roundRobinIndex = startingIndex = 0 ; } for ( int i = startingIndex ; i < length && fragmentsRead < fragmentLimit ; i ++ ) { fragmentsRead += images [ i ] . poll ( fragmentHandler , fragmentLimit - fragmentsRead ) ; } for ( int i = 0 ; i < startingIndex && fragmentsRead < fragmentLimit ; i ++ ) { fragmentsRead += images [ i ] . poll ( fragmentHandler , fragmentLimit - fragmentsRead ) ; } return fragmentsRead ; }


Input: Poll in a controlled manner the { @link Image } s under the subscription for available message fragments . Control is applied to fragments in the stream . If more fragments can be read on another stream they will even if BREAK or ABORT is returned from the fragment handler . <p > Each fragment read will be a whole message if it is under MTU length . If larger than MTU then it will come as a series of fragments ordered within a session . <p > To assemble messages that span multiple fragments then use { @link ControlledFragmentAssembler } . [CODESPLIT] public int controlledPoll ( final ControlledFragmentHandler fragmentHandler , final int fragmentLimit ) { final Image [ ] images = this . images ; final int length = images . length ; int fragmentsRead = 0 ; int startingIndex = roundRobinIndex ++ ; if ( startingIndex >= length ) { roundRobinIndex = startingIndex = 0 ; } for ( int i = startingIndex ; i < length && fragmentsRead < fragmentLimit ; i ++ ) { fragmentsRead += images [ i ] . controlledPoll ( fragmentHandler , fragmentLimit - fragmentsRead ) ; } for ( int i = 0 ; i < startingIndex && fragmentsRead < fragmentLimit ; i ++ ) { fragmentsRead += images [ i ] . controlledPoll ( fragmentHandler , fragmentLimit - fragmentsRead ) ; } return fragmentsRead ; }


Input: Poll the { @link Image } s under the subscription for available message fragments in blocks . <p > This method is useful for operations like bulk archiving and messaging indexing . [CODESPLIT] public long blockPoll ( final BlockHandler blockHandler , final int blockLengthLimit ) { long bytesConsumed = 0 ; for ( final Image image : images ) { bytesConsumed += image . blockPoll ( blockHandler , blockLengthLimit ) ; } return bytesConsumed ; }


Input: Poll the { @link Image } s under the subscription for available message fragments in blocks . <p > This method is useful for operations like bulk archiving a stream to file . [CODESPLIT] public long rawPoll ( final RawBlockHandler rawBlockHandler , final int blockLengthLimit ) { long bytesConsumed = 0 ; for ( final Image image : images ) { bytesConsumed += image . rawPoll ( rawBlockHandler , blockLengthLimit ) ; } return bytesConsumed ; }


Input: Return the { @link Image } associated with the given sessionId . [CODESPLIT] public Image imageBySessionId ( final int sessionId ) { Image result = null ; for ( final Image image : images ) { if ( sessionId == image . sessionId ( ) ) { result = image ; break ; } } return result ; }


Input: Iterate over the { @link Image } s for this subscription . [CODESPLIT] public void forEachImage ( final Consumer < Image > consumer ) { for ( final Image image : images ) { consumer . accept ( image ) ; } }


Input: Launch a new { @link ArchivingMediaDriver } with provided contexts . [CODESPLIT] public static ArchivingMediaDriver launch ( final MediaDriver . Context driverCtx , final Archive . Context archiveCtx ) { final MediaDriver driver = MediaDriver . launch ( driverCtx ) ; final Archive archive = Archive . launch ( archiveCtx . mediaDriverAgentInvoker ( driver . sharedAgentInvoker ( ) ) . errorHandler ( driverCtx . errorHandler ( ) ) . errorCounter ( driverCtx . systemCounters ( ) . get ( SystemCounterDescriptor . ERRORS ) ) ) ; return new ArchivingMediaDriver ( driver , archive ) ; }


Input: /////////////////////////////////////////////////////////// [CODESPLIT] public static boolean originalChannelContains ( final RecordingDescriptorDecoder descriptorDecoder , final byte [ ] channelFragment ) { final int fragmentLength = channelFragment . length ; if ( fragmentLength == 0 ) { return true ; } final int limit = descriptorDecoder . limit ( ) ; final int strippedChannelLength = descriptorDecoder . strippedChannelLength ( ) ; final int originalChannelOffset = limit + RecordingDescriptorDecoder . strippedChannelHeaderLength ( ) + strippedChannelLength ; descriptorDecoder . limit ( originalChannelOffset ) ; final int channelLength = descriptorDecoder . originalChannelLength ( ) ; descriptorDecoder . limit ( limit ) ; final DirectBuffer buffer = descriptorDecoder . buffer ( ) ; int offset = descriptorDecoder . offset ( ) + descriptorDecoder . sbeBlockLength ( ) + RecordingDescriptorDecoder . strippedChannelHeaderLength ( ) + strippedChannelLength + RecordingDescriptorDecoder . originalChannelHeaderLength ( ) ; nextChar : for ( int end = offset + ( channelLength - fragmentLength ) ; offset <= end ; offset ++ ) { for ( int i = 0 ; i < fragmentLength ; i ++ ) { if ( buffer . getByte ( offset + i ) != channelFragment [ i ] ) { continue nextChar ; } } return true ; } return false ; }


Input: On catalog load we verify entries are in coherent state and attempt to recover entries data where untimely termination of recording has resulted in an unaccounted for stopPosition / stopTimestamp . This operation may be expensive for large catalogs . [CODESPLIT] private void refreshCatalog ( final boolean fixOnRefresh ) { if ( fixOnRefresh ) { forEach ( this :: refreshAndFixDescriptor ) ; } else { forEach ( ( ( headerEncoder , headerDecoder , descriptorEncoder , descriptorDecoder ) -> nextRecordingId ++ ) ) ; } }


Input: Claim length of a the term buffer for writing in the message with zero copy semantics . [CODESPLIT] public int claim ( final HeaderWriter header , final int length , final BufferClaim bufferClaim , final int activeTermId ) { final int frameLength = length + HEADER_LENGTH ; final int alignedLength = align ( frameLength , FRAME_ALIGNMENT ) ; final UnsafeBuffer termBuffer = this . termBuffer ; final int termLength = termBuffer . capacity ( ) ; final long rawTail = getAndAddRawTail ( alignedLength ) ; final int termId = termId ( rawTail ) ; final long termOffset = rawTail & 0xFFFF_FFFF  L ; checkTerm ( activeTermId , termId ) ; long resultingOffset = termOffset + alignedLength ; if ( resultingOffset > termLength ) { resultingOffset = handleEndOfLogCondition ( termBuffer , termOffset , header , termLength , termId ) ; } else { final int frameOffset = ( int ) termOffset ; header . write ( termBuffer , frameOffset , frameLength , termId ) ; bufferClaim . wrap ( termBuffer , frameOffset , frameLength ) ; } return ( int ) resultingOffset ; }


Input: Append an unfragmented message to the the term buffer . [CODESPLIT] public int appendUnfragmentedMessage ( final HeaderWriter header , final DirectBuffer bufferOne , final int offsetOne , final int lengthOne , final DirectBuffer bufferTwo , final int offsetTwo , final int lengthTwo , final ReservedValueSupplier reservedValueSupplier , final int activeTermId ) { final int frameLength = lengthOne + lengthTwo + HEADER_LENGTH ; final int alignedLength = align ( frameLength , FRAME_ALIGNMENT ) ; final UnsafeBuffer termBuffer = this . termBuffer ; final int termLength = termBuffer . capacity ( ) ; final long rawTail = getAndAddRawTail ( alignedLength ) ; final int termId = termId ( rawTail ) ; final long termOffset = rawTail & 0xFFFF_FFFF  L ; checkTerm ( activeTermId , termId ) ; long resultingOffset = termOffset + alignedLength ; if ( resultingOffset > termLength ) { resultingOffset = handleEndOfLogCondition ( termBuffer , termOffset , header , termLength , termId ) ; } else { final int frameOffset = ( int ) termOffset ; header . write ( termBuffer , frameOffset , frameLength , termId ) ; termBuffer . putBytes ( frameOffset + HEADER_LENGTH , bufferOne , offsetOne , lengthOne ) ; termBuffer . putBytes ( frameOffset + HEADER_LENGTH + lengthOne , bufferTwo , offsetTwo , lengthTwo ) ; if ( null != reservedValueSupplier ) { final long reservedValue = reservedValueSupplier . get ( termBuffer , frameOffset , frameLength ) ; termBuffer . putLong ( frameOffset + RESERVED_VALUE_OFFSET , reservedValue , LITTLE_ENDIAN ) ; } frameLengthOrdered ( termBuffer , frameOffset , frameLength ) ; } return ( int ) resultingOffset ; }


Input: Append an unfragmented message to the the term buffer . [CODESPLIT] public int appendUnfragmentedMessage ( final HeaderWriter header , final DirectBuffer buffer , final int offset , final int length , final ReservedValueSupplier reservedValueSupplier , final int activeTermId ) { final int frameLength = length + HEADER_LENGTH ; final int alignedLength = align ( frameLength , FRAME_ALIGNMENT ) ; final UnsafeBuffer termBuffer = this . termBuffer ; final int termLength = termBuffer . capacity ( ) ; final long rawTail = getAndAddRawTail ( alignedLength ) ; final int termId = termId ( rawTail ) ; final long termOffset = rawTail & 0xFFFF_FFFF  L ; checkTerm ( activeTermId , termId ) ; long resultingOffset = termOffset + alignedLength ; if ( resultingOffset > termLength ) { resultingOffset = handleEndOfLogCondition ( termBuffer , termOffset , header , termLength , termId ) ; } else { final int frameOffset = ( int ) termOffset ; header . write ( termBuffer , frameOffset , frameLength , termId ) ; termBuffer . putBytes ( frameOffset + HEADER_LENGTH , buffer , offset , length ) ; if ( null != reservedValueSupplier ) { final long reservedValue = reservedValueSupplier . get ( termBuffer , frameOffset , frameLength ) ; termBuffer . putLong ( frameOffset + RESERVED_VALUE_OFFSET , reservedValue , LITTLE_ENDIAN ) ; } frameLengthOrdered ( termBuffer , frameOffset , frameLength ) ; } return ( int ) resultingOffset ; }


Input: Append a fragmented message to the the term buffer . The message will be split up into fragments of MTU length minus header . [CODESPLIT] public int appendFragmentedMessage ( final HeaderWriter header , final DirectBuffer bufferOne , final int offsetOne , final int lengthOne , final DirectBuffer bufferTwo , final int offsetTwo , final int lengthTwo , final int maxPayloadLength , final ReservedValueSupplier reservedValueSupplier , final int activeTermId ) { final int length = lengthOne + lengthTwo ; final int numMaxPayloads = length / maxPayloadLength ; final int remainingPayload = length % maxPayloadLength ; final int lastFrameLength = remainingPayload > 0 ? align ( remainingPayload + HEADER_LENGTH , FRAME_ALIGNMENT ) : 0 ; final int requiredLength = ( numMaxPayloads * ( maxPayloadLength + HEADER_LENGTH ) ) + lastFrameLength ; final UnsafeBuffer termBuffer = this . termBuffer ; final int termLength = termBuffer . capacity ( ) ; final long rawTail = getAndAddRawTail ( requiredLength ) ; final int termId = termId ( rawTail ) ; final long termOffset = rawTail & 0xFFFF_FFFF  L ; checkTerm ( activeTermId , termId ) ; long resultingOffset = termOffset + requiredLength ; if ( resultingOffset > termLength ) { resultingOffset = handleEndOfLogCondition ( termBuffer , termOffset , header , termLength , termId ) ; } else { int frameOffset = ( int ) termOffset ; byte flags = BEGIN_FRAG_FLAG ; int remaining = length ; int positionOne = 0 ; int positionTwo = 0 ; do { final int bytesToWrite = Math . min ( remaining , maxPayloadLength ) ; final int frameLength = bytesToWrite + HEADER_LENGTH ; final int alignedLength = align ( frameLength , FRAME_ALIGNMENT ) ; header . write ( termBuffer , frameOffset , frameLength , termId ) ; int bytesWritten = 0 ; int payloadOffset = frameOffset + HEADER_LENGTH ; do { final int remainingOne = lengthOne - positionOne ; if ( remainingOne > 0 ) { final int numBytes = Math . min ( bytesToWrite - bytesWritten , remainingOne ) ; termBuffer . putBytes ( payloadOffset , bufferOne , offsetOne + positionOne , numBytes ) ; bytesWritten += numBytes ; payloadOffset += numBytes ; positionOne += numBytes ; } else { final int numBytes = Math . min ( bytesToWrite - bytesWritten , lengthTwo - positionTwo ) ; termBuffer . putBytes ( payloadOffset , bufferTwo , offsetTwo + positionTwo , numBytes ) ; bytesWritten += numBytes ; payloadOffset += numBytes ; positionTwo += numBytes ; } } while ( bytesWritten < bytesToWrite ) ; if ( remaining <= maxPayloadLength ) { flags |= END_FRAG_FLAG ; } frameFlags ( termBuffer , frameOffset , flags ) ; if ( null != reservedValueSupplier ) { final long reservedValue = reservedValueSupplier . get ( termBuffer , frameOffset , frameLength ) ; termBuffer . putLong ( frameOffset + RESERVED_VALUE_OFFSET , reservedValue , LITTLE_ENDIAN ) ; } frameLengthOrdered ( termBuffer , frameOffset , frameLength ) ; flags = 0 ; frameOffset += alignedLength ; remaining -= bytesToWrite ; } while ( remaining > 0 ) ; } return ( int ) resultingOffset ; }


Input: Connect to an archive on its control interface providing the response stream details . [CODESPLIT] public boolean connect ( final String responseChannel , final int responseStreamId , final long correlationId ) { connectRequestEncoder . wrapAndApplyHeader ( buffer , 0 , messageHeaderEncoder ) . correlationId ( correlationId ) . responseStreamId ( responseStreamId ) . version ( AeronArchive . Configuration . SEMANTIC_VERSION ) . responseChannel ( responseChannel ) ; return offerWithTimeout ( connectRequestEncoder . encodedLength ( ) , null ) ; }


Input: Try Connect to an archive on its control interface providing the response stream details . Only one attempt will be made to offer the request . [CODESPLIT] public boolean tryConnect ( final String responseChannel , final int responseStreamId , final long correlationId ) { connectRequestEncoder . wrapAndApplyHeader ( buffer , 0 , messageHeaderEncoder ) . correlationId ( correlationId ) . responseStreamId ( responseStreamId ) . version ( AeronArchive . Configuration . SEMANTIC_VERSION ) . responseChannel ( responseChannel ) ; final int length = MessageHeaderEncoder . ENCODED_LENGTH + connectRequestEncoder . encodedLength ( ) ; return publication . offer ( buffer , 0 , length ) > 0 ; }


Input: Close this control session with the archive . [CODESPLIT] public boolean closeSession ( final long controlSessionId ) { closeSessionRequestEncoder . wrapAndApplyHeader ( buffer , 0 , messageHeaderEncoder ) . controlSessionId ( controlSessionId ) ; return offer ( closeSessionRequestEncoder . encodedLength ( ) ) ; }


Input: Start recording streams for a given channel and stream id pairing . [CODESPLIT] public boolean startRecording ( final String channel , final int streamId , final SourceLocation sourceLocation , final long correlationId , final long controlSessionId ) { startRecordingRequestEncoder . wrapAndApplyHeader ( buffer , 0 , messageHeaderEncoder ) . controlSessionId ( controlSessionId ) . correlationId ( correlationId ) . streamId ( streamId ) . sourceLocation ( sourceLocation ) . channel ( channel ) ; return offer ( startRecordingRequestEncoder . encodedLength ( ) ) ; }


Input: Stop an active recording . [CODESPLIT] public boolean stopRecording ( final String channel , final int streamId , final long correlationId , final long controlSessionId ) { stopRecordingRequestEncoder . wrapAndApplyHeader ( buffer , 0 , messageHeaderEncoder ) . controlSessionId ( controlSessionId ) . correlationId ( correlationId ) . streamId ( streamId ) . channel ( channel ) ; return offer ( stopRecordingRequestEncoder . encodedLength ( ) ) ; }


Input: Stop an active recording by the { @link Subscription#registrationId () } it was registered with . [CODESPLIT] public boolean stopRecording ( final long subscriptionId , final long correlationId , final long controlSessionId ) { stopRecordingSubscriptionRequestEncoder . wrapAndApplyHeader ( buffer , 0 , messageHeaderEncoder ) . controlSessionId ( controlSessionId ) . correlationId ( correlationId ) . subscriptionId ( subscriptionId ) ; return offer ( stopRecordingSubscriptionRequestEncoder . encodedLength ( ) ) ; }


Input: Replay a recording from a given position . [CODESPLIT] public boolean replay ( final long recordingId , final long position , final long length , final String replayChannel , final int replayStreamId , final long correlationId , final long controlSessionId ) { replayRequestEncoder . wrapAndApplyHeader ( buffer , 0 , messageHeaderEncoder ) . controlSessionId ( controlSessionId ) . correlationId ( correlationId ) . recordingId ( recordingId ) . position ( position ) . length ( length ) . replayStreamId ( replayStreamId ) . replayChannel ( replayChannel ) ; return offer ( replayRequestEncoder . encodedLength ( ) ) ; }


Input: Stop an existing replay session . [CODESPLIT] public boolean stopReplay ( final long replaySessionId , final long correlationId , final long controlSessionId ) { stopReplayRequestEncoder . wrapAndApplyHeader ( buffer , 0 , messageHeaderEncoder ) . controlSessionId ( controlSessionId ) . correlationId ( correlationId ) . replaySessionId ( replaySessionId ) ; return offer ( replayRequestEncoder . encodedLength ( ) ) ; }


Input: List a range of recording descriptors . [CODESPLIT] public boolean listRecordings ( final long fromRecordingId , final int recordCount , final long correlationId , final long controlSessionId ) { listRecordingsRequestEncoder . wrapAndApplyHeader ( buffer , 0 , messageHeaderEncoder ) . controlSessionId ( controlSessionId ) . correlationId ( correlationId ) . fromRecordingId ( fromRecordingId ) . recordCount ( recordCount ) ; return offer ( listRecordingsRequestEncoder . encodedLength ( ) ) ; }


Input: List a range of recording descriptors which match a channel URI fragment and stream id . [CODESPLIT] public boolean listRecordingsForUri ( final long fromRecordingId , final int recordCount , final String channelFragment , final int streamId , final long correlationId , final long controlSessionId ) { listRecordingsForUriRequestEncoder . wrapAndApplyHeader ( buffer , 0 , messageHeaderEncoder ) . controlSessionId ( controlSessionId ) . correlationId ( correlationId ) . fromRecordingId ( fromRecordingId ) . recordCount ( recordCount ) . streamId ( streamId ) . channel ( channelFragment ) ; return offer ( listRecordingsForUriRequestEncoder . encodedLength ( ) ) ; }


Input: List a recording descriptor for a given recording id . [CODESPLIT] public boolean listRecording ( final long recordingId , final long correlationId , final long controlSessionId ) { listRecordingRequestEncoder . wrapAndApplyHeader ( buffer , 0 , messageHeaderEncoder ) . controlSessionId ( controlSessionId ) . correlationId ( correlationId ) . recordingId ( recordingId ) ; return offer ( listRecordingRequestEncoder . encodedLength ( ) ) ; }


Input: Extend an existing non - active recorded stream for a the same channel and stream id . [CODESPLIT] public boolean extendRecording ( final String channel , final int streamId , final SourceLocation sourceLocation , final long recordingId , final long correlationId , final long controlSessionId ) { extendRecordingRequestEncoder . wrapAndApplyHeader ( buffer , 0 , messageHeaderEncoder ) . controlSessionId ( controlSessionId ) . correlationId ( correlationId ) . recordingId ( recordingId ) . streamId ( streamId ) . sourceLocation ( sourceLocation ) . channel ( channel ) ; return offer ( extendRecordingRequestEncoder . encodedLength ( ) ) ; }


Input: Get the recorded position of an active recording . [CODESPLIT] public boolean getRecordingPosition ( final long recordingId , final long correlationId , final long controlSessionId ) { recordingPositionRequestEncoder . wrapAndApplyHeader ( buffer , 0 , messageHeaderEncoder ) . controlSessionId ( controlSessionId ) . correlationId ( correlationId ) . recordingId ( recordingId ) ; return offer ( recordingPositionRequestEncoder . encodedLength ( ) ) ; }


Input: Truncate a stopped recording to a given position that is less than the stopped position . The provided position must be on a fragment boundary . Truncating a recording to the start position effectively deletes the recording . [CODESPLIT] public boolean truncateRecording ( final long recordingId , final long position , final long correlationId , final long controlSessionId ) { truncateRecordingRequestEncoder . wrapAndApplyHeader ( buffer , 0 , messageHeaderEncoder ) . controlSessionId ( controlSessionId ) . correlationId ( correlationId ) . recordingId ( recordingId ) . position ( position ) ; return offer ( truncateRecordingRequestEncoder . encodedLength ( ) ) ; }


Input: Get the stop position of a recording . [CODESPLIT] public boolean getStopPosition ( final long recordingId , final long correlationId , final long controlSessionId ) { stopPositionRequestEncoder . wrapAndApplyHeader ( buffer , 0 , messageHeaderEncoder ) . controlSessionId ( controlSessionId ) . correlationId ( correlationId ) . recordingId ( recordingId ) ; return offer ( stopPositionRequestEncoder . encodedLength ( ) ) ; }


Input: Find the last recording that matches the given criteria . [CODESPLIT] public boolean findLastMatchingRecording ( final long minRecordingId , final String channelFragment , final int streamId , final int sessionId , final long correlationId , final long controlSessionId ) { findLastMatchingRecordingRequestEncoder . wrapAndApplyHeader ( buffer , 0 , messageHeaderEncoder ) . controlSessionId ( controlSessionId ) . correlationId ( correlationId ) . minRecordingId ( minRecordingId ) . sessionId ( sessionId ) . streamId ( streamId ) . channel ( channelFragment ) ; return offer ( findLastMatchingRecordingRequestEncoder . encodedLength ( ) ) ; }


Input: List registered subscriptions in the archive which have been used to record streams . [CODESPLIT] public boolean listRecordingSubscriptions ( final int pseudoIndex , final int subscriptionCount , final String channelFragment , final int streamId , final boolean applyStreamId , final long correlationId , final long controlSessionId ) { listRecordingSubscriptionsRequestEncoder . wrapAndApplyHeader ( buffer , 0 , messageHeaderEncoder ) . controlSessionId ( controlSessionId ) . correlationId ( correlationId ) . pseudoIndex ( pseudoIndex ) . subscriptionCount ( subscriptionCount ) . applyStreamId ( applyStreamId ? BooleanType . TRUE : BooleanType . FALSE ) . streamId ( streamId ) . channel ( channelFragment ) ; return offer ( listRecordingSubscriptionsRequestEncoder . encodedLength ( ) ) ; }


Input: Parse channel URI and create a { @link UdpChannel } . [CODESPLIT] @ SuppressWarnings ( "MethodLength" ) public static UdpChannel parse ( final String channelUriString ) { try { final ChannelUri channelUri = ChannelUri . parse ( channelUriString ) ; validateConfiguration ( channelUri ) ; InetSocketAddress endpointAddress = getEndpointAddress ( channelUri ) ; final InetSocketAddress explicitControlAddress = getExplicitControlAddress ( channelUri ) ; final String tagIdStr = channelUri . channelTag ( ) ; final String controlMode = channelUri . get ( CommonContext . MDC_CONTROL_MODE_PARAM_NAME ) ; final boolean hasNoDistinguishingCharacteristic = null == endpointAddress && null == explicitControlAddress && null == tagIdStr ; if ( hasNoDistinguishingCharacteristic && null == controlMode ) { throw new IllegalArgumentException ( "Aeron URIs for UDP must specify an endpoint address, control address, tag-id, or control-mode" ) ; } if ( null != endpointAddress && endpointAddress . isUnresolved ( ) ) { throw new UnknownHostException ( "could not resolve endpoint address: " + endpointAddress ) ; } if ( null != explicitControlAddress && explicitControlAddress . isUnresolved ( ) ) { throw new UnknownHostException ( "could not resolve control address: " + explicitControlAddress ) ; } final Context context = new Context ( ) . uriStr ( channelUriString ) . channelUri ( channelUri ) . hasNoDistinguishingCharacteristic ( hasNoDistinguishingCharacteristic ) ; if ( null != tagIdStr ) { context . hasTagId ( true ) . tagId ( Long . parseLong ( tagIdStr ) ) ; } if ( null == endpointAddress ) { endpointAddress = new InetSocketAddress ( "0.0.0.0" , 0 ) ; } if ( endpointAddress . getAddress ( ) . isMulticastAddress ( ) ) { final InetSocketAddress controlAddress = getMulticastControlAddress ( endpointAddress ) ; final InterfaceSearchAddress searchAddress = getInterfaceSearchAddress ( channelUri ) ; final NetworkInterface localInterface = findInterface ( searchAddress ) ; final InetSocketAddress resolvedAddress = resolveToAddressOfInterface ( localInterface , searchAddress ) ; context . isMulticast ( true ) . localControlAddress ( resolvedAddress ) . remoteControlAddress ( controlAddress ) . localDataAddress ( resolvedAddress ) . remoteDataAddress ( endpointAddress ) . localInterface ( localInterface ) . protocolFamily ( getProtocolFamily ( endpointAddress . getAddress ( ) ) ) . canonicalForm ( canonicalise ( resolvedAddress , endpointAddress ) ) ; final String ttlValue = channelUri . get ( CommonContext . TTL_PARAM_NAME ) ; if ( null != ttlValue ) { context . hasMulticastTtl ( true ) . multicastTtl ( Integer . parseInt ( ttlValue ) ) ; } } else if ( null != explicitControlAddress ) { context . hasExplicitControl ( true ) . remoteControlAddress ( endpointAddress ) . remoteDataAddress ( endpointAddress ) . localControlAddress ( explicitControlAddress ) . localDataAddress ( explicitControlAddress ) . protocolFamily ( getProtocolFamily ( endpointAddress . getAddress ( ) ) ) . canonicalForm ( canonicalise ( explicitControlAddress , endpointAddress ) ) ; } else { final InterfaceSearchAddress searchAddress = getInterfaceSearchAddress ( channelUri ) ; final InetSocketAddress localAddress = searchAddress . getInetAddress ( ) . isAnyLocalAddress ( ) ? searchAddress . getAddress ( ) : resolveToAddressOfInterface ( findInterface ( searchAddress ) , searchAddress ) ; final String uniqueCanonicalFormSuffix = hasNoDistinguishingCharacteristic ? ( "-" + UNIQUE_CANONICAL_FORM_VALUE . getAndAdd ( 1 ) ) : "" ; context . remoteControlAddress ( endpointAddress ) . remoteDataAddress ( endpointAddress ) . localControlAddress ( localAddress ) . localDataAddress ( localAddress ) . protocolFamily ( getProtocolFamily ( endpointAddress . getAddress ( ) ) ) . canonicalForm ( canonicalise ( localAddress , endpointAddress ) + uniqueCanonicalFormSuffix ) ; } return new UdpChannel ( context ) ; } catch ( final Exception ex ) { throw new InvalidChannelException ( ErrorCode . INVALID_CHANNEL , ex ) ; } }


Input: Return a string which is a canonical form of the channel suitable for use as a file or directory name and also as a method of hashing etc . <p > A canonical form : <ul > <li > begins with the string UDP - < / li > <li > has all addresses converted to hexadecimal< / li > <li > uses - as all field separators< / li > < / ul > <p > The general format is : UDP - interface - localPort - remoteAddress - remotePort [CODESPLIT] public static String canonicalise ( final InetSocketAddress localData , final InetSocketAddress remoteData ) { final StringBuilder builder = new StringBuilder ( 48 ) ; builder . append ( "UDP-" ) ; toHex ( builder , localData . getAddress ( ) . getAddress ( ) ) . append ( ' ' ) . append ( localData . getPort ( ) ) ; builder . append ( ' ' ) ; toHex ( builder , remoteData . getAddress ( ) . getAddress ( ) ) . append ( ' ' ) . append ( remoteData . getPort ( ) ) ; return builder . toString ( ) ; }


Input: Does this channel have a tag match to another channel including endpoints . [CODESPLIT] public boolean matchesTag ( final UdpChannel udpChannel ) { if ( ! hasTag || ! udpChannel . hasTag ( ) || tag != udpChannel . tag ( ) ) { return false ; } if ( udpChannel . remoteData ( ) . getAddress ( ) . isAnyLocalAddress ( ) && udpChannel . remoteData ( ) . getPort ( ) == 0 && udpChannel . localData ( ) . getAddress ( ) . isAnyLocalAddress ( ) && udpChannel . localData ( ) . getPort ( ) == 0 ) { return true ; } throw new IllegalArgumentException ( "matching tag has set endpoint or control address" ) ; }


Input: Get the endpoint address from the URI . [CODESPLIT] public static InetSocketAddress destinationAddress ( final ChannelUri uri ) { try { validateConfiguration ( uri ) ; return getEndpointAddress ( uri ) ; } catch ( final Exception ex ) { throw new InvalidChannelException ( ErrorCode . INVALID_CHANNEL , ex ) ; } }


Input: Used for debugging to get a human readable description of the channel . [CODESPLIT] public String description ( ) { final StringBuilder builder = new StringBuilder ( "UdpChannel - " ) ; if ( null != localInterface ) { builder . append ( "interface: " ) . append ( localInterface . getDisplayName ( ) ) . append ( ", " ) ; } builder . append ( "localData: " ) . append ( localData ) . append ( ", remoteData: " ) . append ( remoteData ) . append ( ", ttl: " ) . append ( multicastTtl ) ; return builder . toString ( ) ; }


Input: { [CODESPLIT] public void close ( ) { hwmPosition . close ( ) ; rebuildPosition . close ( ) ; for ( final ReadablePosition position : subscriberPositions ) { position . close ( ) ; } for ( int i = 0 , size = untetheredSubscriptions . size ( ) ; i < size ; i ++ ) { final UntetheredSubscription untetheredSubscription = untetheredSubscriptions . get ( i ) ; if ( UntetheredSubscription . RESTING == untetheredSubscription . state ) { untetheredSubscription . position . close ( ) ; } } congestionControl . close ( ) ; rawLog . close ( ) ; }


Input: { [CODESPLIT] public void addSubscriber ( final SubscriptionLink subscriptionLink , final ReadablePosition subscriberPosition ) { subscriberPositions = ArrayUtil . add ( subscriberPositions , subscriberPosition ) ; if ( ! subscriptionLink . isTether ( ) ) { untetheredSubscriptions . add ( new UntetheredSubscription ( subscriptionLink , subscriberPosition , timeOfLastStatusMessageScheduleNs ) ) ; } }


Input: { [CODESPLIT] public void removeSubscriber ( final SubscriptionLink subscriptionLink , final ReadablePosition subscriberPosition ) { subscriberPositions = ArrayUtil . remove ( subscriberPositions , subscriberPosition ) ; subscriberPosition . close ( ) ; if ( ! subscriptionLink . isTether ( ) ) { for ( int lastIndex = untetheredSubscriptions . size ( ) - 1 , i = lastIndex ; i >= 0 ; i -- ) { if ( untetheredSubscriptions . get ( i ) . subscriptionLink == subscriptionLink ) { ArrayListUtil . fastUnorderedRemove ( untetheredSubscriptions , i , lastIndex ) ; break ; } } } }


Input: Called from the { @link LossDetector } when gap is detected by the { @link DriverConductor } thread . [CODESPLIT] public void onGapDetected ( final int termId , final int termOffset , final int length ) { final long changeNumber = beginLossChange + 1 ; beginLossChange = changeNumber ; lossTermId = termId ; lossTermOffset = termOffset ; lossLength = length ; endLossChange = changeNumber ; if ( null != reportEntry ) { reportEntry . recordObservation ( length , cachedEpochClock . time ( ) ) ; } else if ( null != lossReport ) { reportEntry = lossReport . createEntry ( length , cachedEpochClock . time ( ) , sessionId , streamId , channel ( ) , sourceAddress . toString ( ) ) ; if ( null == reportEntry ) { lossReport = null ; } } }


Input: Add a destination to this image so it can merge streams . [CODESPLIT] void addDestination ( final int transportIndex , final ReceiveDestinationUdpTransport transport ) { imageConnections = ArrayUtil . ensureCapacity ( imageConnections , transportIndex + 1 ) ; if ( transport . isMulticast ( ) ) { imageConnections [ transportIndex ] = new ImageConnection ( cachedNanoClock . nanoTime ( ) , transport . udpChannel ( ) . remoteControl ( ) ) ; } else if ( transport . hasExplicitControl ( ) ) { imageConnections [ transportIndex ] = new ImageConnection ( cachedNanoClock . nanoTime ( ) , transport . explicitControlAddress ( ) ) ; } }


Input: Called from the { @link DriverConductor } . [CODESPLIT] final void trackRebuild ( final long nowNs , final long statusMessageTimeoutNs ) { long minSubscriberPosition = Long . MAX_VALUE ; long maxSubscriberPosition = Long . MIN_VALUE ; for ( final ReadablePosition subscriberPosition : subscriberPositions ) { final long position = subscriberPosition . getVolatile ( ) ; minSubscriberPosition = Math . min ( minSubscriberPosition , position ) ; maxSubscriberPosition = Math . max ( maxSubscriberPosition , position ) ; } final long rebuildPosition = Math . max ( this . rebuildPosition . get ( ) , maxSubscriberPosition ) ; final long hwmPosition = this . hwmPosition . getVolatile ( ) ; final long scanOutcome = lossDetector . scan ( termBuffers [ indexByPosition ( rebuildPosition , positionBitsToShift ) ] , rebuildPosition , hwmPosition , nowNs , termLengthMask , positionBitsToShift , initialTermId ) ; final int rebuildTermOffset = ( int ) rebuildPosition & termLengthMask ; final long newRebuildPosition = ( rebuildPosition - rebuildTermOffset ) + rebuildOffset ( scanOutcome ) ; this . rebuildPosition . proposeMaxOrdered ( newRebuildPosition ) ; final long ccOutcome = congestionControl . onTrackRebuild ( nowNs , minSubscriberPosition , nextSmPosition , hwmPosition , rebuildPosition , newRebuildPosition , lossFound ( scanOutcome ) ) ; final int windowLength = CongestionControl . receiverWindowLength ( ccOutcome ) ; final int threshold = CongestionControl . threshold ( windowLength ) ; if ( CongestionControl . shouldForceStatusMessage ( ccOutcome ) || ( ( timeOfLastStatusMessageScheduleNs + statusMessageTimeoutNs ) - nowNs < 0 ) || ( minSubscriberPosition > ( nextSmPosition + threshold ) ) ) { scheduleStatusMessage ( nowNs , minSubscriberPosition , windowLength ) ; cleanBufferTo ( minSubscriberPosition - ( termLengthMask + 1 ) ) ; } }


Input: Insert frame into term buffer . [CODESPLIT] int insertPacket ( final int termId , final int termOffset , final UnsafeBuffer buffer , final int length , final int transportIndex , final InetSocketAddress srcAddress ) { final boolean isHeartbeat = DataHeaderFlyweight . isHeartbeat ( buffer , length ) ; final long packetPosition = computePosition ( termId , termOffset , positionBitsToShift , initialTermId ) ; final long proposedPosition = isHeartbeat ? packetPosition : packetPosition + length ; if ( ! isFlowControlUnderRun ( packetPosition ) && ! isFlowControlOverRun ( proposedPosition ) ) { trackConnection ( transportIndex , srcAddress , lastPacketTimestampNs ) ; if ( isHeartbeat ) { if ( DataHeaderFlyweight . isEndOfStream ( buffer ) && ! isEndOfStream && allEos ( transportIndex ) ) { LogBufferDescriptor . endOfStreamPosition ( rawLog . metaData ( ) , proposedPosition ) ; isEndOfStream = true ; } heartbeatsReceived . incrementOrdered ( ) ; } else { final UnsafeBuffer termBuffer = termBuffers [ indexByPosition ( packetPosition , positionBitsToShift ) ] ; TermRebuilder . insert ( termBuffer , termOffset , buffer , length ) ; } lastPacketTimestampNs = cachedNanoClock . nanoTime ( ) ; hwmPosition . proposeMaxOrdered ( proposedPosition ) ; } return length ; }


Input: To be called from the { @link Receiver } to see if a image should be retained . [CODESPLIT] boolean hasActivityAndNotEndOfStream ( final long nowNs ) { boolean isActive = true ; if ( ( ( lastPacketTimestampNs + imageLivenessTimeoutNs ) - nowNs < 0 ) || ( isEndOfStream && rebuildPosition . getVolatile ( ) >= hwmPosition . get ( ) ) ) { isActive = false ; } return isActive ; }


Input: Called from the { @link Receiver } to send any pending Status Messages . [CODESPLIT] int sendPendingStatusMessage ( ) { int workCount = 0 ; if ( ACTIVE == state ) { final long changeNumber = endSmChange ; if ( changeNumber != lastSmChangeNumber ) { final long smPosition = nextSmPosition ; final int receiverWindowLength = nextSmReceiverWindowLength ; UNSAFE . loadFence ( ) ; if ( changeNumber == beginSmChange ) { final int termId = computeTermIdFromPosition ( smPosition , positionBitsToShift , initialTermId ) ; final int termOffset = ( int ) smPosition & termLengthMask ; channelEndpoint . sendStatusMessage ( imageConnections , sessionId , streamId , termId , termOffset , receiverWindowLength , ( byte ) 0 ) ; statusMessagesSent . incrementOrdered ( ) ; lastSmPosition = smPosition ; lastSmWindowLimit = smPosition + receiverWindowLength ; lastSmChangeNumber = changeNumber ; } workCount = 1 ; } } return workCount ; }


Input: Called from the { @link Receiver } thread to processing any pending loss of packets . [CODESPLIT] int processPendingLoss ( ) { int workCount = 0 ; final long changeNumber = endLossChange ; if ( changeNumber != lastLossChangeNumber ) { final int termId = lossTermId ; final int termOffset = lossTermOffset ; final int length = lossLength ; UNSAFE . loadFence ( ) ; if ( changeNumber == beginLossChange ) { if ( isReliable ) { channelEndpoint . sendNakMessage ( imageConnections , sessionId , streamId , termId , termOffset , length ) ; nakMessagesSent . incrementOrdered ( ) ; } else { final UnsafeBuffer termBuffer = termBuffers [ indexByTerm ( initialTermId , termId ) ] ; if ( tryFillGap ( rawLog . metaData ( ) , termBuffer , termId , termOffset , length ) ) { lossGapFills . incrementOrdered ( ) ; } } lastLossChangeNumber = changeNumber ; } workCount = 1 ; } return workCount ; }


Input: Called from the { @link Receiver } thread to check for initiating an RTT measurement . [CODESPLIT] int initiateAnyRttMeasurements ( final long nowNs ) { int workCount = 0 ; if ( congestionControl . shouldMeasureRtt ( nowNs ) ) { final long preciseTimeNs = nanoClock . nanoTime ( ) ; channelEndpoint . sendRttMeasurement ( imageConnections , sessionId , streamId , preciseTimeNs , 0 , true ) ; congestionControl . onRttMeasurementSent ( preciseTimeNs ) ; workCount = 1 ; } return workCount ; }


Input: Called from the { @link Receiver } upon receiving an RTT Measurement that is a reply . [CODESPLIT] void onRttMeasurement ( final RttMeasurementFlyweight header , @ SuppressWarnings ( "unused" ) final int transportIndex , final InetSocketAddress srcAddress ) { final long nowNs = nanoClock . nanoTime ( ) ; final long rttInNs = nowNs - header . echoTimestampNs ( ) - header . receptionDelta ( ) ; congestionControl . onRttMeasurement ( nowNs , rttInNs , srcAddress ) ; }


Input: { [CODESPLIT] public void onTimeEvent ( final long timeNs , final long timesMs , final DriverConductor conductor ) { switch ( state ) { case ACTIVE : checkUntetheredSubscriptions ( timeNs , conductor ) ; break ; case INACTIVE : if ( isDrained ( ) ) { state = State . LINGER ; timeOfLastStateChangeNs = timeNs ; conductor . transitionToLinger ( this ) ; } isTrackingRebuild = false ; break ; case LINGER : if ( ( timeOfLastStateChangeNs + imageLivenessTimeoutNs ) - timeNs < 0 ) { state = State . DONE ; conductor . cleanupImage ( this ) ; } break ; } }


Input: Map a { @link CountersReader } over the provided { @link File } for the CnC file . [CODESPLIT] public static CountersReader mapCounters ( final File cncFile ) { final MappedByteBuffer cncByteBuffer = IoUtil . mapExistingFile ( cncFile , "cnc" ) ; final DirectBuffer cncMetaData = createMetaDataBuffer ( cncByteBuffer ) ; final int cncVersion = cncMetaData . getInt ( cncVersionOffset ( 0 ) ) ; if ( CncFileDescriptor . CNC_VERSION != cncVersion ) { throw new AeronException ( "Aeron CnC version does not match: version=" + cncVersion + " required=" + CNC_VERSION ) ; } return new CountersReader ( createCountersMetaDataBuffer ( cncByteBuffer , cncMetaData ) , createCountersValuesBuffer ( cncByteBuffer , cncMetaData ) , StandardCharsets . US_ASCII ) ; }


Input: Find the control toggle counter or return null if not found . [CODESPLIT] public static AtomicCounter findControlToggle ( final CountersReader counters ) { final AtomicBuffer buffer = counters . metaDataBuffer ( ) ; for ( int i = 0 , size = counters . maxCounterId ( ) ; i < size ; i ++ ) { final int recordOffset = CountersReader . metaDataOffset ( i ) ; if ( counters . getCounterState ( i ) == RECORD_ALLOCATED && buffer . getInt ( recordOffset + TYPE_ID_OFFSET ) == CONTROL_TOGGLE_TYPE_ID ) { return new AtomicCounter ( counters . valuesBuffer ( ) , i , null ) ; } } return null ; }


Input: Put a key and value pair in the map of params . [CODESPLIT] public String put ( final String key , final String value ) { return params . put ( key , value ) ; }


Input: Get the channel tag if it exists that refers to an another channel . [CODESPLIT] public String channelTag ( ) { return ( null != tags && tags . length > CHANNEL_TAG_INDEX ) ? tags [ CHANNEL_TAG_INDEX ] : null ; }


Input: Get the entity tag if it exists that refers to an entity such as subscription or publication . [CODESPLIT] public String entityTag ( ) { return ( null != tags && tags . length > ENTITY_TAG_INDEX ) ? tags [ ENTITY_TAG_INDEX ] : null ; }


Input: Initialise a channel for restarting a publication at a given position . [CODESPLIT] public void initialPosition ( final long position , final int initialTermId , final int termLength ) { if ( position < 0 || 0 != ( position & ( FRAME_ALIGNMENT - 1 ) ) ) { throw new IllegalArgumentException ( "invalid position: " + position ) ; } final int bitsToShift = LogBufferDescriptor . positionBitsToShift ( termLength ) ; final int termId = LogBufferDescriptor . computeTermIdFromPosition ( position , bitsToShift , initialTermId ) ; final int termOffset = ( int ) ( position & ( termLength - 1 ) ) ; put ( INITIAL_TERM_ID_PARAM_NAME , Integer . toString ( initialTermId ) ) ; put ( TERM_ID_PARAM_NAME , Integer . toString ( termId ) ) ; put ( TERM_OFFSET_PARAM_NAME , Integer . toString ( termOffset ) ) ; put ( TERM_LENGTH_PARAM_NAME , Integer . toString ( termLength ) ) ; }


Input: Parse a { @link CharSequence } which contains an Aeron URI . [CODESPLIT] public static ChannelUri parse ( final CharSequence cs ) { int position = 0 ; final String prefix ; if ( startsWith ( cs , 0 , SPY_PREFIX ) ) { prefix = SPY_QUALIFIER ; position = SPY_PREFIX . length ( ) ; } else { prefix = "" ; } if ( ! startsWith ( cs , position , AERON_PREFIX ) ) { throw new IllegalArgumentException ( "Aeron URIs must start with 'aeron:', found: '" + cs + "'" ) ; } else { position += AERON_PREFIX . length ( ) ; } final StringBuilder builder = new StringBuilder ( ) ; final Map < String , String > params = new Object2ObjectHashMap <> ( ) ; String media = null ; String key = null ; State state = State . MEDIA ; for ( int i = position ; i < cs . length ( ) ; i ++ ) { final char c = cs . charAt ( i ) ; switch ( state ) { case MEDIA : switch ( c ) { case ' ' : media = builder . toString ( ) ; builder . setLength ( 0 ) ; state = State . PARAMS_KEY ; break ; case ' ' : throw new IllegalArgumentException ( "encountered ':' within media definition" ) ; default : builder . append ( c ) ; } break ; case PARAMS_KEY : if ( c == ' ' ) { key = builder . toString ( ) ; builder . setLength ( 0 ) ; state = State . PARAMS_VALUE ; } else { builder . append ( c ) ; } break ; case PARAMS_VALUE : if ( c == ' ' ) { params . put ( key , builder . toString ( ) ) ; builder . setLength ( 0 ) ; state = State . PARAMS_KEY ; } else { builder . append ( c ) ; } break ; default : throw new IllegalStateException ( "unexpected state=" + state ) ; } } switch ( state ) { case MEDIA : media = builder . toString ( ) ; break ; case PARAMS_VALUE : params . put ( key , builder . toString ( ) ) ; break ; default : throw new IllegalArgumentException ( "no more input found, state=" + state ) ; } return new ChannelUri ( prefix , media , params ) ; }


Input: Add a sessionId to a given channel . [CODESPLIT] public static String addSessionId ( final String channel , final int sessionId ) { final ChannelUri channelUri = ChannelUri . parse ( channel ) ; channelUri . put ( CommonContext . SESSION_ID_PARAM_NAME , Integer . toString ( sessionId ) ) ; return channelUri . toString ( ) ; }


Input: Get the value of the tag from a given parameter value . [CODESPLIT] public static long getTag ( final String paramValue ) { return isTagged ( paramValue ) ? AsciiEncoding . parseLongAscii ( paramValue , 4 , paramValue . length ( ) - 4 ) : INVALID_TAG ; }


Input: Claim length of a the term buffer for writing in the message with zero copy semantics . [CODESPLIT] public int claim ( final int termId , final int termOffset , final HeaderWriter header , final int length , final BufferClaim bufferClaim ) { final int frameLength = length + HEADER_LENGTH ; final int alignedLength = align ( frameLength , FRAME_ALIGNMENT ) ; final UnsafeBuffer termBuffer = this . termBuffer ; final int termLength = termBuffer . capacity ( ) ; int resultingOffset = termOffset + alignedLength ; putRawTailOrdered ( termId , resultingOffset ) ; if ( resultingOffset > termLength ) { resultingOffset = handleEndOfLogCondition ( termBuffer , termOffset , header , termLength , termId ) ; } else { header . write ( termBuffer , termOffset , frameLength , termId ) ; bufferClaim . wrap ( termBuffer , termOffset , frameLength ) ; } return resultingOffset ; }


Input: Pad a length of the term buffer with a padding record . [CODESPLIT] public int appendPadding ( final int termId , final int termOffset , final HeaderWriter header , final int length ) { final int frameLength = length + HEADER_LENGTH ; final int alignedLength = align ( frameLength , FRAME_ALIGNMENT ) ; final UnsafeBuffer termBuffer = this . termBuffer ; final int termLength = termBuffer . capacity ( ) ; int resultingOffset = termOffset + alignedLength ; putRawTailOrdered ( termId , resultingOffset ) ; if ( resultingOffset > termLength ) { resultingOffset = handleEndOfLogCondition ( termBuffer , termOffset , header , termLength , termId ) ; } else { header . write ( termBuffer , termOffset , frameLength , termId ) ; frameType ( termBuffer , termOffset , PADDING_FRAME_TYPE ) ; frameLengthOrdered ( termBuffer , termOffset , frameLength ) ; } return resultingOffset ; }


Input: Append an unfragmented message to the the term buffer . [CODESPLIT] public int appendUnfragmentedMessage ( final int termId , final int termOffset , final HeaderWriter header , final DirectBuffer srcBuffer , final int srcOffset , final int length , final ReservedValueSupplier reservedValueSupplier ) { final int frameLength = length + HEADER_LENGTH ; final int alignedLength = align ( frameLength , FRAME_ALIGNMENT ) ; final UnsafeBuffer termBuffer = this . termBuffer ; final int termLength = termBuffer . capacity ( ) ; int resultingOffset = termOffset + alignedLength ; putRawTailOrdered ( termId , resultingOffset ) ; if ( resultingOffset > termLength ) { resultingOffset = handleEndOfLogCondition ( termBuffer , termOffset , header , termLength , termId ) ; } else { header . write ( termBuffer , termOffset , frameLength , termId ) ; termBuffer . putBytes ( termOffset + HEADER_LENGTH , srcBuffer , srcOffset , length ) ; if ( null != reservedValueSupplier ) { final long reservedValue = reservedValueSupplier . get ( termBuffer , termOffset , frameLength ) ; termBuffer . putLong ( termOffset + RESERVED_VALUE_OFFSET , reservedValue , LITTLE_ENDIAN ) ; } frameLengthOrdered ( termBuffer , termOffset , frameLength ) ; } return resultingOffset ; }


Input: Append a fragmented message to the the term buffer . The message will be split up into fragments of MTU length minus header . [CODESPLIT] public int appendFragmentedMessage ( final int termId , final int termOffset , final HeaderWriter header , final DirectBufferVector [ ] vectors , final int length , final int maxPayloadLength , final ReservedValueSupplier reservedValueSupplier ) { final int numMaxPayloads = length / maxPayloadLength ; final int remainingPayload = length % maxPayloadLength ; final int lastFrameLength = remainingPayload > 0 ? align ( remainingPayload + HEADER_LENGTH , FRAME_ALIGNMENT ) : 0 ; final int requiredLength = ( numMaxPayloads * ( maxPayloadLength + HEADER_LENGTH ) ) + lastFrameLength ; final UnsafeBuffer termBuffer = this . termBuffer ; final int termLength = termBuffer . capacity ( ) ; int resultingOffset = termOffset + requiredLength ; putRawTailOrdered ( termId , resultingOffset ) ; if ( resultingOffset > termLength ) { resultingOffset = handleEndOfLogCondition ( termBuffer , termOffset , header , termLength , termId ) ; } else { int frameOffset = termOffset ; byte flags = BEGIN_FRAG_FLAG ; int remaining = length ; int vectorIndex = 0 ; int vectorOffset = 0 ; do { final int bytesToWrite = Math . min ( remaining , maxPayloadLength ) ; final int frameLength = bytesToWrite + HEADER_LENGTH ; final int alignedLength = align ( frameLength , FRAME_ALIGNMENT ) ; header . write ( termBuffer , frameOffset , frameLength , termId ) ; int bytesWritten = 0 ; int payloadOffset = frameOffset + HEADER_LENGTH ; do { final DirectBufferVector vector = vectors [ vectorIndex ] ; final int vectorRemaining = vector . length - vectorOffset ; final int numBytes = Math . min ( bytesToWrite - bytesWritten , vectorRemaining ) ; termBuffer . putBytes ( payloadOffset , vector . buffer , vector . offset + vectorOffset , numBytes ) ; bytesWritten += numBytes ; payloadOffset += numBytes ; vectorOffset += numBytes ; if ( vectorRemaining <= numBytes ) { vectorIndex ++ ; vectorOffset = 0 ; } } while ( bytesWritten < bytesToWrite ) ; if ( remaining <= maxPayloadLength ) { flags |= END_FRAG_FLAG ; } frameFlags ( termBuffer , frameOffset , flags ) ; if ( null != reservedValueSupplier ) { final long reservedValue = reservedValueSupplier . get ( termBuffer , frameOffset , frameLength ) ; termBuffer . putLong ( frameOffset + RESERVED_VALUE_OFFSET , reservedValue , LITTLE_ENDIAN ) ; } frameLengthOrdered ( termBuffer , frameOffset , frameLength ) ; flags = 0 ; frameOffset += alignedLength ; remaining -= bytesToWrite ; } while ( remaining > 0 ) ; } return resultingOffset ; }


Input: Update the publishers limit for flow control as part of the conductor duty cycle . [CODESPLIT] final int updatePublisherLimit ( ) { int workCount = 0 ; final long senderPosition = this . senderPosition . getVolatile ( ) ; if ( hasReceivers || ( spiesSimulateConnection && spyPositions . length > 0 ) ) { long minConsumerPosition = senderPosition ; for ( final ReadablePosition spyPosition : spyPositions ) { minConsumerPosition = Math . min ( minConsumerPosition , spyPosition . getVolatile ( ) ) ; } final long proposedPublisherLimit = minConsumerPosition + termWindowLength ; if ( publisherLimit . proposeMaxOrdered ( proposedPublisherLimit ) ) { cleanBuffer ( proposedPublisherLimit ) ; workCount = 1 ; } } else if ( publisherLimit . get ( ) > senderPosition ) { publisherLimit . setOrdered ( senderPosition ) ; } return workCount ; }


Input: Search for a list of network interfaces that match the specified address and subnet prefix . The results will be ordered by the length of the subnet prefix ( { @link InterfaceAddress#getNetworkPrefixLength () } ) . If no results match then the collection will be empty . [CODESPLIT] public static NetworkInterface [ ] filterBySubnet ( final InetAddress address , final int subnetPrefix ) throws SocketException { return filterBySubnet ( NetworkInterfaceShim . DEFAULT , address , subnetPrefix ) ; }


Input: Allocate a direct { @link ByteBuffer } that is padded at the end with at least alignment bytes . [CODESPLIT] public static ByteBuffer allocateDirectAlignedAndPadded ( final int capacity , final int alignment ) { final ByteBuffer buffer = BufferUtil . allocateDirectAligned ( capacity + alignment , alignment ) ; buffer . limit ( buffer . limit ( ) - alignment ) ; return buffer . slice ( ) ; }


Input: Allocate a counter for tracking a position on a stream of messages . [CODESPLIT] public static UnsafeBufferPosition allocate ( final MutableDirectBuffer tempBuffer , final String name , final int typeId , final CountersManager countersManager , final long registrationId , final int sessionId , final int streamId , final String channel ) { return new UnsafeBufferPosition ( ( UnsafeBuffer ) countersManager . valuesBuffer ( ) , allocateCounterId ( tempBuffer , name , typeId , countersManager , registrationId , sessionId , streamId , channel ) , countersManager ) ; }


Input: Return the label name for a counter type identifier . [CODESPLIT] public static String labelName ( final int typeId ) { switch ( typeId ) { case PublisherLimit . PUBLISHER_LIMIT_TYPE_ID : return PublisherLimit . NAME ; case SenderPos . SENDER_POSITION_TYPE_ID : return SenderPos . NAME ; case ReceiverHwm . RECEIVER_HWM_TYPE_ID : return ReceiverHwm . NAME ; case SubscriberPos . SUBSCRIBER_POSITION_TYPE_ID : return SubscriberPos . NAME ; case ReceiverPos . RECEIVER_POS_TYPE_ID : return ReceiverPos . NAME ; case SenderLimit . SENDER_LIMIT_TYPE_ID : return SenderLimit . NAME ; case PublisherPos . PUBLISHER_POS_TYPE_ID : return PublisherPos . NAME ; case SenderBpe . SENDER_BPE_TYPE_ID : return SenderBpe . NAME ; default : return "<unknown>" ; } }


Input: Scan the term buffer for availability of new message fragments from a given offset up to a maxLength of bytes . [CODESPLIT] public static long scanForAvailability ( final UnsafeBuffer termBuffer , final int offset , final int maxLength ) { final int limit = Math . min ( maxLength , termBuffer . capacity ( ) - offset ) ; int available = 0 ; int padding = 0 ; do { final int termOffset = offset + available ; final int frameLength = frameLengthVolatile ( termBuffer , termOffset ) ; if ( frameLength <= 0 ) { break ; } int alignedFrameLength = align ( frameLength , FRAME_ALIGNMENT ) ; if ( isPaddingFrame ( termBuffer , termOffset ) ) { padding = alignedFrameLength - HEADER_LENGTH ; alignedFrameLength = HEADER_LENGTH ; } available += alignedFrameLength ; if ( available > limit ) { available -= alignedFrameLength ; padding = 0 ; break ; } } while ( 0 == padding && available < limit ) ; return pack ( padding , available ) ; }


Input: Clear out all the values thus setting back to the initial state . [CODESPLIT] public ChannelUriStringBuilder clear ( ) { prefix = null ; media = null ; endpoint = null ; networkInterface = null ; controlEndpoint = null ; controlMode = null ; tags = null ; alias = null ; reliable = null ; ttl = null ; mtu = null ; termLength = null ; initialTermId = null ; termId = null ; termOffset = null ; sessionId = null ; linger = null ; sparse = null ; eos = null ; tether = null ; isSessionIdTagged = false ; return this ; }


Input: Validates that the collection of set parameters are valid together . [CODESPLIT] public ChannelUriStringBuilder validate ( ) { if ( null == media ) { throw new IllegalStateException ( "media type is mandatory" ) ; } if ( CommonContext . UDP_MEDIA . equals ( media ) && ( null == endpoint && null == controlEndpoint ) ) { throw new IllegalStateException ( "either 'endpoint' or 'control' must be specified for UDP." ) ; } int count = 0 ; count += null == initialTermId ? 0 : 1 ; count += null == termId ? 0 : 1 ; count += null == termOffset ? 0 : 1 ; if ( count > 0 ) { if ( count < 3 ) { throw new IllegalStateException ( "if any of then a complete set of 'initialTermId', 'termId', and 'termOffset' must be provided" ) ; } if ( termId - initialTermId < 0 ) // lgtm [java/dereferenced-value-may-be-null] { throw new IllegalStateException ( "difference greater than 2^31 - 1: termId=" + termId + " - initialTermId=" + initialTermId ) ; } if ( null != termLength && termOffset > termLength ) // lgtm [java/dereferenced-value-may-be-null] { throw new IllegalStateException ( "termOffset=" + termOffset + " > termLength=" + termLength ) ; } } return this ; }


Input: Set the prefix for taking an addition action such as spying on an outgoing publication with aeron - spy . [CODESPLIT] public ChannelUriStringBuilder prefix ( final String prefix ) { if ( null != prefix && ! prefix . equals ( "" ) && ! prefix . equals ( SPY_QUALIFIER ) ) { throw new IllegalArgumentException ( "invalid prefix: " + prefix ) ; } this . prefix = prefix ; return this ; }


Input: Set the media for this channel . Valid values are udp and ipc . [CODESPLIT] public ChannelUriStringBuilder media ( final String media ) { switch ( media ) { case CommonContext . UDP_MEDIA : case CommonContext . IPC_MEDIA : break ; default : throw new IllegalArgumentException ( "invalid media: " + media ) ; } this . media = media ; return this ; }


Input: Set the control mode for multi - destination - cast . Set to manual for allowing control from the publication API . [CODESPLIT] public ChannelUriStringBuilder controlMode ( final String controlMode ) { if ( null != controlMode && ! controlMode . equals ( CommonContext . MDC_CONTROL_MODE_MANUAL ) && ! controlMode . equals ( CommonContext . MDC_CONTROL_MODE_DYNAMIC ) ) { throw new IllegalArgumentException ( "invalid control mode: " + controlMode ) ; } this . controlMode = controlMode ; return this ; }


Input: Set the Time To Live ( TTL ) for a multicast datagram . Valid values are 0 - 255 for the number of hops the datagram can progress along . [CODESPLIT] public ChannelUriStringBuilder ttl ( final Integer ttl ) { if ( null != ttl && ( ttl < 0 || ttl > 255 ) ) { throw new IllegalArgumentException ( "TTL not in range 0-255: " + ttl ) ; } this . ttl = ttl ; return this ; }


Input: Set the maximum transmission unit ( MTU ) including Aeron header for a datagram payload . If this is greater than the network MTU for UDP then the packet will be fragmented and can amplify the impact of loss . [CODESPLIT] public ChannelUriStringBuilder mtu ( final Integer mtu ) { if ( null != mtu ) { if ( mtu < 32 || mtu > 65504 ) { throw new IllegalArgumentException ( "MTU not in range 32-65504: " + mtu ) ; } if ( ( mtu & ( FRAME_ALIGNMENT - 1 ) ) != 0 ) { throw new IllegalArgumentException ( "MTU not a multiple of FRAME_ALIGNMENT: mtu=" + mtu ) ; } } this . mtu = mtu ; return this ; }


Input: Set the length of buffer used for each term of the log . Valid values are powers of 2 in the 64K - 1G range . [CODESPLIT] public ChannelUriStringBuilder termLength ( final Integer termLength ) { if ( null != termLength ) { LogBufferDescriptor . checkTermLength ( termLength ) ; } this . termLength = termLength ; return this ; }


Input: Set the offset within a term at which a publication will start . This when combined with the term id can establish a starting position . [CODESPLIT] public ChannelUriStringBuilder termOffset ( final Integer termOffset ) { if ( null != termOffset ) { if ( ( termOffset < 0 || termOffset > LogBufferDescriptor . TERM_MAX_LENGTH ) ) { throw new IllegalArgumentException ( "term offset not in range 0-1g: " + termOffset ) ; } if ( 0 != ( termOffset & ( FRAME_ALIGNMENT - 1 ) ) ) { throw new IllegalArgumentException ( "term offset not multiple of FRAME_ALIGNMENT: " + termOffset ) ; } } this . termOffset = termOffset ; return this ; }


Input: Set the time a network publication will linger in nanoseconds after being drained . This time is so that tail loss can be recovered . [CODESPLIT] public ChannelUriStringBuilder linger ( final Long lingerNs ) { if ( null != lingerNs && lingerNs < 0 ) { throw new IllegalArgumentException ( "linger value cannot be negative: " + lingerNs ) ; } this . linger = lingerNs ; return this ; }


Input: Initialise a channel for restarting a publication at a given position . [CODESPLIT] public ChannelUriStringBuilder initialPosition ( final long position , final int initialTermId , final int termLength ) { if ( position < 0 || 0 != ( position & ( FRAME_ALIGNMENT - 1 ) ) ) { throw new IllegalArgumentException ( "invalid position: " + position ) ; } final int bitsToShift = LogBufferDescriptor . positionBitsToShift ( termLength ) ; this . initialTermId = initialTermId ; this . termId = LogBufferDescriptor . computeTermIdFromPosition ( position , bitsToShift , initialTermId ) ; this . termOffset = ( int ) ( position & ( termLength - 1 ) ) ; this . termLength = termLength ; return this ; }


Input: Build a channel URI String for the given parameters . [CODESPLIT] @ SuppressWarnings ( "MethodLength" ) public String build ( ) { sb . setLength ( 0 ) ; if ( null != prefix && ! "" . equals ( prefix ) ) { sb . append ( prefix ) . append ( ' ' ) ; } sb . append ( ChannelUri . AERON_SCHEME ) . append ( ' ' ) . append ( media ) . append ( ' ' ) ; if ( null != tags ) { sb . append ( TAGS_PARAM_NAME ) . append ( ' ' ) . append ( tags ) . append ( ' ' ) ; } if ( null != endpoint ) { sb . append ( ENDPOINT_PARAM_NAME ) . append ( ' ' ) . append ( endpoint ) . append ( ' ' ) ; } if ( null != networkInterface ) { sb . append ( INTERFACE_PARAM_NAME ) . append ( ' ' ) . append ( networkInterface ) . append ( ' ' ) ; } if ( null != controlEndpoint ) { sb . append ( MDC_CONTROL_PARAM_NAME ) . append ( ' ' ) . append ( controlEndpoint ) . append ( ' ' ) ; } if ( null != controlMode ) { sb . append ( MDC_CONTROL_MODE_PARAM_NAME ) . append ( ' ' ) . append ( controlMode ) . append ( ' ' ) ; } if ( null != mtu ) { sb . append ( MTU_LENGTH_PARAM_NAME ) . append ( ' ' ) . append ( mtu . intValue ( ) ) . append ( ' ' ) ; } if ( null != termLength ) { sb . append ( TERM_LENGTH_PARAM_NAME ) . append ( ' ' ) . append ( termLength . intValue ( ) ) . append ( ' ' ) ; } if ( null != initialTermId ) { sb . append ( INITIAL_TERM_ID_PARAM_NAME ) . append ( ' ' ) . append ( initialTermId . intValue ( ) ) . append ( ' ' ) ; } if ( null != termId ) { sb . append ( TERM_ID_PARAM_NAME ) . append ( ' ' ) . append ( termId . intValue ( ) ) . append ( ' ' ) ; } if ( null != termOffset ) { sb . append ( TERM_OFFSET_PARAM_NAME ) . append ( ' ' ) . append ( termOffset . intValue ( ) ) . append ( ' ' ) ; } if ( null != sessionId ) { sb . append ( SESSION_ID_PARAM_NAME ) . append ( ' ' ) . append ( prefixTag ( isSessionIdTagged , sessionId ) ) . append ( ' ' ) ; } if ( null != ttl ) { sb . append ( TTL_PARAM_NAME ) . append ( ' ' ) . append ( ttl . intValue ( ) ) . append ( ' ' ) ; } if ( null != reliable ) { sb . append ( RELIABLE_STREAM_PARAM_NAME ) . append ( ' ' ) . append ( reliable ) . append ( ' ' ) ; } if ( null != linger ) { sb . append ( LINGER_PARAM_NAME ) . append ( ' ' ) . append ( linger . intValue ( ) ) . append ( ' ' ) ; } if ( null != alias ) { sb . append ( ALIAS_PARAM_NAME ) . append ( ' ' ) . append ( alias ) . append ( ' ' ) ; } if ( null != sparse ) { sb . append ( SPARSE_PARAM_NAME ) . append ( ' ' ) . append ( sparse ) . append ( ' ' ) ; } if ( null != eos ) { sb . append ( EOS_PARAM_NAME ) . append ( ' ' ) . append ( eos ) . append ( ' ' ) ; } if ( null != tether ) { sb . append ( TETHER_PARAM_NAME ) . append ( ' ' ) . append ( tether ) . append ( ' ' ) ; } final char lastChar = sb . charAt ( sb . length ( ) - 1 ) ; if ( lastChar == ' ' || lastChar == ' ' ) { sb . setLength ( sb . length ( ) - 1 ) ; } return sb . toString ( ) ; }


Input: Throw a { @link AeronException } with a message for a send error . [CODESPLIT] public static void sendError ( final int bytesToSend , final IOException ex , final InetSocketAddress destination ) { throw new AeronException ( "failed to send packet of " + bytesToSend + " bytes to " + destination , ex ) ; }


Input: Create the underlying channel for reading and writing . [CODESPLIT] public void openDatagramChannel ( final AtomicCounter statusIndicator ) { try { sendDatagramChannel = DatagramChannel . open ( udpChannel . protocolFamily ( ) ) ; receiveDatagramChannel = sendDatagramChannel ; if ( udpChannel . isMulticast ( ) ) { if ( null != connectAddress ) { receiveDatagramChannel = DatagramChannel . open ( udpChannel . protocolFamily ( ) ) ; } receiveDatagramChannel . setOption ( StandardSocketOptions . SO_REUSEADDR , true ) ; receiveDatagramChannel . bind ( new InetSocketAddress ( endPointAddress . getPort ( ) ) ) ; receiveDatagramChannel . join ( endPointAddress . getAddress ( ) , udpChannel . localInterface ( ) ) ; sendDatagramChannel . setOption ( StandardSocketOptions . IP_MULTICAST_IF , udpChannel . localInterface ( ) ) ; if ( udpChannel . isHasMulticastTtl ( ) ) { sendDatagramChannel . setOption ( StandardSocketOptions . IP_MULTICAST_TTL , udpChannel . multicastTtl ( ) ) ; multicastTtl = sendDatagramChannel . getOption ( StandardSocketOptions . IP_MULTICAST_TTL ) ; } else if ( context . socketMulticastTtl ( ) != 0 ) { sendDatagramChannel . setOption ( StandardSocketOptions . IP_MULTICAST_TTL , context . socketMulticastTtl ( ) ) ; multicastTtl = sendDatagramChannel . getOption ( StandardSocketOptions . IP_MULTICAST_TTL ) ; } } else { sendDatagramChannel . bind ( bindAddress ) ; } if ( null != connectAddress ) { sendDatagramChannel . connect ( connectAddress ) ; } if ( 0 != context . socketSndbufLength ( ) ) { sendDatagramChannel . setOption ( SO_SNDBUF , context . socketSndbufLength ( ) ) ; } if ( 0 != context . socketRcvbufLength ( ) ) { receiveDatagramChannel . setOption ( SO_RCVBUF , context . socketRcvbufLength ( ) ) ; } sendDatagramChannel . configureBlocking ( false ) ; receiveDatagramChannel . configureBlocking ( false ) ; } catch ( final IOException ex ) { if ( null != statusIndicator ) { statusIndicator . setOrdered ( ChannelEndpointStatus . ERRORED ) ; } CloseHelper . quietClose ( sendDatagramChannel ) ; if ( receiveDatagramChannel != sendDatagramChannel ) { CloseHelper . quietClose ( receiveDatagramChannel ) ; } sendDatagramChannel = null ; receiveDatagramChannel = null ; throw new AeronException ( "channel error - " + ex . getMessage ( ) + " (at " + ex . getStackTrace ( ) [ 0 ] . toString ( ) + "): " + udpChannel . originalUriString ( ) , ex ) ; } }


Input: Close transport canceling any pending read operations and closing channel [CODESPLIT] public void close ( ) { if ( ! isClosed ) { isClosed = true ; try { if ( null != selectionKey ) { selectionKey . cancel ( ) ; } if ( null != transportPoller ) { transportPoller . cancelRead ( this ) ; transportPoller . selectNowWithoutProcessing ( ) ; } if ( null != sendDatagramChannel ) { sendDatagramChannel . close ( ) ; } if ( receiveDatagramChannel != sendDatagramChannel && null != receiveDatagramChannel ) { receiveDatagramChannel . close ( ) ; } if ( null != transportPoller ) { transportPoller . selectNowWithoutProcessing ( ) ; } } catch ( final IOException ex ) { errorLog . record ( ex ) ; } } }


Input: Is the received frame valid . This method will do some basic checks on the header and can be overridden in a subclass for further validation . [CODESPLIT] public boolean isValidFrame ( final UnsafeBuffer buffer , final int length ) { boolean isFrameValid = true ; if ( frameVersion ( buffer , 0 ) != HeaderFlyweight . CURRENT_VERSION ) { isFrameValid = false ; invalidPackets . increment ( ) ; } else if ( length < HeaderFlyweight . MIN_HEADER_LENGTH ) { isFrameValid = false ; invalidPackets . increment ( ) ; } return isFrameValid ; }


Input: Receive a datagram from the media layer . [CODESPLIT] public InetSocketAddress receive ( final ByteBuffer buffer ) { buffer . clear ( ) ; InetSocketAddress address = null ; try { if ( receiveDatagramChannel . isOpen ( ) ) { address = ( InetSocketAddress ) receiveDatagramChannel . receive ( buffer ) ; } } catch ( final PortUnreachableException ignored ) { } catch ( final Exception ex ) { LangUtil . rethrowUnchecked ( ex ) ; } return address ; }


Input: Called on reception of a NAK to start retransmits handling . [CODESPLIT] public void onNak ( final int termId , final int termOffset , final int length , final int termLength , final RetransmitSender retransmitSender ) { if ( ! isInvalid ( termOffset , termLength ) ) { if ( null == activeRetransmitsMap . get ( termId , termOffset ) && activeRetransmitsMap . size ( ) < MAX_RETRANSMITS_DEFAULT ) { final RetransmitAction action = assignRetransmitAction ( ) ; action . termId = termId ; action . termOffset = termOffset ; action . length = Math . min ( length , termLength - termOffset ) ; final long delay = delayGenerator . generateDelay ( ) ; if ( 0 == delay ) { retransmitSender . resend ( termId , termOffset , action . length ) ; action . linger ( lingerTimeoutGenerator . generateDelay ( ) , nanoClock . nanoTime ( ) ) ; } else { action . delay ( delay , nanoClock . nanoTime ( ) ) ; } activeRetransmitsMap . put ( termId , termOffset , action ) ; } } }


Input: Called to indicate a retransmission is received that may obviate the need to send one ourselves . <p > NOTE : Currently only called from unit tests . Would be used for retransmitting from receivers for NAK suppression . [CODESPLIT] public void onRetransmitReceived ( final int termId , final int termOffset ) { final RetransmitAction action = activeRetransmitsMap . get ( termId , termOffset ) ; if ( null != action && DELAYED == action . state ) { activeRetransmitsMap . remove ( termId , termOffset ) ; action . cancel ( ) ; // do not go into linger } }


Input: Called to process any outstanding timeouts . [CODESPLIT] public void processTimeouts ( final long nowNs , final RetransmitSender retransmitSender ) { if ( activeRetransmitsMap . size ( ) > 0 ) { for ( final RetransmitAction action : retransmitActionPool ) { if ( DELAYED == action . state && ( action . expireNs - nowNs < 0 ) ) { retransmitSender . resend ( action . termId , action . termOffset , action . length ) ; action . linger ( lingerTimeoutGenerator . generateDelay ( ) , nanoClock . nanoTime ( ) ) ; } else if ( LINGERING == action . state && ( action . expireNs - nowNs < 0 ) ) { action . cancel ( ) ; activeRetransmitsMap . remove ( action . termId , action . termOffset ) ; } } } }


Input: Reset the poller to dispatch the descriptors returned from a query . [CODESPLIT] public void reset ( final long correlationId , final int subscriptionCount , final RecordingSubscriptionDescriptorConsumer consumer ) { this . correlationId = correlationId ; this . consumer = consumer ; this . remainingSubscriptionCount = subscriptionCount ; isDispatchComplete = false ; }


Input: The implementation of { @link ControlledFragmentHandler } that reassembles and forwards whole messages . [CODESPLIT] public Action onFragment ( final DirectBuffer buffer , final int offset , final int length , final Header header ) { final byte flags = header . flags ( ) ; Action action = Action . CONTINUE ; if ( ( flags & UNFRAGMENTED ) == UNFRAGMENTED ) { action = delegate . onFragment ( buffer , offset , length , header ) ; } else { if ( ( flags & BEGIN_FRAG_FLAG ) == BEGIN_FRAG_FLAG ) { final BufferBuilder builder = getBufferBuilder ( header . sessionId ( ) ) ; builder . reset ( ) . append ( buffer , offset , length ) ; } else { final BufferBuilder builder = builderBySessionIdMap . get ( header . sessionId ( ) ) ; if ( null != builder && builder . limit ( ) != 0 ) { final int limit = builder . limit ( ) ; builder . append ( buffer , offset , length ) ; if ( ( flags & END_FRAG_FLAG ) == END_FRAG_FLAG ) { final int msgLength = builder . limit ( ) ; action = delegate . onFragment ( builder . buffer ( ) , 0 , msgLength , header ) ; if ( Action . ABORT == action ) { builder . limit ( limit ) ; } else { builder . reset ( ) ; } } } } } return action ; }


Input: String representation of the channel status . [CODESPLIT] public static String status ( final long status ) { if ( INITIALIZING == status ) { return "INITIALIZING" ; } if ( ERRORED == status ) { return "ERRORED" ; } if ( ACTIVE == status ) { return "ACTIVE" ; } if ( CLOSING == status ) { return "CLOSING" ; } return "unknown id=" + status ; }


Input: Allocate an indicator for tracking the status of a channel endpoint . [CODESPLIT] public static AtomicCounter allocate ( final MutableDirectBuffer tempBuffer , final String name , final int typeId , final CountersManager countersManager , final String channel ) { final int keyLength = tempBuffer . putStringWithoutLengthAscii ( CHANNEL_OFFSET + SIZE_OF_INT , channel , 0 , MAX_CHANNEL_LENGTH ) ; tempBuffer . putInt ( CHANNEL_OFFSET , keyLength ) ; int labelLength = 0 ; labelLength += tempBuffer . putStringWithoutLengthAscii ( keyLength + labelLength , name ) ; labelLength += tempBuffer . putStringWithoutLengthAscii ( keyLength + labelLength , ": " ) ; labelLength += tempBuffer . putStringWithoutLengthAscii ( keyLength + labelLength , channel , 0 , MAX_LABEL_LENGTH - labelLength ) ; return countersManager . newCounter ( typeId , tempBuffer , 0 , keyLength , tempBuffer , keyLength , labelLength ) ; }


Input: The implementation of { @link FragmentHandler } that reassembles and forwards whole messages . [CODESPLIT] public void onFragment ( final DirectBuffer buffer , final int offset , final int length , final Header header ) { final byte flags = header . flags ( ) ; if ( ( flags & UNFRAGMENTED ) == UNFRAGMENTED ) { delegate . onFragment ( buffer , offset , length , header ) ; } else { handleFragment ( buffer , offset , length , header , flags ) ; } }


Input: Reset the values . [CODESPLIT] public DirectBufferVector reset ( final DirectBuffer buffer , final int offset , final int length ) { this . buffer = buffer ; this . offset = offset ; this . length = length ; return this ; }


Input: Ensure the vector is valid for the buffer . [CODESPLIT] public DirectBufferVector validate ( ) { final int capacity = buffer . capacity ( ) ; if ( offset < 0 || offset >= capacity ) { throw new IllegalArgumentException ( "offset=" + offset + " capacity=" + capacity ) ; } if ( length < 0 || length > ( capacity - offset ) ) { throw new IllegalArgumentException ( "offset=" + offset + " capacity=" + capacity + " length=" + length ) ; } return this ; }


Input: Validate an array of vectors to make up a message and compute the total length . [CODESPLIT] public static int validateAndComputeLength ( final DirectBufferVector [ ] vectors ) { int messageLength = 0 ; for ( final DirectBufferVector vector : vectors ) { vector . validate ( ) ; messageLength += vector . length ; if ( messageLength < 0 ) { throw new IllegalStateException ( "length overflow: " + Arrays . toString ( vectors ) ) ; } } return messageLength ; }


Input: How far ahead a producer can get from a consumer position . [CODESPLIT] public static int producerWindowLength ( final int termBufferLength , final int defaultTermWindowLength ) { int termWindowLength = termBufferLength / 2 ; if ( 0 != defaultTermWindowLength ) { termWindowLength = Math . min ( defaultTermWindowLength , termWindowLength ) ; } return termWindowLength ; }


Input: Get the { @link IdleStrategy } that should be applied to { @link org . agrona . concurrent . Agent } s . [CODESPLIT] public static IdleStrategy agentIdleStrategy ( final String strategyName , final StatusIndicator controllableStatus ) { IdleStrategy idleStrategy = null ; switch ( strategyName ) { case DEFAULT_IDLE_STRATEGY : idleStrategy = new BackoffIdleStrategy ( IDLE_MAX_SPINS , IDLE_MAX_YIELDS , IDLE_MIN_PARK_NS , IDLE_MAX_PARK_NS ) ; break ; case CONTROLLABLE_IDLE_STRATEGY : idleStrategy = new ControllableIdleStrategy ( controllableStatus ) ; controllableStatus . setOrdered ( ControllableIdleStrategy . PARK ) ; break ; default : try { idleStrategy = ( IdleStrategy ) Class . forName ( strategyName ) . getConstructor ( ) . newInstance ( ) ; } catch ( final Exception ex ) { LangUtil . rethrowUnchecked ( ex ) ; } break ; } return idleStrategy ; }


Input: Get the supplier of { @link SendChannelEndpoint } s which can be used for debugging monitoring or modifying the behaviour when sending to the channel . [CODESPLIT] public static SendChannelEndpointSupplier sendChannelEndpointSupplier ( ) { SendChannelEndpointSupplier supplier = null ; try { final String className = getProperty ( SEND_CHANNEL_ENDPOINT_SUPPLIER_PROP_NAME ) ; if ( null == className ) { return new DefaultSendChannelEndpointSupplier ( ) ; } supplier = ( SendChannelEndpointSupplier ) Class . forName ( className ) . getConstructor ( ) . newInstance ( ) ; } catch ( final Exception ex ) { LangUtil . rethrowUnchecked ( ex ) ; } return supplier ; }


Input: Get the supplier of { @link ReceiveChannelEndpoint } s which can be used for debugging monitoring or modifying the behaviour when receiving from the channel . [CODESPLIT] public static ReceiveChannelEndpointSupplier receiveChannelEndpointSupplier ( ) { ReceiveChannelEndpointSupplier supplier = null ; try { final String className = getProperty ( RECEIVE_CHANNEL_ENDPOINT_SUPPLIER_PROP_NAME ) ; if ( null == className ) { return new DefaultReceiveChannelEndpointSupplier ( ) ; } supplier = ( ReceiveChannelEndpointSupplier ) Class . forName ( className ) . getConstructor ( ) . newInstance ( ) ; } catch ( final Exception ex ) { LangUtil . rethrowUnchecked ( ex ) ; } return supplier ; }


Input: Get the supplier of { @link FlowControl } s which can be used for changing behavior of flow control for unicast publications . [CODESPLIT] public static FlowControlSupplier unicastFlowControlSupplier ( ) { FlowControlSupplier supplier = null ; try { final String className = getProperty ( UNICAST_FLOW_CONTROL_STRATEGY_SUPPLIER_PROP_NAME ) ; if ( null == className ) { return new DefaultUnicastFlowControlSupplier ( ) ; } supplier = ( FlowControlSupplier ) Class . forName ( className ) . getConstructor ( ) . newInstance ( ) ; } catch ( final Exception ex ) { LangUtil . rethrowUnchecked ( ex ) ; } return supplier ; }


Input: Get the supplier of { @link FlowControl } s which can be used for changing behavior of flow control for multicast publications . [CODESPLIT] public static FlowControlSupplier multicastFlowControlSupplier ( ) { FlowControlSupplier supplier = null ; try { final String className = getProperty ( MULTICAST_FLOW_CONTROL_STRATEGY_SUPPLIER_PROP_NAME ) ; if ( null == className ) { return new DefaultMulticastFlowControlSupplier ( ) ; } supplier = ( FlowControlSupplier ) Class . forName ( className ) . getConstructor ( ) . newInstance ( ) ; } catch ( final Exception ex ) { LangUtil . rethrowUnchecked ( ex ) ; } return supplier ; }


Input: Get the supplier of { @link CongestionControl } implementations which can be used for receivers . [CODESPLIT] public static CongestionControlSupplier congestionControlSupplier ( ) { CongestionControlSupplier supplier = null ; try { final String className = getProperty ( CONGESTION_CONTROL_STRATEGY_SUPPLIER_PROP_NAME ) ; if ( null == className ) { return new DefaultCongestionControlSupplier ( ) ; } supplier = ( CongestionControlSupplier ) Class . forName ( className ) . getConstructor ( ) . newInstance ( ) ; } catch ( final Exception ex ) { LangUtil . rethrowUnchecked ( ex ) ; } return supplier ; }


Input: Validate that the MTU is an appropriate length . MTU lengths must be a multiple of { @link FrameDescriptor#FRAME_ALIGNMENT } . [CODESPLIT] public static void validateMtuLength ( final int mtuLength ) { if ( mtuLength < DataHeaderFlyweight . HEADER_LENGTH || mtuLength > MAX_UDP_PAYLOAD_LENGTH ) { throw new ConfigurationException ( "mtuLength must be a >= HEADER_LENGTH and <= MAX_UDP_PAYLOAD_LENGTH: " + mtuLength ) ; } if ( ( mtuLength & ( FrameDescriptor . FRAME_ALIGNMENT - 1 ) ) != 0 ) { throw new ConfigurationException ( "mtuLength must be a multiple of FRAME_ALIGNMENT: " + mtuLength ) ; } }


Input: Get the { @link TerminationValidator } implementations which can be used for validating a termination request sent to the driver to ensure the client has the right to terminate a driver . [CODESPLIT] public static TerminationValidator terminationValidator ( ) { TerminationValidator validator = null ; try { final String className = getProperty ( TERMINATION_VALIDATOR_PROP_NAME ) ; if ( null == className ) { return new DefaultDenyTerminationValidator ( ) ; } validator = ( TerminationValidator ) Class . forName ( className ) . getConstructor ( ) . newInstance ( ) ; } catch ( final Exception ex ) { LangUtil . rethrowUnchecked ( ex ) ; } return validator ; }


Input: Validate that the socket buffer lengths are sufficient for the media driver configuration . [CODESPLIT] public static void validateSocketBufferLengths ( final MediaDriver . Context ctx ) { try ( DatagramChannel probe = DatagramChannel . open ( ) ) { final int defaultSoSndBuf = probe . getOption ( StandardSocketOptions . SO_SNDBUF ) ; probe . setOption ( StandardSocketOptions . SO_SNDBUF , Integer . MAX_VALUE ) ; final int maxSoSndBuf = probe . getOption ( StandardSocketOptions . SO_SNDBUF ) ; if ( maxSoSndBuf < ctx . socketSndbufLength ( ) ) { System . err . format ( "WARNING: Could not get desired SO_SNDBUF, adjust OS to allow %s: attempted=%d, actual=%d%n" , SOCKET_SNDBUF_LENGTH_PROP_NAME , ctx . socketSndbufLength ( ) , maxSoSndBuf ) ; } probe . setOption ( StandardSocketOptions . SO_RCVBUF , Integer . MAX_VALUE ) ; final int maxSoRcvBuf = probe . getOption ( StandardSocketOptions . SO_RCVBUF ) ; if ( maxSoRcvBuf < ctx . socketRcvbufLength ( ) ) { System . err . format ( "WARNING: Could not get desired SO_RCVBUF, adjust OS to allow %s: attempted=%d, actual=%d%n" , SOCKET_RCVBUF_LENGTH_PROP_NAME , ctx . socketRcvbufLength ( ) , maxSoRcvBuf ) ; } final int soSndBuf = 0 == ctx . socketSndbufLength ( ) ? defaultSoSndBuf : ctx . socketSndbufLength ( ) ; if ( ctx . mtuLength ( ) > soSndBuf ) { throw new ConfigurationException ( String . format ( "MTU greater than socket SO_SNDBUF, adjust %s to match MTU: mtuLength=%d, SO_SNDBUF=%d" , SOCKET_SNDBUF_LENGTH_PROP_NAME , ctx . mtuLength ( ) , soSndBuf ) ) ; } if ( ctx . initialWindowLength ( ) > maxSoRcvBuf ) { throw new ConfigurationException ( "window length greater than socket SO_RCVBUF, increase '" + Configuration . INITIAL_WINDOW_LENGTH_PROP_NAME + "' to match window: windowLength=" + ctx . initialWindowLength ( ) + ", SO_RCVBUF=" + maxSoRcvBuf ) ; } } catch ( final IOException ex ) { throw new AeronException ( "probe socket: " + ex . toString ( ) , ex ) ; } }


Input: Validate that page size is valid and alignment is valid . [CODESPLIT] public static void validatePageSize ( final int pageSize ) { if ( pageSize < PAGE_MIN_SIZE ) { throw new ConfigurationException ( "page size less than min size of " + PAGE_MIN_SIZE + ": " + pageSize ) ; } if ( pageSize > PAGE_MAX_SIZE ) { throw new ConfigurationException ( "page size greater than max size of " + PAGE_MAX_SIZE + ": " + pageSize ) ; } if ( ! BitUtil . isPowerOfTwo ( pageSize ) ) { throw new ConfigurationException ( "page size not a power of 2: " + pageSize ) ; } }


Input: Validate the range of session ids based on a high and low value provided which accounts for the values wrapping . [CODESPLIT] public static void validateSessionIdRange ( final int low , final int high ) { if ( low > high ) { throw new ConfigurationException ( "low session id value " + low + " must be <= high value " + high ) ; } if ( Math . abs ( ( long ) high - low ) > Integer . MAX_VALUE ) { throw new ConfigurationException ( "reserved range to too large" ) ; } }


Input: Validate that the timeouts for unblocking publications from a client are valid . [CODESPLIT] public static void validateUnblockTimeout ( final long publicationUnblockTimeoutNs , final long clientLivenessTimeoutNs , final long timerIntervalNs ) { if ( publicationUnblockTimeoutNs <= clientLivenessTimeoutNs ) { throw new ConfigurationException ( "publicationUnblockTimeoutNs=" + publicationUnblockTimeoutNs + " <= clientLivenessTimeoutNs=" + clientLivenessTimeoutNs ) ; } if ( clientLivenessTimeoutNs <= timerIntervalNs ) { throw new ConfigurationException ( "clientLivenessTimeoutNs=" + clientLivenessTimeoutNs + " <= timerIntervalNs=" + timerIntervalNs ) ; } }


Input: Set the error code for the command . [CODESPLIT] public ErrorResponseFlyweight errorCode ( final ErrorCode code ) { buffer . putInt ( offset + ERROR_CODE_OFFSET , code . value ( ) ) ; return this ; }


Input: Get the { @link Set } of { @link ClusterEventCode } s that are enabled for the logger . [CODESPLIT] static Set < ClusterEventCode > getEnabledClusterEventCodes ( final String enabledClusterEventCodes ) { if ( null == enabledClusterEventCodes || "" . equals ( enabledClusterEventCodes ) ) { return EnumSet . noneOf ( ClusterEventCode . class ) ; } final Function < Integer , ClusterEventCode > eventCodeById = ClusterEventCode :: get ; final Function < String , ClusterEventCode > eventCodeByName = ClusterEventCode :: valueOf ; final EnumSet < ClusterEventCode > allEventsSet = EnumSet . allOf ( ClusterEventCode . class ) ; return parseEventCodes ( enabledClusterEventCodes , eventCodeById , eventCodeByName , allEventsSet ) ; }


Input: Get the { @link Set } of { @link ArchiveEventCode } s that are enabled for the logger . [CODESPLIT] static Set < ArchiveEventCode > getEnabledArchiveEventCodes ( final String enabledArchiveEventCodes ) { if ( null == enabledArchiveEventCodes || "" . equals ( enabledArchiveEventCodes ) ) { return EnumSet . noneOf ( ArchiveEventCode . class ) ; } final Function < Integer , ArchiveEventCode > eventCodeById = ArchiveEventCode :: get ; final Function < String , ArchiveEventCode > eventCodeByName = ArchiveEventCode :: valueOf ; final EnumSet < ArchiveEventCode > allEventsSet = EnumSet . allOf ( ArchiveEventCode . class ) ; return parseEventCodes ( enabledArchiveEventCodes , eventCodeById , eventCodeByName , allEventsSet ) ; }


Input: Get the { @link Set } of { @link DriverEventCode } s that are enabled for the logger . [CODESPLIT] static Set < DriverEventCode > getEnabledDriverEventCodes ( final String enabledLoggerEventCodes ) { if ( null == enabledLoggerEventCodes || "" . equals ( enabledLoggerEventCodes ) ) { return EnumSet . noneOf ( DriverEventCode . class ) ; } final Set < DriverEventCode > eventCodeSet = new HashSet <> ( ) ; final String [ ] codeIds = enabledLoggerEventCodes . split ( "," ) ; for ( final String codeId : codeIds ) { switch ( codeId ) { case "all" : eventCodeSet . addAll ( ALL_LOGGER_EVENT_CODES ) ; break ; case "admin" : eventCodeSet . addAll ( ADMIN_ONLY_EVENT_CODES ) ; break ; default : { DriverEventCode code = null ; try { code = DriverEventCode . valueOf ( codeId ) ; } catch ( final IllegalArgumentException ignore ) { } if ( null == code ) { try { code = DriverEventCode . get ( Integer . parseInt ( codeId ) ) ; } catch ( final IllegalArgumentException ignore ) { } } if ( null != code ) { eventCodeSet . add ( code ) ; } else { System . err . println ( "unknown event code: " + codeId ) ; } } } } return eventCodeSet ; }


Input: Reset the state of a cluster member so it can be canvassed and reestablished . [CODESPLIT] public void reset ( ) { isBallotSent = false ; isLeader = false ; hasRequestedJoin = false ; hasSentTerminationAck = false ; vote = null ; candidateTermId = Aeron . NULL_VALUE ; leadershipTermId = Aeron . NULL_VALUE ; logPosition = NULL_POSITION ; }


Input: Parse the details for a cluster members from a string . <p > <code > member - id client - facing : port member - facing : port log : port transfer : port archive : port|1 ... < / code > [CODESPLIT] public static ClusterMember [ ] parse ( final String value ) { if ( null == value || value . length ( ) == 0 ) { return ClusterMember . EMPTY_CLUSTER_MEMBER_ARRAY ; } final String [ ] memberValues = value . split ( "\\|" ) ; final int length = memberValues . length ; final ClusterMember [ ] members = new ClusterMember [ length ] ; for ( int i = 0 ; i < length ; i ++ ) { final String endpointsDetail = memberValues [ i ] ; final String [ ] memberAttributes = endpointsDetail . split ( "," ) ; if ( memberAttributes . length != 6 ) { throw new ClusterException ( "invalid member value: " + endpointsDetail + " within: " + value ) ; } final String justEndpoints = String . join ( "," , memberAttributes [ 1 ] , memberAttributes [ 2 ] , memberAttributes [ 3 ] , memberAttributes [ 4 ] , memberAttributes [ 5 ] ) ; members [ i ] = new ClusterMember ( Integer . parseInt ( memberAttributes [ 0 ] ) , memberAttributes [ 1 ] , memberAttributes [ 2 ] , memberAttributes [ 3 ] , memberAttributes [ 4 ] , memberAttributes [ 5 ] , justEndpoints ) ; } return members ; }


Input: Encode member details from a cluster members array to a string . [CODESPLIT] public static String encodeAsString ( final ClusterMember [ ] clusterMembers ) { final StringBuilder builder = new StringBuilder ( ) ; for ( int i = 0 , length = clusterMembers . length ; i < length ; i ++ ) { final ClusterMember member = clusterMembers [ i ] ; builder . append ( member . id ( ) ) . append ( ' ' ) . append ( member . endpointsDetail ( ) ) ; if ( ( length - 1 ) != i ) { builder . append ( ' ' ) ; } } return builder . toString ( ) ; }


Input: Add the publications for sending status messages to the other members of the cluster . [CODESPLIT] public static void addMemberStatusPublications ( final ClusterMember [ ] members , final ClusterMember exclude , final ChannelUri channelUri , final int streamId , final Aeron aeron ) { for ( final ClusterMember member : members ) { if ( member != exclude ) { channelUri . put ( ENDPOINT_PARAM_NAME , member . memberFacingEndpoint ( ) ) ; member . publication = aeron . addExclusivePublication ( channelUri . toString ( ) , streamId ) ; } } }


Input: Close the publications associated with members of the cluster . [CODESPLIT] public static void closeMemberPublications ( final ClusterMember [ ] clusterMembers ) { for ( final ClusterMember member : clusterMembers ) { CloseHelper . close ( member . publication ) ; } }


Input: Add an exclusive { @link Publication } for communicating to a member on the member status channel . [CODESPLIT] public static void addMemberStatusPublication ( final ClusterMember member , final ChannelUri channelUri , final int streamId , final Aeron aeron ) { channelUri . put ( ENDPOINT_PARAM_NAME , member . memberFacingEndpoint ( ) ) ; member . publication = aeron . addExclusivePublication ( channelUri . toString ( ) , streamId ) ; }


Input: Populate map of { @link ClusterMember } s which can be looked up by id . [CODESPLIT] public static void addClusterMemberIds ( final ClusterMember [ ] clusterMembers , final Int2ObjectHashMap < ClusterMember > clusterMemberByIdMap ) { for ( final ClusterMember member : clusterMembers ) { clusterMemberByIdMap . put ( member . id ( ) , member ) ; } }


Input: Check if the cluster leader has an active quorum of cluster followers . [CODESPLIT] public static boolean hasActiveQuorum ( final ClusterMember [ ] clusterMembers , final long nowMs , final long timeoutMs ) { int threshold = quorumThreshold ( clusterMembers . length ) ; for ( final ClusterMember member : clusterMembers ) { if ( member . isLeader ( ) || nowMs <= ( member . timeOfLastAppendPositionMs ( ) + timeoutMs ) ) { if ( -- threshold <= 0 ) { return true ; } } } return false ; }


Input: Calculate the position reached by a quorum of cluster members . [CODESPLIT] public static long quorumPosition ( final ClusterMember [ ] members , final long [ ] rankedPositions ) { final int length = rankedPositions . length ; for ( int i = 0 ; i < length ; i ++ ) { rankedPositions [ i ] = 0 ; } for ( final ClusterMember member : members ) { long newPosition = member . logPosition ; for ( int i = 0 ; i < length ; i ++ ) { final long rankedPosition = rankedPositions [ i ] ; if ( newPosition > rankedPosition ) { rankedPositions [ i ] = newPosition ; newPosition = rankedPosition ; } } } return rankedPositions [ length - 1 ] ; }


Input: Reset the log position of all the members to the provided value . [CODESPLIT] public static void resetLogPositions ( final ClusterMember [ ] clusterMembers , final long logPosition ) { for ( final ClusterMember member : clusterMembers ) { member . logPosition ( logPosition ) ; } }


Input: Has the members of the cluster the voted reached the provided position in their log . [CODESPLIT] public static boolean haveVotersReachedPosition ( final ClusterMember [ ] clusterMembers , final long position , final long leadershipTermId ) { for ( final ClusterMember member : clusterMembers ) { if ( member . vote != null && ( member . logPosition < position || member . leadershipTermId != leadershipTermId ) ) { return false ; } } return true ; }


Input: Become a candidate by voting for yourself and resetting the other votes to { @link Aeron#NULL_VALUE } . [CODESPLIT] public static void becomeCandidate ( final ClusterMember [ ] members , final long candidateTermId , final int candidateMemberId ) { for ( final ClusterMember member : members ) { if ( member . id == candidateMemberId ) { member . vote ( Boolean . TRUE ) . candidateTermId ( candidateTermId ) . isBallotSent ( true ) ; } else { member . vote ( null ) . candidateTermId ( Aeron . NULL_VALUE ) . isBallotSent ( false ) ; } } }