Input: Decode a Base32 string into an array of binary bytes . [CODESPLIT] public static byte [ ] decode ( final String base32 ) throws IllegalArgumentException { switch ( base32 . length ( ) % 8 ) { case 1 : case 3 : case 6 : throw new IllegalArgumentException ( ERR_CANONICAL_LEN ) ; } byte [ ] bytes = new byte [ base32 . length ( ) * 5 / 8 ] ; int offset = 0 , i = 0 , lookup ; byte nextByte , digit ; while ( i < base32 . length ( ) ) { lookup = base32 . charAt ( i ++ ) - ' ' ; if ( lookup < 0 || lookup >= LOOKUP . length ) { throw new IllegalArgumentException ( ERR_INVALID_CHARS ) ; } digit = LOOKUP [ lookup ] ; if ( digit == - 1 ) { throw new IllegalArgumentException ( ERR_INVALID_CHARS ) ; } // STEP n = 0: leave 5 bits nextByte = ( byte ) ( digit << 3 ) ; lookup = base32 . charAt ( i ++ ) - ' ' ; if ( lookup < 0 || lookup >= LOOKUP . length ) { throw new IllegalArgumentException ( ERR_INVALID_CHARS ) ; } digit = LOOKUP [ lookup ] ; if ( digit == - 1 ) { throw new IllegalArgumentException ( ERR_INVALID_CHARS ) ; } // STEP n = 5: insert 3 bits, leave 2 bits bytes [ offset ++ ] = ( byte ) ( nextByte | ( digit >> 2 ) ) ; nextByte = ( byte ) ( ( digit & 3 ) << 6 ) ; if ( i >= base32 . length ( ) ) { if ( nextByte != ( byte ) 0 ) { throw new IllegalArgumentException ( ERR_CANONICAL_END ) ; } break ; } lookup = base32 . charAt ( i ++ ) - ' ' ; if ( lookup < 0 || lookup >= LOOKUP . length ) { throw new IllegalArgumentException ( ERR_INVALID_CHARS ) ; } digit = LOOKUP [ lookup ] ; if ( digit == - 1 ) { throw new IllegalArgumentException ( ERR_INVALID_CHARS ) ; } // STEP n = 2: leave 7 bits nextByte |= ( byte ) ( digit << 1 ) ; lookup = base32 . charAt ( i ++ ) - ' ' ; if ( lookup < 0 || lookup >= LOOKUP . length ) { throw new IllegalArgumentException ( ERR_INVALID_CHARS ) ; } digit = LOOKUP [ lookup ] ; if ( digit == - 1 ) { throw new IllegalArgumentException ( ERR_INVALID_CHARS ) ; } // STEP n = 7: insert 1 bit, leave 4 bits bytes [ offset ++ ] = ( byte ) ( nextByte | ( digit >> 4 ) ) ; nextByte = ( byte ) ( ( digit & 15 ) << 4 ) ; if ( i >= base32 . length ( ) ) { if ( nextByte != ( byte ) 0 ) { throw new IllegalArgumentException ( ERR_CANONICAL_END ) ; } break ; } lookup = base32 . charAt ( i ++ ) - ' ' ; if ( lookup < 0 || lookup >= LOOKUP . length ) { throw new IllegalArgumentException ( ERR_INVALID_CHARS ) ; } digit = LOOKUP [ lookup ] ; if ( digit == - 1 ) { throw new IllegalArgumentException ( ERR_INVALID_CHARS ) ; } // STEP n = 4: insert 4 bits, leave 1 bit bytes [ offset ++ ] = ( byte ) ( nextByte | ( digit >> 1 ) ) ; nextByte = ( byte ) ( ( digit & 1 ) << 7 ) ; if ( i >= base32 . length ( ) ) { if ( nextByte != ( byte ) 0 ) { throw new IllegalArgumentException ( ERR_CANONICAL_END ) ; } break ; } lookup = base32 . charAt ( i ++ ) - ' ' ; if ( lookup < 0 || lookup >= LOOKUP . length ) { throw new IllegalArgumentException ( ERR_INVALID_CHARS ) ; } digit = LOOKUP [ lookup ] ; if ( digit == - 1 ) { throw new IllegalArgumentException ( ERR_INVALID_CHARS ) ; } // STEP n = 1: leave 6 bits nextByte |= ( byte ) ( digit << 2 ) ; lookup = base32 . charAt ( i ++ ) - ' ' ; if ( lookup < 0 || lookup >= LOOKUP . length ) { throw new IllegalArgumentException ( ERR_INVALID_CHARS ) ; } digit = LOOKUP [ lookup ] ; if ( digit == - 1 ) { throw new IllegalArgumentException ( ERR_INVALID_CHARS ) ; } // STEP n = 6: insert 2 bits, leave 3 bits bytes [ offset ++ ] = ( byte ) ( nextByte | ( digit >> 3 ) ) ; nextByte = ( byte ) ( ( digit & 7 ) << 5 ) ; if ( i >= base32 . length ( ) ) { if ( nextByte != ( byte ) 0 ) { throw new IllegalArgumentException ( ERR_CANONICAL_END ) ; } break ; } lookup = base32 . charAt ( i ++ ) - ' ' ; if ( lookup < 0 || lookup >= LOOKUP . length ) { throw new IllegalArgumentException ( ERR_INVALID_CHARS ) ; } digit = LOOKUP [ lookup ] ; if ( digit == - 1 ) { throw new IllegalArgumentException ( ERR_INVALID_CHARS ) ; } // STEP n = 3: insert 5 bits, leave 0 bit bytes [ offset ++ ] = ( byte ) ( nextByte | digit ) ; } return bytes ; }


Input: Converts non - array value to array . Detects various types and collections iterates them to make conversion and to create target array . [CODESPLIT] protected byte [ ] convertValueToArray ( final Object value ) { if ( value instanceof Blob ) { final Blob blob = ( Blob ) value ; try { final long length = blob . length ( ) ; if ( length > Integer . MAX_VALUE ) { throw new TypeConversionException ( "Blob is too big." ) ; } return blob . getBytes ( 1 , ( int ) length ) ; } catch ( SQLException sex ) { throw new TypeConversionException ( value , sex ) ; } } if ( value instanceof File ) { try { return FileUtil . readBytes ( ( File ) value ) ; } catch ( IOException ioex ) { throw new TypeConversionException ( value , ioex ) ; } } if ( value instanceof Collection ) { final Collection collection = ( Collection ) value ; final byte [ ] target = new byte [ collection . size ( ) ] ; int i = 0 ; for ( final Object element : collection ) { target [ i ] = convertType ( element ) ; i ++ ; } return target ; } if ( value instanceof Iterable ) { final Iterable iterable = ( Iterable ) value ; final ArrayList < Byte > byteArrayList = new ArrayList <> ( ) ; for ( final Object element : iterable ) { final byte convertedValue = convertType ( element ) ; byteArrayList . add ( Byte . valueOf ( convertedValue ) ) ; } final byte [ ] array = new byte [ byteArrayList . size ( ) ] ; for ( int i = 0 ; i < byteArrayList . size ( ) ; i ++ ) { final Byte b = byteArrayList . get ( i ) ; array [ i ] = b . byteValue ( ) ; } return array ; } if ( value instanceof CharSequence ) { final String [ ] strings = StringUtil . splitc ( value . toString ( ) , ArrayConverter . NUMBER_DELIMITERS ) ; return convertArrayToArray ( strings ) ; } // everything else: return convertToSingleElementArray ( value ) ; }


Input: If browser supports gzip sets the Content - Encoding response header and invoke resource with a wrapped response that collects all the output . Extracts the output and write it into a gzipped byte array . Finally write that array to the client s output stream . <p > If browser does not support gzip invokes resource normally . [CODESPLIT] @ Override public void doFilter ( final ServletRequest request , final ServletResponse response , final FilterChain chain ) throws ServletException , IOException { HttpServletRequest req = ( HttpServletRequest ) request ; HttpServletResponse res = ( HttpServletResponse ) response ; if ( ( threshold == 0 ) || ( ! ServletUtil . isGzipSupported ( req ) ) || ( ! isGzipEligible ( req ) ) ) { chain . doFilter ( request , response ) ; return ; } GzipResponseWrapper wrappedResponse = new GzipResponseWrapper ( res ) ; wrappedResponse . setCompressionThreshold ( threshold ) ; try { chain . doFilter ( request , wrappedResponse ) ; } finally { wrappedResponse . finishResponse ( ) ; } }


Input: Filter initialization . [CODESPLIT] @ Override public void init ( final FilterConfig config ) { try { wildcards = Converter . get ( ) . toBooleanValue ( config . getInitParameter ( "wildcards" ) , false ) ; } catch ( TypeConversionException ignore ) { wildcards = false ; } // min size try { threshold = Converter . get ( ) . toIntValue ( config . getInitParameter ( "threshold" ) , 0 ) ; } catch ( TypeConversionException ignore ) { threshold = 0 ; } // match string String uriMatch = config . getInitParameter ( "match" ) ; if ( ( uriMatch != null ) && ( ! uriMatch . equals ( StringPool . STAR ) ) ) { matches = StringUtil . splitc ( uriMatch , ' ' ) ; for ( int i = 0 ; i < matches . length ; i ++ ) { matches [ i ] = matches [ i ] . trim ( ) ; } } // exclude string String uriExclude = config . getInitParameter ( "exclude" ) ; if ( uriExclude != null ) { excludes = StringUtil . splitc ( uriExclude , ' ' ) ; for ( int i = 0 ; i < excludes . length ; i ++ ) { excludes [ i ] = excludes [ i ] . trim ( ) ; } } // request parameter name requestParameterName = config . getInitParameter ( "requestParameterName" ) ; if ( requestParameterName == null ) { requestParameterName = "gzip" ; } requestParameterName = requestParameterName . trim ( ) ; // allowed extensions String urlExtensions = config . getInitParameter ( "extensions" ) ; if ( urlExtensions != null ) { if ( urlExtensions . equals ( StringPool . STAR ) ) { extensions = null ; } else { extensions = StringUtil . splitc ( urlExtensions , ", " ) ; } } else { extensions = new String [ ] { "html" , "htm" , "js" , "css" } ; } }


Input: Determine if request is eligible for GZipping . [CODESPLIT] protected boolean isGzipEligible ( final HttpServletRequest request ) { // request parameter name if ( requestParameterName . length ( ) != 0 ) { String forceGzipString = request . getParameter ( requestParameterName ) ; if ( forceGzipString != null ) { return Converter . get ( ) . toBooleanValue ( forceGzipString , false ) ; } } // extract uri String uri = request . getRequestURI ( ) ; if ( uri == null ) { return false ; } uri = uri . toLowerCase ( ) ; boolean result = false ; // check uri if ( matches == null ) { // match == * if ( extensions == null ) { // extensions == * return true ; } // extension String extension = FileNameUtil . getExtension ( uri ) ; if ( extension . length ( ) > 0 ) { extension = extension . toLowerCase ( ) ; if ( StringUtil . equalsOne ( extension , extensions ) != - 1 ) { result = true ; } } } else { if ( wildcards ) { result = Wildcard . matchPathOne ( uri , matches ) != - 1 ; } else { for ( String match : matches ) { if ( uri . contains ( match ) ) { result = true ; break ; } } } } if ( ( result ) && ( excludes != null ) ) { if ( wildcards ) { if ( Wildcard . matchPathOne ( uri , excludes ) != - 1 ) { result = false ; } } else { for ( String exclude : excludes ) { if ( uri . contains ( exclude ) ) { result = false ; // excludes founded break ; } } } } return result ; }


Input: Adds new { [CODESPLIT] public void addViolation ( final Violation v ) { if ( v == null ) { return ; } if ( violations == null ) { violations = new ArrayList <> ( ) ; } violations . add ( v ) ; }


Input: Validate object using context from the annotations . [CODESPLIT] public List < Violation > validate ( final Object target ) { return validate ( ValidationContext . resolveFor ( target . getClass ( ) ) , target ) ; }


Input: Performs validation of provided validation context and appends violations . [CODESPLIT] public List < Violation > validate ( final ValidationContext ctx , final Object target , final String targetName ) { for ( Map . Entry < String , List < Check > > entry : ctx . map . entrySet ( ) ) { String name = entry . getKey ( ) ; Object value = BeanUtil . declaredSilent . getProperty ( target , name ) ; String valueName = targetName != null ? ( targetName + ' ' + name ) : name ; // move up ValidationConstraintContext vcc = new ValidationConstraintContext ( this , target , valueName ) ; for ( Check check : entry . getValue ( ) ) { String [ ] checkProfiles = check . getProfiles ( ) ; if ( ! matchProfiles ( checkProfiles ) ) { continue ; } if ( check . getSeverity ( ) < severity ) { continue ; } ValidationConstraint constraint = check . getConstraint ( ) ; if ( ! constraint . isValid ( vcc , value ) ) { addViolation ( new Violation ( valueName , target , value , check ) ) ; } } } return getViolations ( ) ; }


Input: Enables single profile . [CODESPLIT] public void useProfile ( final String profile ) { if ( profile == null ) { return ; } if ( this . enabledProfiles == null ) { this . enabledProfiles = new HashSet <> ( ) ; } this . enabledProfiles . add ( profile ) ; }


Input: Enables list of profiles . [CODESPLIT] public void useProfiles ( final String ... enabledProfiles ) { if ( enabledProfiles == null ) { return ; } if ( this . enabledProfiles == null ) { this . enabledProfiles = new HashSet <> ( ) ; } Collections . addAll ( this . enabledProfiles , enabledProfiles ) ; }


Input: Determine if any of checks profiles is among enabled profiles . [CODESPLIT] protected boolean matchProfiles ( final String [ ] checkProfiles ) { // test for all profiles if ( ( checkProfiles != null ) && ( checkProfiles . length == 1 ) && checkProfiles [ 0 ] . equals ( ALL_PROFILES ) ) { return true ; } if ( enabledProfiles == null || enabledProfiles . isEmpty ( ) ) { if ( validateAllProfilesByDefault ) { return true ; // all profiles are considered as enabled } // only default profile is enabled if ( ( checkProfiles == null ) || ( checkProfiles . length == 0 ) ) { return true ; } for ( String profile : checkProfiles ) { if ( StringUtil . isEmpty ( profile ) ) { return true ; // default profile } if ( profile . equals ( DEFAULT_PROFILE ) ) { return true ; } } return false ; } // there are enabled profiles if ( ( checkProfiles == null ) || ( checkProfiles . length == 0 ) ) { return enabledProfiles . contains ( DEFAULT_PROFILE ) ; } boolean result = false ; for ( String profile : checkProfiles ) { boolean b = true ; boolean must = false ; if ( StringUtil . isEmpty ( profile ) ) { profile = DEFAULT_PROFILE ; } else if ( profile . charAt ( 0 ) == ' ' ) { profile = profile . substring ( 1 ) ; b = false ; } else if ( profile . charAt ( 0 ) == ' ' ) { profile = profile . substring ( 1 ) ; must = true ; } if ( enabledProfiles . contains ( profile ) ) { if ( ! b ) { return false ; } result = true ; } else { if ( must ) { return false ; } } } return result ; }


Input: Parses request body into the target type . [CODESPLIT] protected Object parseRequestBody ( final String body , final Class targetType ) { return JsonParser . create ( ) . parse ( body , targetType ) ; }


Input: Converts to milliseconds . [CODESPLIT] public long toMilliseconds ( ) { double then = ( fraction - JD_1970 . fraction ) * MILLIS_IN_DAY ; then += ( integer - JD_1970 . integer ) * MILLIS_IN_DAY ; then += then > 0 ? 1.0e-6 : - 1.0e-6 ; return ( long ) then ; }


Input: Adds a JD to current instance . [CODESPLIT] public JulianDate add ( final JulianDate jds ) { int i = this . integer + jds . integer ; double f = this . fraction + jds . fraction ; return new JulianDate ( i , f ) ; }


Input: Subtracts a JD from current instance . [CODESPLIT] public JulianDate sub ( final JulianDate jds ) { int i = this . integer - jds . integer ; double f = this . fraction - jds . fraction ; return new JulianDate ( i , f ) ; }


Input: Sets integer and fractional part with normalization . Normalization means that if double is out of range values will be correctly fixed . [CODESPLIT] private void set ( final int i , double f ) { integer = i ; int fi = ( int ) f ; f -= fi ; integer += fi ; if ( f < 0 ) { f += 1 ; integer -- ; } this . fraction = f ; }


Input: Returns span between two days . Returned value may be positive ( when this date is after the provided one ) or negative ( when comparing to future date ) . [CODESPLIT] public int daysSpan ( final JulianDate otherDate ) { int now = getJulianDayNumber ( ) ; int then = otherDate . getJulianDayNumber ( ) ; return now - then ; }


Input: ---------------------------------------------------------------- fg codes [CODESPLIT] public Chalk256 standard ( final int index ) { startSequence ( FG_CODES [ index ( index , 0 , 8 ) ] ) ; endSequence ( RESET ) ; return _this ( ) ; }


Input: Colors with red - green - blue value in the range 0 to 6 . [CODESPLIT] public Chalk256 rgb ( final int r , final int b , final int g ) { startSequence ( FG_CODES [ index ( 36 * r + 6 * g + b , 16 , 232 ) ] ) ; endSequence ( RESET ) ; return _this ( ) ; }


Input: ---------------------------------------------------------------- bg codes [CODESPLIT] public Chalk256 bgStandard ( final int index ) { startSequence ( BG_CODES [ index ( index , 0 , 8 ) ] ) ; endSequence ( RESET ) ; return _this ( ) ; }


Input: Colors with red - green - blue value in the range 0 to 6 . [CODESPLIT] public Chalk256 bgRgb ( final int r , final int b , final int g ) { startSequence ( BG_CODES [ index ( 36 * r + 6 * g + b , 16 , 232 ) ] ) ; endSequence ( RESET ) ; return _this ( ) ; }


Input: ---------------------------------------------------------------- bgcolors [CODESPLIT] private int index ( int index , final int from , final int to ) { index += from ; if ( ( index < from ) || ( index >= to ) ) { throw new IllegalArgumentException ( "Color index not in range: [0, " + ( to - from ) + "]" ) ; } return index ; }


Input: Initializes parser . [CODESPLIT] @ Override protected void initialize ( final char [ ] input ) { super . initialize ( input ) ; this . tag = new ParsedTag ( ) ; this . doctype = new ParsedDoctype ( ) ; this . text = new char [ 1024 ] ; this . textLen = 0 ; this . parsingTime = - 1 ; }


Input: Parses content and callback provided { [CODESPLIT] public void parse ( final TagVisitor visitor ) { tag . init ( config . caseSensitive ) ; this . parsingTime = System . currentTimeMillis ( ) ; this . visitor = visitor ; visitor . start ( ) ; parsing = true ; while ( parsing ) { state . parse ( ) ; } emitText ( ) ; visitor . end ( ) ; this . parsingTime = System . currentTimeMillis ( ) - parsingTime ; }


Input: Emits a comment . Also checks for conditional comments! [CODESPLIT] protected void emitComment ( final int from , final int to ) { if ( config . enableConditionalComments ) { // CC: downlevel-hidden starting if ( match ( CC_IF , from ) ) { int endBracketNdx = find ( ' ' , from + 3 , to ) ; CharSequence expression = charSequence ( from + 1 , endBracketNdx ) ; ndx = endBracketNdx + 1 ; char c = input [ ndx ] ; if ( c != ' ' ) { errorInvalidToken ( ) ; } visitor . condComment ( expression , true , true , false ) ; state = DATA_STATE ; return ; } if ( to > CC_ENDIF2 . length && match ( CC_ENDIF2 , to - CC_ENDIF2 . length ) ) { // CC: downlevel-hidden ending visitor . condComment ( _ENDIF , false , true , true ) ; state = DATA_STATE ; return ; } } CharSequence comment = charSequence ( from , to ) ; visitor . comment ( comment ) ; commentStart = - 1 ; }


Input: Prepares error message and reports it to the visitor . [CODESPLIT] protected void _error ( String message ) { if ( config . calculatePosition ) { Position currentPosition = position ( ndx ) ; message = message . concat ( StringPool . SPACE ) . concat ( currentPosition . toString ( ) ) ; } else { message = message . concat ( " [@" ) . concat ( Integer . toString ( ndx ) ) . concat ( StringPool . RIGHT_SQ_BRACKET ) ; } visitor . error ( message ) ; }


Input: ---------------------------------------------------------------- util [CODESPLIT] private boolean isAppropriateTagName ( final char [ ] lowerCaseNameToMatch , final int from , final int to ) { final int len = to - from ; if ( len != lowerCaseNameToMatch . length ) { return false ; } for ( int i = from , k = 0 ; i < to ; i ++ , k ++ ) { char c = input [ i ] ; c = CharUtil . toLowerAscii ( c ) ; if ( c != lowerCaseNameToMatch [ k ] ) { return false ; } } return true ; }


Input: Returns a salted PBKDF2 hash of the password . [CODESPLIT] public String createHash ( final char [ ] password ) { // Generate a random salt SecureRandom random = new SecureRandom ( ) ; byte [ ] salt = new byte [ saltBytes ] ; random . nextBytes ( salt ) ; // Hash the password byte [ ] hash = pbkdf2 ( password , salt , pbkdf2Iterations , hashBytes ) ; // format iterations:salt:hash return pbkdf2Iterations + ":" + StringUtil . toHexString ( salt ) + ":" + StringUtil . toHexString ( hash ) ; }


Input: Computes the PBKDF2 hash of a password . [CODESPLIT] private static byte [ ] pbkdf2 ( final char [ ] password , final byte [ ] salt , final int iterations , final int bytes ) { PBEKeySpec spec = new PBEKeySpec ( password , salt , iterations , bytes * 8 ) ; try { SecretKeyFactory skf = SecretKeyFactory . getInstance ( PBKDF2_ALGORITHM ) ; return skf . generateSecret ( spec ) . getEncoded ( ) ; } catch ( NoSuchAlgorithmException ignore ) { return null ; } catch ( InvalidKeySpecException e ) { throw new IllegalArgumentException ( e ) ; } }


Input: Converts a string of hexadecimal characters into a byte array . [CODESPLIT] private static byte [ ] fromHex ( final String hex ) { final byte [ ] binary = new byte [ hex . length ( ) / 2 ] ; for ( int i = 0 ; i < binary . length ; i ++ ) { binary [ i ] = ( byte ) Integer . parseInt ( hex . substring ( 2 * i , 2 * i + 2 ) , 16 ) ; } return binary ; }


Input: Resolves provider definition defined in a bean . [CODESPLIT] public ProviderDefinition [ ] resolveProviderDefinitions ( final Class type , final String name ) { return providerResolver . resolve ( type , name ) ; }


Input: Sets file name . [CODESPLIT] public EmailAttachmentBuilder name ( final String name ) { if ( name != null && ! name . trim ( ) . isEmpty ( ) ) { this . name = name ; } return this ; }


Input: Sets the { @link DataSource } . Common { @link DataSource } s include { @link ByteArrayDataSource } and { @link FileDataSource } . [CODESPLIT] public < T extends DataSource > EmailAttachmentBuilder content ( final T dataSource ) { this . dataSource = dataSource ; name ( dataSource . getName ( ) ) ; return this ; }


Input: Creates new { @link ByteArrayDataSource } and then calls { @link #content ( DataSource ) } . [CODESPLIT] public EmailAttachmentBuilder content ( final InputStream inputStream , final String contentType ) throws IOException { return content ( new ByteArrayDataSource ( inputStream , resolveContentType ( contentType ) ) ) ; }


Input: Creates new { @link ByteArrayDataSource } and then calls { @link #content ( DataSource ) } . [CODESPLIT] public EmailAttachmentBuilder content ( final byte [ ] bytes , final String contentType ) { return content ( new ByteArrayDataSource ( bytes , resolveContentType ( contentType ) ) ) ; }


Input: Creates { @link EmailAttachment } . [CODESPLIT] public EmailAttachment < ByteArrayDataSource > buildByteArrayDataSource ( ) throws MailException { try { final ByteArrayDataSource bads ; if ( dataSource instanceof ByteArrayDataSource ) { bads = ( ByteArrayDataSource ) dataSource ; } else { bads = new ByteArrayDataSource ( dataSource . getInputStream ( ) , dataSource . getContentType ( ) ) ; } checkDataSource ( ) ; return new EmailAttachment <> ( name , contentId , isInline , bads ) . setEmbeddedMessage ( targetMessage ) ; } catch ( final IOException ioexc ) { throw new MailException ( ioexc ) ; } }


Input: Creates { @link EmailAttachment } . [CODESPLIT] public EmailAttachment < FileDataSource > buildFileDataSource ( final String messageId , final File attachmentStorage ) throws MailException { try { final FileDataSource fds ; if ( dataSource instanceof FileDataSource ) { fds = ( FileDataSource ) dataSource ; } else { final File file = new File ( attachmentStorage , messageId ) ; FileUtil . writeStream ( file , dataSource . getInputStream ( ) ) ; fds = new FileDataSource ( file ) ; } checkDataSource ( ) ; return new EmailAttachment <> ( name , contentId , isInline , fds ) . setEmbeddedMessage ( targetMessage ) ; } catch ( final IOException ioexc ) { throw new MailException ( ioexc ) ; } }


Input: Set content ID if it is missing . [CODESPLIT] protected EmailAttachmentBuilder setContentIdFromNameIfMissing ( ) { if ( contentId == null ) { if ( name != null ) { contentId ( FileNameUtil . getName ( name ) ) ; } else { contentId ( NO_NAME ) ; } } return this ; }


Input: Resolves content type from all data . [CODESPLIT] protected String resolveContentType ( final String contentType ) { if ( contentType != null ) { return contentType ; } if ( name == null ) { return MimeTypes . MIME_APPLICATION_OCTET_STREAM ; } final String extension = FileNameUtil . getExtension ( name ) ; return MimeTypes . getMimeType ( extension ) ; }


Input: Makes the given visitor visit the signature of this { @link SignatureReader } . This signature is the one specified in the constructor ( see { @link #SignatureReader } ) . This method is intended to be called on a { @link SignatureReader } that was created using a <i > ClassSignature< / i > ( such as the <code > signature< / code > parameter of the { @link org . objectweb . asm . ClassVisitor#visit } method ) or a <i > MethodSignature< / i > ( such as the <code > signature< / code > parameter of the { @link org . objectweb . asm . ClassVisitor#visitMethod } method ) . [CODESPLIT] public void accept ( final SignatureVisitor signatureVistor ) { String signature = this . signatureValue ; int length = signature . length ( ) ; int offset ; // Current offset in the parsed signature (parsed from left to right). char currentChar ; // The signature character at 'offset', or just before. // If the signature starts with '<', it starts with TypeParameters, i.e. a formal type parameter // identifier, followed by one or more pair ':',ReferenceTypeSignature (for its class bound and // interface bounds). if ( signature . charAt ( 0 ) == ' ' ) { // Invariant: offset points to the second character of a formal type parameter name at the // beginning of each iteration of the loop below. offset = 2 ; do { // The formal type parameter name is everything between offset - 1 and the first ':'. int classBoundStartOffset = signature . indexOf ( ' ' , offset ) ; signatureVistor . visitFormalTypeParameter ( signature . substring ( offset - 1 , classBoundStartOffset ) ) ; // If the character after the ':' class bound marker is not the start of a // ReferenceTypeSignature, it means the class bound is empty (which is a valid case). offset = classBoundStartOffset + 1 ; currentChar = signature . charAt ( offset ) ; if ( currentChar == ' ' || currentChar == ' ' || currentChar == ' ' ) { offset = parseType ( signature , offset , signatureVistor . visitClassBound ( ) ) ; } // While the character after the class bound or after the last parsed interface bound // is ':', we need to parse another interface bound. while ( ( currentChar = signature . charAt ( offset ++ ) ) == ' ' ) { offset = parseType ( signature , offset , signatureVistor . visitInterfaceBound ( ) ) ; } // At this point a TypeParameter has been fully parsed, and we need to parse the next one // (note that currentChar is now the first character of the next TypeParameter, and that // offset points to the second character), unless the character just after this // TypeParameter signals the end of the TypeParameters. } while ( currentChar != ' ' ) ; } else { offset = 0 ; } // If the (optional) TypeParameters is followed by '(' this means we are parsing a // MethodSignature, which has JavaTypeSignature type inside parentheses, followed by a Result // type and optional ThrowsSignature types. if ( signature . charAt ( offset ) == ' ' ) { offset ++ ; while ( signature . charAt ( offset ) != ' ' ) { offset = parseType ( signature , offset , signatureVistor . visitParameterType ( ) ) ; } // Use offset + 1 to skip ')'. offset = parseType ( signature , offset + 1 , signatureVistor . visitReturnType ( ) ) ; while ( offset < length ) { // Use offset + 1 to skip the first character of a ThrowsSignature, i.e. '^'. offset = parseType ( signature , offset + 1 , signatureVistor . visitExceptionType ( ) ) ; } } else { // Otherwise we are parsing a ClassSignature (by hypothesis on the method input), which has // one or more ClassTypeSignature for the super class and the implemented interfaces. offset = parseType ( signature , offset , signatureVistor . visitSuperclass ( ) ) ; while ( offset < length ) { offset = parseType ( signature , offset , signatureVistor . visitInterface ( ) ) ; } } }


Input: Parses a JavaTypeSignature and makes the given visitor visit it . [CODESPLIT] private static int parseType ( final String signature , final int startOffset , final SignatureVisitor signatureVisitor ) { int offset = startOffset ; // Current offset in the parsed signature. char currentChar = signature . charAt ( offset ++ ) ; // The signature character at 'offset'. // Switch based on the first character of the JavaTypeSignature, which indicates its kind. switch ( currentChar ) { case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : // Case of a BaseType or a VoidDescriptor. signatureVisitor . visitBaseType ( currentChar ) ; return offset ; case ' ' : // Case of an ArrayTypeSignature, a '[' followed by a JavaTypeSignature. return parseType ( signature , offset , signatureVisitor . visitArrayType ( ) ) ; case ' ' : // Case of TypeVariableSignature, an identifier between 'T' and ';'. int endOffset = signature . indexOf ( ' ' , offset ) ; signatureVisitor . visitTypeVariable ( signature . substring ( offset , endOffset ) ) ; return endOffset + 1 ; case ' ' : // Case of a ClassTypeSignature, which ends with ';'. // These signatures have a main class type followed by zero or more inner class types // (separated by '.'). Each can have type arguments, inside '<' and '>'. int start = offset ; // The start offset of the currently parsed main or inner class name. boolean visited = false ; // Whether the currently parsed class name has been visited. boolean inner = false ; // Whether we are currently parsing an inner class type. // Parses the signature, one character at a time. while ( true ) { currentChar = signature . charAt ( offset ++ ) ; if ( currentChar == ' ' || currentChar == ' ' ) { // If a '.' or ';' is encountered, this means we have fully parsed the main class name // or an inner class name. This name may already have been visited it is was followed by // type arguments between '<' and '>'. If not, we need to visit it here. if ( ! visited ) { String name = signature . substring ( start , offset - 1 ) ; if ( inner ) { signatureVisitor . visitInnerClassType ( name ) ; } else { signatureVisitor . visitClassType ( name ) ; } } // If we reached the end of the ClassTypeSignature return, otherwise start the parsing // of a new class name, which is necessarily an inner class name. if ( currentChar == ' ' ) { signatureVisitor . visitEnd ( ) ; break ; } start = offset ; visited = false ; inner = true ; } else if ( currentChar == ' ' ) { // If a '<' is encountered, this means we have fully parsed the main class name or an // inner class name, and that we now need to parse TypeArguments. First, we need to // visit the parsed class name. String name = signature . substring ( start , offset - 1 ) ; if ( inner ) { signatureVisitor . visitInnerClassType ( name ) ; } else { signatureVisitor . visitClassType ( name ) ; } visited = true ; // Now, parse the TypeArgument(s), one at a time. while ( ( currentChar = signature . charAt ( offset ) ) != ' ' ) { switch ( currentChar ) { case ' ' : // Unbounded TypeArgument. ++ offset ; signatureVisitor . visitTypeArgument ( ) ; break ; case ' ' : case ' ' : // Extends or Super TypeArgument. Use offset + 1 to skip the '+' or '-'. offset = parseType ( signature , offset + 1 , signatureVisitor . visitTypeArgument ( currentChar ) ) ; break ; default : // Instanceof TypeArgument. The '=' is implicit. offset = parseType ( signature , offset , signatureVisitor . visitTypeArgument ( ' ' ) ) ; break ; } } } } return offset ; default : throw new IllegalArgumentException ( ) ; } }


Input: Returns the size of the Module ModulePackages and ModuleMainClass attributes generated by this ModuleWriter . Also add the names of these attributes in the constant pool . [CODESPLIT] int computeAttributesSize ( ) { symbolTable . addConstantUtf8 ( Constants . MODULE ) ; // 6 attribute header bytes, 6 bytes for name, flags and version, and 5 * 2 bytes for counts. int size = 22 + requires . length + exports . length + opens . length + usesIndex . length + provides . length ; if ( packageCount > 0 ) { symbolTable . addConstantUtf8 ( Constants . MODULE_PACKAGES ) ; // 6 attribute header bytes, and 2 bytes for package_count. size += 8 + packageIndex . length ; } if ( mainClassIndex > 0 ) { symbolTable . addConstantUtf8 ( Constants . MODULE_MAIN_CLASS ) ; // 6 attribute header bytes, and 2 bytes for main_class_index. size += 8 ; } return size ; }


Input: Puts the Module ModulePackages and ModuleMainClass attributes generated by this ModuleWriter in the given ByteVector . [CODESPLIT] void putAttributes ( final ByteVector output ) { // 6 bytes for name, flags and version, and 5 * 2 bytes for counts. int moduleAttributeLength = 16 + requires . length + exports . length + opens . length + usesIndex . length + provides . length ; output . putShort ( symbolTable . addConstantUtf8 ( Constants . MODULE ) ) . putInt ( moduleAttributeLength ) . putShort ( moduleNameIndex ) . putShort ( moduleFlags ) . putShort ( moduleVersionIndex ) . putShort ( requiresCount ) . putByteArray ( requires . data , 0 , requires . length ) . putShort ( exportsCount ) . putByteArray ( exports . data , 0 , exports . length ) . putShort ( opensCount ) . putByteArray ( opens . data , 0 , opens . length ) . putShort ( usesCount ) . putByteArray ( usesIndex . data , 0 , usesIndex . length ) . putShort ( providesCount ) . putByteArray ( provides . data , 0 , provides . length ) ; if ( packageCount > 0 ) { output . putShort ( symbolTable . addConstantUtf8 ( Constants . MODULE_PACKAGES ) ) . putInt ( 2 + packageIndex . length ) . putShort ( packageCount ) . putByteArray ( packageIndex . data , 0 , packageIndex . length ) ; } if ( mainClassIndex > 0 ) { output . putShort ( symbolTable . addConstantUtf8 ( Constants . MODULE_MAIN_CLASS ) ) . putInt ( 2 ) . putShort ( mainClassIndex ) ; } }


Input: Decodes URL elements . This method may be used for all parts of URL except for the query parts since it does not decode the + character . [CODESPLIT] public static String decode ( final String source , final String encoding ) { return decode ( source , encoding , false ) ; }


Input: Decodes query name or value . [CODESPLIT] public static String decodeQuery ( final String source , final String encoding ) { return decode ( source , encoding , true ) ; }


Input: Initializes database . First creates connection pool . and transaction manager . Then Jodds DbEntityManager is configured . It is also configured automagically by scanning the class path for entities . [CODESPLIT] @ Override @ SuppressWarnings ( "unchecked" ) public void start ( ) { initLogger ( ) ; if ( ! databaseEnabled ) { log . info ( "DB not enabled." ) ; return ; } log . info ( "DB start ----------" ) ; final PetiteContainer petiteContainer = joyPetiteSupplier . get ( ) . getPetiteContainer ( ) ; // connection pool connectionProvider = createConnectionProviderIfNotSupplied ( ) ; petiteContainer . addBean ( beanNamePrefix ( ) + "pool" , connectionProvider ) ; if ( connectionProvider instanceof CoreConnectionPool ) { final CoreConnectionPool pool = ( CoreConnectionPool ) connectionProvider ; if ( pool . getDriver ( ) == null ) { databaseEnabled = false ; log . warn ( "DB configuration not set (" + beanNamePrefix ( ) + "pool.*). DB will be disabled." ) ; return ; } } connectionProvider . init ( ) ; checkConnectionProvider ( ) ; // transactions manager jtxManager = createJtxTransactionManager ( connectionProvider ) ; jtxManager . setValidateExistingTransaction ( true ) ; final AnnotationTxAdviceManager annTxAdviceManager = new AnnotationTxAdviceManager ( new LeanJtxWorker ( jtxManager ) , jtxScopePattern ) ; AnnotationTxAdviceSupport . manager = annTxAdviceManager ; // create proxy joyProxettaSupplier . get ( ) . getProxetta ( ) . withAspect ( createTxProxyAspects ( annTxAdviceManager . getAnnotations ( ) ) ) ; final DbSessionProvider sessionProvider = new DbJtxSessionProvider ( jtxManager ) ; // querymap final long startTime = System . currentTimeMillis ( ) ; final QueryMap queryMap = new DbPropsQueryMap ( ) ; log . debug ( "Queries loaded in " + ( System . currentTimeMillis ( ) - startTime ) + "ms." ) ; log . debug ( "Total queries: " + queryMap . size ( ) ) ; // dboom dbOom = DbOom . create ( ) . withConnectionProvider ( connectionProvider ) . withSessionProvider ( sessionProvider ) . withQueryMap ( queryMap ) . get ( ) ; dbOom . connect ( ) ; final DbEntityManager dbEntityManager = dbOom . entityManager ( ) ; dbEntityManager . reset ( ) ; petiteContainer . addBean ( beanNamePrefix ( ) + "query" , dbOom . queryConfig ( ) ) ; petiteContainer . addBean ( beanNamePrefix ( ) + "oom" , dbOom . config ( ) ) ; // automatic configuration if ( autoConfiguration ) { final AutomagicDbOomConfigurator automagicDbOomConfigurator = new AutomagicDbOomConfigurator ( dbEntityManager , true ) ; automagicDbOomConfigurator . registerAsConsumer ( joyScannerSupplier . get ( ) . getClassScanner ( ) ) ; } dbEntityManagerConsumers . accept ( dbEntityManager ) ; log . info ( "DB OK!" ) ; }


Input: Checks if connection provider can return a connection . [CODESPLIT] protected void checkConnectionProvider ( ) { final Connection connection = connectionProvider . getConnection ( ) ; try { final DatabaseMetaData databaseMetaData = connection . getMetaData ( ) ; String name = databaseMetaData . getDatabaseProductName ( ) ; String version = databaseMetaData . getDatabaseProductVersion ( ) ; if ( log . isInfoEnabled ( ) ) { log . info ( "Connected to database: " + name + " v" + version ) ; } } catch ( SQLException sex ) { log . error ( "DB connection failed: " , sex ) ; } finally { connectionProvider . closeConnection ( connection ) ; } }


Input: ---------------------------------------------------------------- print [CODESPLIT] public void printEntities ( final int width ) { if ( ! databaseEnabled ) { return ; } final List < DbEntityDescriptor > list = new ArrayList <> ( ) ; dbOom . entityManager ( ) . forEachEntity ( list :: add ) ; if ( list . isEmpty ( ) ) { return ; } final Print print = new Print ( ) ; print . line ( "Entities" , width ) ; list . stream ( ) . sorted ( Comparator . comparing ( DbEntityDescriptor :: getEntityName ) ) . forEach ( ded -> print . outLeftRightNewLine ( Chalk256 . chalk ( ) . yellow ( ) , ded . getTableName ( ) , Chalk256 . chalk ( ) . blue ( ) , ClassUtil . getShortClassName ( ded . getType ( ) , 2 ) , width ) ) ; print . line ( width ) ; }


Input: Returns method signature for some method . If signature is not found returns <code > null< / code > . Founded signatures means that those method can be proxyfied . [CODESPLIT] public MethodSignatureVisitor lookupMethodSignatureVisitor ( final int access , final String name , final String desc , final String className ) { String key = ProxettaAsmUtil . createMethodSignaturesKey ( access , name , desc , className ) ; return methodSignatures . get ( key ) ; }


Input: ---------------------------------------------------------------- visits [CODESPLIT] @ Override public void visit ( final int version , final int access , final String name , final String signature , final String superName , final String [ ] interfaces ) { final int lastSlash = name . lastIndexOf ( ' ' ) ; this . thisReference = name ; this . superName = superName ; this . nextSupername = superName ; this . targetPackage = lastSlash == - 1 ? StringPool . EMPTY : name . substring ( 0 , lastSlash ) . replace ( ' ' , ' ' ) ; this . targetClassname = name . substring ( lastSlash + 1 ) ; this . isTargetInterface = ( access & AsmUtil . ACC_INTERFACE ) != 0 ; if ( this . isTargetInterface ) { nextInterfaces = new HashSet <> ( ) ; if ( interfaces != null ) { Collections . addAll ( nextInterfaces , interfaces ) ; } } generics = new GenericsReader ( ) . parseSignatureForGenerics ( signature , isTargetInterface ) ; }


Input: Stores method signature for target method . [CODESPLIT] @ Override public MethodVisitor visitMethod ( final int access , final String name , final String desc , final String signature , final String [ ] exceptions ) { //		if ((access & AsmUtil.ACC_FINAL) != 0) { //			return null;	// skip finals //		} MethodSignatureVisitor msign = createMethodSignature ( access , name , desc , signature , exceptions , thisReference , this . generics ) ; String key = ProxettaAsmUtil . createMethodSignaturesKey ( access , name , desc , thisReference ) ; methodSignatures . put ( key , msign ) ; allMethodSignatures . add ( msign . getCleanSignature ( ) ) ; return new MethodAnnotationReader ( msign ) ; }


Input: Stores signatures for all super public methods not already overridden by target class . All this methods will be accepted for proxyfication . [CODESPLIT] @ Override public void visitEnd ( ) { // prepare class annotations if ( classAnnotations != null ) { annotations = classAnnotations . toArray ( new AnnotationInfo [ 0 ] ) ; classAnnotations = null ; } List < String > superList = new ArrayList <> ( ) ; Set < String > allInterfaces = new HashSet <> ( ) ; if ( nextInterfaces != null ) { allInterfaces . addAll ( nextInterfaces ) ; } // check all public super methods that are not overridden in superclass while ( nextSupername != null ) { InputStream inputStream = null ; ClassReader cr ; try { inputStream = ClassLoaderUtil . getClassAsStream ( nextSupername , classLoader ) ; cr = new ClassReader ( inputStream ) ; } catch ( IOException ioex ) { throw new ProxettaException ( "Unable to inspect super class: " + nextSupername , ioex ) ; } finally { StreamUtil . close ( inputStream ) ; } superList . add ( nextSupername ) ; superClassReaders . add ( cr ) ; // remember the super class reader cr . accept ( new SuperClassVisitor ( ) , 0 ) ; if ( cr . getInterfaces ( ) != null ) { Collections . addAll ( allInterfaces , cr . getInterfaces ( ) ) ; } } superClasses = superList . toArray ( new String [ 0 ] ) ; // check all interface methods that are not overridden in super-interface Set < String > todoInterfaces = new HashSet <> ( allInterfaces ) ; Set < String > newCollectedInterfaces = new HashSet <> ( ) ; while ( true ) { for ( String next : todoInterfaces ) { InputStream inputStream = null ; ClassReader cr ; try { inputStream = ClassLoaderUtil . getClassAsStream ( next , classLoader ) ; cr = new ClassReader ( inputStream ) ; } catch ( IOException ioex ) { throw new ProxettaException ( "Unable to inspect super interface: " + next , ioex ) ; } finally { StreamUtil . close ( inputStream ) ; } superClassReaders . add ( cr ) ; // remember the super class reader cr . accept ( new SuperClassVisitor ( ) , 0 ) ; if ( cr . getInterfaces ( ) != null ) { for ( String newInterface : cr . getInterfaces ( ) ) { if ( ! allInterfaces . contains ( newInterface ) && ! todoInterfaces . contains ( newInterface ) ) { // new interface found newCollectedInterfaces . add ( newInterface ) ; } } } } // perform collection allInterfaces . addAll ( todoInterfaces ) ; if ( newCollectedInterfaces . isEmpty ( ) ) { // no new interface found break ; } todoInterfaces . clear ( ) ; todoInterfaces . addAll ( newCollectedInterfaces ) ; newCollectedInterfaces . clear ( ) ; } }


Input: Creates method signature from method name . [CODESPLIT] protected MethodSignatureVisitor createMethodSignature ( final int access , final String methodName , final String description , final String signature , final String [ ] exceptions , final String classname , final Map < String , String > declaredTypeGenerics ) { MethodSignatureVisitor v = new MethodSignatureVisitor ( methodName , access , classname , description , exceptions , signature , declaredTypeGenerics , this ) ; new SignatureReader ( signature != null ? signature : description ) . accept ( v ) ; return v ; }


Input: Parse fields as csv string [CODESPLIT] public static String toCsvString ( final Object ... elements ) { StringBuilder line = new StringBuilder ( ) ; int last = elements . length - 1 ; for ( int i = 0 ; i < elements . length ; i ++ ) { if ( elements [ i ] == null ) { if ( i != last ) { line . append ( FIELD_SEPARATOR ) ; } continue ; } String field = elements [ i ] . toString ( ) ; // check for special cases int ndx = field . indexOf ( FIELD_SEPARATOR ) ; if ( ndx == - 1 ) { ndx = field . indexOf ( FIELD_QUOTE ) ; } if ( ndx == - 1 ) { if ( field . startsWith ( StringPool . SPACE ) || field . endsWith ( StringPool . SPACE ) ) { ndx = 1 ; } } if ( ndx == - 1 ) { ndx = StringUtil . indexOfChars ( field , SPECIAL_CHARS ) ; } // add field if ( ndx != - 1 ) { line . append ( FIELD_QUOTE ) ; } field = StringUtil . replace ( field , StringPool . QUOTE , DOUBLE_QUOTE ) ; line . append ( field ) ; if ( ndx != - 1 ) { line . append ( FIELD_QUOTE ) ; } // last if ( i != last ) { line . append ( FIELD_SEPARATOR ) ; } } return line . toString ( ) ; }


Input: Converts CSV line to string array . [CODESPLIT] public static String [ ] toStringArray ( final String line ) { List < String > row = new ArrayList <> ( ) ; boolean inQuotedField = false ; int fieldStart = 0 ; final int len = line . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) { char c = line . charAt ( i ) ; if ( c == FIELD_SEPARATOR ) { if ( ! inQuotedField ) { // ignore we are quoting addField ( row , line , fieldStart , i , inQuotedField ) ; fieldStart = i + 1 ; } } else if ( c == FIELD_QUOTE ) { if ( inQuotedField ) { if ( i + 1 == len || line . charAt ( i + 1 ) == FIELD_SEPARATOR ) { // we are already quoting - peek to see if this is the end of the field addField ( row , line , fieldStart , i , inQuotedField ) ; fieldStart = i + 2 ; i ++ ; // and skip the comma inQuotedField = false ; } } else if ( fieldStart == i ) { inQuotedField = true ; // this is a beginning of a quote fieldStart ++ ; // move field start } } } // add last field - but only if string was not empty if ( len > 0 && fieldStart <= len ) { addField ( row , line , fieldStart , len , inQuotedField ) ; } return row . toArray ( new String [ 0 ] ) ; }


Input: Resolves constructor injection point from type . Looks for single annotated constructor . If no annotated constructors found the total number of constructors will be checked . If there is only one constructor that one will be used as injection point . If more constructors exist the default one will be used as injection point . Otherwise exception is thrown . [CODESPLIT] public CtorInjectionPoint resolve ( final Class type , final boolean useAnnotation ) { // lookup methods ClassDescriptor cd = ClassIntrospector . get ( ) . lookup ( type ) ; CtorDescriptor [ ] allCtors = cd . getAllCtorDescriptors ( ) ; Constructor foundedCtor = null ; Constructor defaultCtor = null ; BeanReferences [ ] references = null ; for ( CtorDescriptor ctorDescriptor : allCtors ) { Constructor < ? > ctor = ctorDescriptor . getConstructor ( ) ; Class < ? > [ ] paramTypes = ctor . getParameterTypes ( ) ; if ( paramTypes . length == 0 ) { defaultCtor = ctor ; // detects default ctors } if ( ! useAnnotation ) { continue ; } BeanReferences [ ] ctorReferences = referencesResolver . readAllReferencesFromAnnotation ( ctor ) ; if ( ctorReferences == null ) { continue ; } if ( foundedCtor != null ) { throw new PetiteException ( "Two or more constructors are annotated as injection points in the bean: " + type . getName ( ) ) ; } foundedCtor = ctor ; references = ctorReferences ; } if ( foundedCtor == null ) { // there is no annotated constructor if ( allCtors . length == 1 ) { foundedCtor = allCtors [ 0 ] . getConstructor ( ) ; } else { foundedCtor = defaultCtor ; } if ( foundedCtor == null ) { // no matching ctor found // still this is not an error if bean is already instantiated. return CtorInjectionPoint . EMPTY ; } references = referencesResolver . readAllReferencesFromAnnotation ( foundedCtor ) ; if ( references == null ) { references = new BeanReferences [ 0 ] ; } } return new CtorInjectionPoint ( foundedCtor , references ) ; }


Input: Creates advice s class reader . [CODESPLIT] private ClassReader createAdviceClassReader ( final Class < ? extends ProxyAdvice > advice ) { InputStream inputStream = null ; try { inputStream = ClassLoaderUtil . getClassAsStream ( advice ) ; return new ClassReader ( inputStream ) ; } catch ( IOException ioex ) { throw new ProxettaException ( ioex ) ; } finally { StreamUtil . close ( inputStream ) ; } }


Input: Returns class reader for advice . [CODESPLIT] private ClassReader getCachedAdviceClassReader ( final Class < ? extends ProxyAdvice > advice ) { if ( adviceClassReaderCache == null ) { adviceClassReaderCache = TypeCache . createDefault ( ) ; } ClassReader adviceReader = adviceClassReaderCache . get ( advice ) ; if ( adviceReader == null ) { adviceReader = createAdviceClassReader ( advice ) ; adviceClassReaderCache . put ( advice , adviceReader ) ; } return adviceReader ; }


Input:
Parse advice class to gather some advice data . Should be called before any advice use . Must be called only * once * per advice . [CODESPLIT] private void readAdviceData ( ) { if ( ready ) { return ; } adviceClassReader . accept ( new EmptyClassVisitor ( ) { /**
			 * Stores advice reference.
			 */ @ Override public void visit ( final int version , final int access , final String name , final String signature , final String superName , final String [ ] interfaces ) { adviceReference = name ; super . visit ( version , access , name , signature , superName , interfaces ) ; } /**
			 * Prevents advice to have inner classes.
			 */ @ Override public void visitInnerClass ( final String name , final String outerName , final String innerName , final int access ) { if ( outerName . equals ( adviceReference ) ) { throw new ProxettaException ( "Proxetta doesn't allow inner classes in/for advice: " + advice . getName ( ) ) ; } super . visitInnerClass ( name , outerName , innerName , access ) ; } /**
			 * Clones advices fields to destination.
			 */ @ Override public FieldVisitor visitField ( final int access , final String name , final String desc , final String signature , final Object value ) { wd . dest . visitField ( access , adviceFieldName ( name , aspectIndex ) , desc , signature , value ) ; // [A5] return super . visitField ( access , name , desc , signature , value ) ; } /**
			 * Copies advices methods to destination.
			 */ @ Override public MethodVisitor visitMethod ( int access , String name , final String desc , final String signature , final String [ ] exceptions ) { if ( name . equals ( CLINIT ) ) { // [A6] if ( ! desc . equals ( DESC_VOID ) ) { throw new ProxettaException ( "Invalid static initialization block description for advice: " + advice . getName ( ) ) ; } name = ProxettaNames . clinitMethodName + ProxettaNames . methodDivider + aspectIndex ; access |= AsmUtil . ACC_PRIVATE | AsmUtil . ACC_FINAL ; wd . addAdviceClinitMethod ( name ) ; return new MethodAdapter ( wd . dest . visitMethod ( access , name , desc , signature , exceptions ) ) { @ Override public void visitLocalVariable ( final String name , final String desc , final String signature , final Label start , final Label end , final int index ) { } @ Override public void visitLineNumber ( final int line , final Label start ) { } @ Override public void visitMethodInsn ( final int opcode , String owner , String name , final String desc , final boolean isInterface ) { if ( opcode == INVOKESTATIC ) { if ( owner . equals ( adviceReference ) ) { owner = wd . thisReference ; name = adviceMethodName ( name , aspectIndex ) ; } } super . visitMethodInsn ( opcode , owner , name , desc , isInterface ) ; } @ Override public void visitFieldInsn ( final int opcode , String owner , String name , final String desc ) { // [F6] if ( owner . equals ( adviceReference ) ) { owner = wd . thisReference ; // [F5] name = adviceFieldName ( name , aspectIndex ) ; } super . visitFieldInsn ( opcode , owner , name , desc ) ; } } ; } else if ( name . equals ( INIT ) ) { // [A7] if ( ! desc . equals ( DESC_VOID ) ) { throw new ProxettaException ( "Advices can have only default constructors. Invalid advice: " + advice . getName ( ) ) ; } name = ProxettaNames . initMethodName + ProxettaNames . methodDivider + aspectIndex ; access = ProxettaAsmUtil . makePrivateFinalAccess ( access ) ; wd . addAdviceInitMethod ( name ) ; return new MethodAdapter ( wd . dest . visitMethod ( access , name , desc , signature , exceptions ) ) { @ Override public void visitLocalVariable ( final String name , final String desc , final String signature , final Label start , final Label end , final int index ) { } @ Override public void visitLineNumber ( final int line , final Label start ) { } int state ; // used to detect and to ignore the first super call() @ Override public void visitVarInsn ( final int opcode , final int var ) { // [F7] if ( ( state == 0 ) && ( opcode == ALOAD ) && ( var == 0 ) ) { state ++ ; return ; } super . visitVarInsn ( opcode , var ) ; } @ Override public void visitMethodInsn ( final int opcode , String owner , String name , final String desc , final boolean isInterface ) { if ( ( state == 1 ) && ( opcode == INVOKESPECIAL ) ) { state ++ ; return ; } if ( ( opcode == INVOKEVIRTUAL ) || ( opcode == INVOKEINTERFACE ) ) { if ( owner . equals ( adviceReference ) ) { owner = wd . thisReference ; name = adviceMethodName ( name , aspectIndex ) ; } } else if ( opcode == INVOKESTATIC ) { if ( owner . equals ( adviceReference ) ) { owner = wd . thisReference ; name = adviceMethodName ( name , aspectIndex ) ; } } super . visitMethodInsn ( opcode , owner , name , desc , isInterface ) ; } @ Override public void visitFieldInsn ( final int opcode , String owner , String name , final String desc ) { // [F7] if ( owner . equals ( adviceReference ) ) { owner = wd . thisReference ; // [F5] name = adviceFieldName ( name , aspectIndex ) ; } super . visitFieldInsn ( opcode , owner , name , desc ) ; } } ; } else // other methods if ( ! name . equals ( ProxettaNames . executeMethodName ) ) { name = adviceMethodName ( name , aspectIndex ) ; return new MethodAdapter ( wd . dest . visitMethod ( access , name , desc , signature , exceptions ) ) { @ Override public void visitLocalVariable ( final String name , final String desc , final String signature , final Label start , final Label end , final int index ) { } @ Override public void visitLineNumber ( final int line , final Label start ) { } @ Override public void visitMethodInsn ( final int opcode , String owner , String name , final String desc , final boolean isInterface ) { if ( ( opcode == INVOKEVIRTUAL ) || ( opcode == INVOKEINTERFACE ) ) { if ( owner . equals ( adviceReference ) ) { owner = wd . thisReference ; name = adviceMethodName ( name , aspectIndex ) ; } } else if ( opcode == INVOKESTATIC || opcode == INVOKESPECIAL ) { if ( owner . equals ( adviceReference ) ) { owner = wd . thisReference ; name = adviceMethodName ( name , aspectIndex ) ; } } super . visitMethodInsn ( opcode , owner , name , desc , isInterface ) ; } @ Override public void visitFieldInsn ( final int opcode , String owner , String name , final String desc ) { // replace field references if ( owner . equals ( adviceReference ) ) { owner = wd . thisReference ; name = adviceFieldName ( name , aspectIndex ) ; } super . visitFieldInsn ( opcode , owner , name , desc ) ; } } ; } // Parse EXECUTE method, just to gather some info, real parsing will come later //return new MethodAdapter(new EmptyMethodVisitor()) {		// toask may we replace this with the following code? return new EmptyMethodVisitor ( ) { @ Override public void visitVarInsn ( final int opcode , final int var ) { if ( isStoreOpcode ( opcode ) ) { if ( var > maxLocalVarOffset ) { maxLocalVarOffset = var ; // find max local var offset } } super . visitVarInsn ( opcode , var ) ; } } ; //					return super.visitMethod(access, name, desc, signature, exceptions); } } , 0 ) ; maxLocalVarOffset += 2 ; // increment offset by 2 because var on last index may be a dword value ready = true ; }


Input: Symmetrically encrypts the string . [CODESPLIT] public String encrypt ( final String str ) { try { byte [ ] utf8 = StringUtil . getBytes ( str ) ; // encode the string into bytes using utf-8 byte [ ] enc = ecipher . doFinal ( utf8 ) ; // encrypt return Base64 . encodeToString ( enc ) ; // encode bytes to base64 to get a string } catch ( Throwable ignore ) { return null ; } }


Input: Symmetrically decrypts the string . [CODESPLIT] public String decrypt ( String str ) { try { str = StringUtil . replaceChar ( str , ' ' , ' ' ) ; // replace spaces with chars. byte [ ] dec = Base64 . decode ( str ) ; // decode base64 to get bytes byte [ ] utf8 = dcipher . doFinal ( dec ) ; // decrypt return new String ( utf8 , UTF_8 ) ; // decode using utf-8 } catch ( Throwable ignore ) { return null ; } }


Input: Sets { [CODESPLIT] public static void setLoggerProvider ( final LoggerProvider loggerProvider ) { LoggerFactory . loggerProvider = loggerProvider :: createLogger ; if ( loggers != null ) { loggers . clear ( ) ; } }


Input: Returns logger for given name . Repeated calls to this method with the same argument should return the very same instance of the logger . [CODESPLIT] public static Logger getLogger ( final String name ) { if ( loggers == null ) { return loggerProvider . apply ( name ) ; } return loggers . computeIfAbsent ( name , loggerProvider ) ; }


Input: Sets the cookie name and checks for validity . [CODESPLIT] private void setName ( final String name ) { if ( name . contains ( ";" ) || name . contains ( "," ) || name . startsWith ( "$" ) ) { throw new IllegalArgumentException ( "Invalid cookie name:" + name ) ; } for ( int n = 0 ; n < name . length ( ) ; n ++ ) { char c = name . charAt ( n ) ; if ( c <= 0x20 || c >= 0x7f ) { throw new IllegalArgumentException ( "Invalid cookie name:" + name ) ; } } this . name = name ; }


Input: Invokes action registered to provided action path Provides action chaining by invoking the next action request . Returns <code > null< / code > if action path is consumed and has been invoked by this controller ; otherwise the action path string is returned ( it might be different than original one provided in arguments ) . On first invoke initializes the action runtime before further proceeding . [CODESPLIT] public String invoke ( String actionPath , final HttpServletRequest servletRequest , final HttpServletResponse servletResponse ) throws Exception { final String originalActionPath = actionPath ; boolean characterEncodingSet = false ; while ( actionPath != null ) { // build action path final String httpMethod = servletRequest . getMethod ( ) . toUpperCase ( ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Action path: " + httpMethod + " " + actionPath ) ; } actionPath = actionPathRewriter . rewrite ( servletRequest , actionPath , httpMethod ) ; String [ ] actionPathChunks = MadvocUtil . splitPathToChunks ( actionPath ) ; // resolve action runtime ActionRuntime actionRuntime = actionsManager . lookup ( httpMethod , actionPathChunks ) ; if ( actionRuntime == null ) { // special case! if ( actionPath . endsWith ( welcomeFile ) ) { actionPath = actionPath . substring ( 0 , actionPath . length ( ) - ( welcomeFile . length ( ) - 1 ) ) ; actionPathChunks = MadvocUtil . splitPathToChunks ( actionPath ) ; actionRuntime = actionsManager . lookup ( httpMethod , actionPathChunks ) ; } if ( actionRuntime == null ) { return originalActionPath ; } } if ( log . isDebugEnabled ( ) ) { log . debug ( "Invoke action for '" + actionPath + "' using " + actionRuntime . createActionString ( ) ) ; } // set character encoding if ( ! characterEncodingSet && applyCharacterEncoding ) { final String encoding = madvocEncoding . getEncoding ( ) ; if ( encoding != null ) { servletRequest . setCharacterEncoding ( encoding ) ; servletResponse . setCharacterEncoding ( encoding ) ; } characterEncodingSet = true ; } // create action object final Object action ; if ( actionRuntime . isActionHandlerDefined ( ) ) { action = actionRuntime . getActionHandler ( ) ; } else { action = createAction ( actionRuntime . getActionClass ( ) ) ; } final ActionRequest actionRequest = createActionRequest ( actionPath , actionPathChunks , actionRuntime , action , servletRequest , servletResponse ) ; // invoke and render if ( actionRuntime . isAsync ( ) ) { asyncActionExecutor . invoke ( actionRequest ) ; } else { actionRequest . invoke ( ) ; } actionPath = actionRequest . getNextActionPath ( ) ; } return null ; }


Input: Invokes a result after the action invocation . <p > Results may be objects that specify which action result will be used to render the result . <p > Result value may consist of two parts : type and value . Result type is optional and if exists it is separated by semi - colon from the value . If type is not specified then the default result type if still not defined . Result type defines which { @link ActionResult } should be used for rendering the value . <p > Result value is first checked against aliased values . Then it is resolved and then passed to the founded { @link ActionResult } . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public void render ( final ActionRequest actionRequest , final Object resultObject ) throws Exception { final ActionResult actionResult = resultsManager . lookup ( actionRequest , resultObject ) ; if ( actionResult == null ) { throw new MadvocException ( "Action result not found" ) ; } if ( preventCaching ) { ServletUtil . preventCaching ( actionRequest . getHttpServletResponse ( ) ) ; } log . debug ( ( ) -> "Result type: " + actionResult . getClass ( ) . getSimpleName ( ) ) ; actionResult . render ( actionRequest , actionRequest . getActionResult ( ) ) ; }


Input: Creates new action object from { [CODESPLIT] protected Object createAction ( final Class actionClass ) { try { return ClassUtil . newInstance ( actionClass ) ; } catch ( Exception ex ) { throw new MadvocException ( "Invalid Madvoc action" , ex ) ; } }


Input: Creates new action request . [CODESPLIT] protected ActionRequest createActionRequest ( final String actionPath , final String [ ] actionPathChunks , final ActionRuntime actionRuntime , final Object action , final HttpServletRequest servletRequest , final HttpServletResponse servletResponse ) { return new ActionRequest ( this , actionPath , actionPathChunks , actionRuntime , action , servletRequest , servletResponse ) ; }


Input: Acquires filter from Petite container . [CODESPLIT] @ Override protected < R extends ActionFilter > R createWrapper ( final Class < R > wrapperClass ) { return petiteContainer . createBean ( wrapperClass ) ; }


Input: Returns <code > true< / code > if bean is destroyable . [CODESPLIT] protected boolean isBeanDestroyable ( final BeanData beanData ) { DestroyMethodPoint [ ] dmp = beanData . definition ( ) . destroyMethodPoints ( ) ; return dmp != null && dmp . length != 0 ; }


Input: Checks if bean data is destroyable ( has destroy methods ) and registers it for later { [CODESPLIT] protected void registerDestroyableBeans ( final BeanData beanData ) { if ( ! isBeanDestroyable ( beanData ) ) { return ; } if ( destroyableBeans == null ) { destroyableBeans = new ArrayList <> ( ) ; } destroyableBeans . add ( beanData ) ; }


Input: Removes destroyable bean from the list and calls it destroy methods . If bean is not destroyable does nothing . Bean gets destroyed only once . [CODESPLIT] protected void destroyBean ( final BeanData beanData ) { if ( destroyableBeans == null ) { return ; } if ( ! isBeanDestroyable ( beanData ) ) { return ; } if ( destroyableBeans . remove ( beanData ) ) { beanData . callDestroyMethods ( ) ; } }


Input: Shutdowns the scope and calls all collected destroyable beans . [CODESPLIT] @ Override public void shutdown ( ) { if ( destroyableBeans == null ) { return ; } for ( final BeanData destroyableBean : destroyableBeans ) { destroyableBean . callDestroyMethods ( ) ; } destroyableBeans . clear ( ) ; }


Input: Creates { @link MailSession } { @link Properties } . [CODESPLIT] protected Properties createSessionProperties ( ) { final Properties props = new Properties ( ) ; props . putAll ( customProperties ) ; if ( debugMode ) { props . put ( MAIL_DEBUG , "true" ) ; } if ( ! strictAddress ) { props . put ( MAIL_MIME_ADDRESS_STRICT , "false" ) ; } return props ; }


Input: Receives the emails as specified by the builder . [CODESPLIT] public ReceivedEmail [ ] get ( ) { if ( fromFolder != null ) { session . useFolder ( fromFolder ) ; } return session . receiveMessages ( filter , flagsToSet , flagsToUnset , envelopeOnly , messages -> { if ( targetFolder != null ) { try { session . folder . copyMessages ( messages , session . getFolder ( targetFolder ) ) ; } catch ( MessagingException e ) { throw new MailException ( "Copying messages failed" ) ; } } } ) ; }


Input: Duplicate the underlying { @link ByteBuffer } s and wrap them for thread local access . [CODESPLIT] public UnsafeBuffer [ ] duplicateTermBuffers ( ) { final UnsafeBuffer [ ] buffers = new UnsafeBuffer [ PARTITION_COUNT ] ; for ( int i = 0 ; i < PARTITION_COUNT ; i ++ ) { buffers [ i ] = new UnsafeBuffer ( termBuffers [ i ] . duplicate ( ) . order ( ByteOrder . LITTLE_ENDIAN ) ) ; } return buffers ; }


Input: Launch the clustered service container and await a shutdown signal . [CODESPLIT] public static void main ( final String [ ] args ) { loadPropertiesFiles ( args ) ; try ( ClusteredServiceContainer container = launch ( ) ) { container . context ( ) . shutdownSignalBarrier ( ) . await ( ) ; System . out . println ( "Shutdown ClusteredServiceContainer..." ) ; } }


Input: Allocate a per { @link io . aeron . driver . PublicationImage } indicator . [CODESPLIT] public static AtomicCounter allocate ( final MutableDirectBuffer tempBuffer , final String name , final CountersManager countersManager , final long registrationId , final int sessionId , final int streamId , final String channel ) { final int counterId = StreamCounter . allocateCounterId ( tempBuffer , name , PER_IMAGE_TYPE_ID , countersManager , registrationId , sessionId , streamId , channel ) ; return new AtomicCounter ( countersManager . valuesBuffer ( ) , counterId , countersManager ) ; }


Input: Run loop for the rate reporter [CODESPLIT] public void run ( ) { do { LockSupport . parkNanos ( parkNs ) ; final long currentTotalMessages = totalMessages ; final long currentTotalBytes = totalBytes ; final long currentTimestamp = System . nanoTime ( ) ; final long timeSpanNs = currentTimestamp - lastTimestamp ; final double messagesPerSec = ( ( currentTotalMessages - lastTotalMessages ) * ( double ) reportIntervalNs ) / ( double ) timeSpanNs ; final double bytesPerSec = ( ( currentTotalBytes - lastTotalBytes ) * ( double ) reportIntervalNs ) / ( double ) timeSpanNs ; reportingFunc . onReport ( messagesPerSec , bytesPerSec , currentTotalMessages , currentTotalBytes ) ; lastTotalBytes = currentTotalBytes ; lastTotalMessages = currentTotalMessages ; lastTimestamp = currentTimestamp ; } while ( ! halt ) ; }


Input: Return a reusable parametrised { @link FragmentHandler } that calls into a { @link RateReporter } . [CODESPLIT] public static FragmentHandler rateReporterHandler ( final RateReporter reporter ) { return ( buffer , offset , length , header ) -> reporter . onMessage ( 1 , length ) ; }


Input: Generic error handler that just prints message to stdout . [CODESPLIT] @ SuppressWarnings ( "unused" ) public static void printError ( final String channel , final int streamId , final int sessionId , final String message , final HeaderFlyweight cause ) { System . out . println ( message ) ; }


Input: Print the rates to stdout [CODESPLIT] public static void printRate ( final double messagesPerSec , final double bytesPerSec , final long totalMessages , final long totalBytes ) { System . out . println ( String . format ( "%.02g msgs/sec, %.02g payload bytes/sec, totals %d messages %d MB" , messagesPerSec , bytesPerSec , totalMessages , totalBytes / ( 1024 * 1024 ) ) ) ; }


Input: Map an existing file as a read only buffer . [CODESPLIT] public static MappedByteBuffer mapExistingFileReadOnly ( final File location ) { if ( ! location . exists ( ) ) { final String msg = "file not found: " + location . getAbsolutePath ( ) ; throw new IllegalStateException ( msg ) ; } MappedByteBuffer mappedByteBuffer = null ; try ( RandomAccessFile file = new RandomAccessFile ( location , "r" ) ; FileChannel channel = file . getChannel ( ) ) { mappedByteBuffer = channel . map ( READ_ONLY , 0 , channel . size ( ) ) ; } catch ( final IOException ex ) { LangUtil . rethrowUnchecked ( ex ) ; } return mappedByteBuffer ; }


Input: Close the merge and stop any active replay . Will remove the replay destination from the subscription . Will NOT remove the live destination if it has been added . [CODESPLIT] public void close ( ) { final State state = this . state ; if ( State . CLOSED != state ) { if ( isReplayActive ) { isReplayActive = false ; archive . stopReplay ( replaySessionId ) ; } if ( State . MERGED != state ) { subscription . removeDestination ( replayDestination ) ; } state ( State . CLOSED ) ; } }


Input: Process the operation of the merge . Do not call the processing of fragments on the subscription . [CODESPLIT] public int doWork ( ) { int workCount = 0 ; switch ( state ) { case AWAIT_INITIAL_RECORDING_POSITION : workCount += awaitInitialRecordingPosition ( ) ; break ; case AWAIT_REPLAY : workCount += awaitReplay ( ) ; break ; case AWAIT_CATCH_UP : workCount += awaitCatchUp ( ) ; break ; case AWAIT_CURRENT_RECORDING_POSITION : workCount += awaitUpdatedRecordingPosition ( ) ; break ; case AWAIT_STOP_REPLAY : workCount += awaitStopReplay ( ) ; break ; } return workCount ; }


Input: Poll the { @link Image } used for the merging replay and live stream . The { @link ReplayMerge#doWork () } method will be called before the poll so that processing of the merge can be done . [CODESPLIT] public int poll ( final FragmentHandler fragmentHandler , final int fragmentLimit ) { doWork ( ) ; return null == image ? 0 : image . poll ( fragmentHandler , fragmentLimit ) ; }


Input: Get the current position to which the publication has advanced for this stream . [CODESPLIT] public long position ( ) { if ( isClosed ) { return CLOSED ; } final long rawTail = rawTailVolatile ( logMetaDataBuffer ) ; final int termOffset = termOffset ( rawTail , termBufferLength ) ; return computePosition ( termId ( rawTail ) , termOffset , positionBitsToShift , initialTermId ) ; }


Input: Non - blocking publish of a partial buffer containing a message . [CODESPLIT] public final long offer ( final DirectBuffer buffer , final int offset , final int length ) { return offer ( buffer , offset , length , null ) ; }


Input: Non - blocking publish of a message composed of two parts e . g . a header and encapsulated payload . [CODESPLIT] public final long offer ( final DirectBuffer bufferOne , final int offsetOne , final int lengthOne , final DirectBuffer bufferTwo , final int offsetTwo , final int lengthTwo ) { return offer ( bufferOne , offsetOne , lengthOne , bufferTwo , offsetTwo , lengthTwo , null ) ; }


Input: Non - blocking publish of a partial buffer containing a message . [CODESPLIT] public long offer ( final DirectBuffer buffer , final int offset , final int length , final ReservedValueSupplier reservedValueSupplier ) { long newPosition = CLOSED ; if ( ! isClosed ) { final long limit = positionLimit . getVolatile ( ) ; final ExclusiveTermAppender termAppender = termAppenders [ activePartitionIndex ] ; final long position = termBeginPosition + termOffset ; if ( position < limit ) { final int result ; if ( length <= maxPayloadLength ) { checkPositiveLength ( length ) ; result = termAppender . appendUnfragmentedMessage ( termId , termOffset , headerWriter , buffer , offset , length , reservedValueSupplier ) ; } else { checkMaxMessageLength ( length ) ; result = termAppender . appendFragmentedMessage ( termId , termOffset , headerWriter , buffer , offset , length , maxPayloadLength , reservedValueSupplier ) ; } newPosition = newPosition ( result ) ; } else { newPosition = backPressureStatus ( position , length ) ; } } return newPosition ; }


Input: Non - blocking publish of a message composed of two parts e . g . a header and encapsulated payload . [CODESPLIT] public long offer ( final DirectBuffer bufferOne , final int offsetOne , final int lengthOne , final DirectBuffer bufferTwo , final int offsetTwo , final int lengthTwo , final ReservedValueSupplier reservedValueSupplier ) { long newPosition = CLOSED ; if ( ! isClosed ) { final long limit = positionLimit . getVolatile ( ) ; final ExclusiveTermAppender termAppender = termAppenders [ activePartitionIndex ] ; final long position = termBeginPosition + termOffset ; final int length = validateAndComputeLength ( lengthOne , lengthTwo ) ; if ( position < limit ) { final int result ; if ( length <= maxPayloadLength ) { checkPositiveLength ( length ) ; result = termAppender . appendUnfragmentedMessage ( termId , termOffset , headerWriter , bufferOne , offsetOne , lengthOne , bufferTwo , offsetTwo , lengthTwo , reservedValueSupplier ) ; } else { checkMaxMessageLength ( length ) ; result = termAppender . appendFragmentedMessage ( termId , termOffset , headerWriter , bufferOne , offsetOne , lengthOne , bufferTwo , offsetTwo , lengthTwo , maxPayloadLength , reservedValueSupplier ) ; } newPosition = newPosition ( result ) ; } else { newPosition = backPressureStatus ( position , length ) ; } } return newPosition ; }


Input: Non - blocking publish by gathering buffer vectors into a message . [CODESPLIT] public long offer ( final DirectBufferVector [ ] vectors , final ReservedValueSupplier reservedValueSupplier ) { final int length = DirectBufferVector . validateAndComputeLength ( vectors ) ; long newPosition = CLOSED ; if ( ! isClosed ) { final long limit = positionLimit . getVolatile ( ) ; final ExclusiveTermAppender termAppender = termAppenders [ activePartitionIndex ] ; final long position = termBeginPosition + termOffset ; if ( position < limit ) { final int result ; if ( length <= maxPayloadLength ) { result = termAppender . appendUnfragmentedMessage ( termId , termOffset , headerWriter , vectors , length , reservedValueSupplier ) ; } else { checkMaxMessageLength ( length ) ; result = termAppender . appendFragmentedMessage ( termId , termOffset , headerWriter , vectors , length , maxPayloadLength , reservedValueSupplier ) ; } newPosition = newPosition ( result ) ; } else { newPosition = backPressureStatus ( position , length ) ; } } return newPosition ; }


Input: Try to claim a range in the publication log into which a message can be written with zero copy semantics . Once the message has been written then { @link BufferClaim#commit () } should be called thus making it available . <p > <b > Note : < / b > This method can only be used for message lengths less than MTU length minus header . If the claim is held after the publication is closed or the client dies then it will be unblocked to reach end - of - stream ( EOS ) . <pre > { @code final BufferClaim bufferClaim = new BufferClaim () ; [CODESPLIT] public long tryClaim ( final int length , final BufferClaim bufferClaim ) { checkPayloadLength ( length ) ; long newPosition = CLOSED ; if ( ! isClosed ) { final long limit = positionLimit . getVolatile ( ) ; final ExclusiveTermAppender termAppender = termAppenders [ activePartitionIndex ] ; final long position = termBeginPosition + termOffset ; if ( position < limit ) { final int result = termAppender . claim ( termId , termOffset , headerWriter , length , bufferClaim ) ; newPosition = newPosition ( result ) ; } else { newPosition = backPressureStatus ( position , length ) ; } } return newPosition ; }


Input: Append a padding record log of a given length to make up the log to a position . [CODESPLIT] public long appendPadding ( final int length ) { checkMaxMessageLength ( length ) ; long newPosition = CLOSED ; if ( ! isClosed ) { final long limit = positionLimit . getVolatile ( ) ; final ExclusiveTermAppender termAppender = termAppenders [ activePartitionIndex ] ; final long position = termBeginPosition + termOffset ; if ( position < limit ) { checkPositiveLength ( length ) ; final int result = termAppender . appendPadding ( termId , termOffset , headerWriter , length ) ; newPosition = newPosition ( result ) ; } else { newPosition = backPressureStatus ( position , length ) ; } } return newPosition ; }


Input: Set channel field in ASCII [CODESPLIT] public DestinationMessageFlyweight channel ( final String channel ) { lengthOfChannel = buffer . putStringAscii ( offset + CHANNEL_OFFSET , channel ) ; return this ; }


Input: Notify the archive that this control session is closed so it can promptly release resources then close the local resources associated with the client . [CODESPLIT] public void close ( ) { lock . lock ( ) ; try { if ( ! isClosed ) { isClosed = true ; archiveProxy . closeSession ( controlSessionId ) ; if ( ! context . ownsAeronClient ( ) ) { CloseHelper . close ( controlResponsePoller . subscription ( ) ) ; CloseHelper . close ( archiveProxy . publication ( ) ) ; } context . close ( ) ; } } finally { lock . unlock ( ) ; } }


Input: Connect to an Aeron archive by providing a { @link Context } . This will create a control session . <p > Before connecting { @link Context#conclude () } will be called . If an exception occurs then { @link Context#close () } will be called . [CODESPLIT] public static AeronArchive connect ( final Context ctx ) { Subscription subscription = null ; Publication publication = null ; AsyncConnect asyncConnect = null ; try { ctx . conclude ( ) ; final Aeron aeron = ctx . aeron ( ) ; final long messageTimeoutNs = ctx . messageTimeoutNs ( ) ; final long deadlineNs = aeron . context ( ) . nanoClock ( ) . nanoTime ( ) + messageTimeoutNs ; subscription = aeron . addSubscription ( ctx . controlResponseChannel ( ) , ctx . controlResponseStreamId ( ) ) ; final ControlResponsePoller controlResponsePoller = new ControlResponsePoller ( subscription ) ; publication = aeron . addExclusivePublication ( ctx . controlRequestChannel ( ) , ctx . controlRequestStreamId ( ) ) ; final ArchiveProxy archiveProxy = new ArchiveProxy ( publication , ctx . idleStrategy ( ) , aeron . context ( ) . nanoClock ( ) , messageTimeoutNs , DEFAULT_RETRY_ATTEMPTS ) ; asyncConnect = new AsyncConnect ( ctx , controlResponsePoller , archiveProxy , deadlineNs ) ; final IdleStrategy idleStrategy = ctx . idleStrategy ( ) ; final AgentInvoker aeronClientInvoker = aeron . conductorAgentInvoker ( ) ; AeronArchive aeronArchive ; while ( null == ( aeronArchive = asyncConnect . poll ( ) ) ) { if ( null != aeronClientInvoker ) { aeronClientInvoker . invoke ( ) ; } idleStrategy . idle ( ) ; } return aeronArchive ; } catch ( final Exception ex ) { if ( ! ctx . ownsAeronClient ( ) ) { CloseHelper . quietClose ( subscription ) ; CloseHelper . quietClose ( publication ) ; } CloseHelper . quietClose ( asyncConnect ) ; ctx . close ( ) ; throw ex ; } }


Input: Begin an attempt at creating a connection which can be completed by calling { @link AsyncConnect#poll () } until it returns the client before complete it will return null . [CODESPLIT] public static AsyncConnect asyncConnect ( final Context ctx ) { Subscription subscription = null ; Publication publication = null ; try { ctx . conclude ( ) ; final Aeron aeron = ctx . aeron ( ) ; final long messageTimeoutNs = ctx . messageTimeoutNs ( ) ; final long deadlineNs = aeron . context ( ) . nanoClock ( ) . nanoTime ( ) + messageTimeoutNs ; subscription = aeron . addSubscription ( ctx . controlResponseChannel ( ) , ctx . controlResponseStreamId ( ) ) ; final ControlResponsePoller controlResponsePoller = new ControlResponsePoller ( subscription ) ; publication = aeron . addExclusivePublication ( ctx . controlRequestChannel ( ) , ctx . controlRequestStreamId ( ) ) ; final ArchiveProxy archiveProxy = new ArchiveProxy ( publication , ctx . idleStrategy ( ) , aeron . context ( ) . nanoClock ( ) , messageTimeoutNs , DEFAULT_RETRY_ATTEMPTS ) ; return new AsyncConnect ( ctx , controlResponsePoller , archiveProxy , deadlineNs ) ; } catch ( final Exception ex ) { if ( ! ctx . ownsAeronClient ( ) ) { CloseHelper . quietClose ( subscription ) ; CloseHelper . quietClose ( publication ) ; } ctx . close ( ) ; throw ex ; } }


Input: Poll the response stream once for an error . If another message is present then it will be skipped over so only call when not expecting another response . [CODESPLIT] public String pollForErrorResponse ( ) { lock . lock ( ) ; try { ensureOpen ( ) ; if ( controlResponsePoller . poll ( ) != 0 && controlResponsePoller . isPollComplete ( ) ) { if ( controlResponsePoller . controlSessionId ( ) == controlSessionId && controlResponsePoller . templateId ( ) == ControlResponseDecoder . TEMPLATE_ID && controlResponsePoller . code ( ) == ControlResponseCode . ERROR ) { return controlResponsePoller . errorMessage ( ) ; } } return null ; } finally { lock . unlock ( ) ; } }


Input: Check if an error has been returned for the control session and throw a { @link ArchiveException } if { @link Context#errorHandler ( ErrorHandler ) } is not set . <p > To check for an error response without raising an exception then try { @link #pollForErrorResponse () } . [CODESPLIT] public void checkForErrorResponse ( ) { lock . lock ( ) ; try { ensureOpen ( ) ; if ( controlResponsePoller . poll ( ) != 0 && controlResponsePoller . isPollComplete ( ) ) { if ( controlResponsePoller . controlSessionId ( ) == controlSessionId && controlResponsePoller . templateId ( ) == ControlResponseDecoder . TEMPLATE_ID && controlResponsePoller . code ( ) == ControlResponseCode . ERROR ) { final ArchiveException ex = new ArchiveException ( controlResponsePoller . errorMessage ( ) , ( int ) controlResponsePoller . relevantId ( ) ) ; if ( null != context . errorHandler ( ) ) { context . errorHandler ( ) . onError ( ex ) ; } else { throw ex ; } } } } finally { lock . unlock ( ) ; } }


Input: Add a { @link Publication } and set it up to be recorded . If this is not the first i . e . { @link Publication#isOriginal () } is true then an { @link ArchiveException } will be thrown and the recording not initiated . <p > This is a sessionId specific recording . [CODESPLIT] public Publication addRecordedPublication ( final String channel , final int streamId ) { Publication publication = null ; lock . lock ( ) ; try { ensureOpen ( ) ; publication = aeron . addPublication ( channel , streamId ) ; if ( ! publication . isOriginal ( ) ) { throw new ArchiveException ( "publication already added for channel=" + channel + " streamId=" + streamId ) ; } startRecording ( ChannelUri . addSessionId ( channel , publication . sessionId ( ) ) , streamId , SourceLocation . LOCAL ) ; } catch ( final RuntimeException ex ) { CloseHelper . quietClose ( publication ) ; throw ex ; } finally { lock . unlock ( ) ; } return publication ; }


Input: Add an { @link ExclusivePublication } and set it up to be recorded . <p > This is a sessionId specific recording . [CODESPLIT] public ExclusivePublication addRecordedExclusivePublication ( final String channel , final int streamId ) { ExclusivePublication publication = null ; lock . lock ( ) ; try { ensureOpen ( ) ; publication = aeron . addExclusivePublication ( channel , streamId ) ; startRecording ( ChannelUri . addSessionId ( channel , publication . sessionId ( ) ) , streamId , SourceLocation . LOCAL ) ; } catch ( final RuntimeException ex ) { CloseHelper . quietClose ( publication ) ; throw ex ; } finally { lock . unlock ( ) ; } return publication ; }


Input: Start recording a channel and stream pairing . <p > Channels that include sessionId parameters are considered different than channels without sessionIds . If a publication matches both a sessionId specific channel recording and a non - sessionId specific recording it will be recorded twice . [CODESPLIT] public long startRecording ( final String channel , final int streamId , final SourceLocation sourceLocation ) { lock . lock ( ) ; try { ensureOpen ( ) ; final long correlationId = aeron . nextCorrelationId ( ) ; if ( ! archiveProxy . startRecording ( channel , streamId , sourceLocation , correlationId , controlSessionId ) ) { throw new ArchiveException ( "failed to send start recording request" ) ; } return pollForResponse ( correlationId ) ; } finally { lock . unlock ( ) ; } }


Input: Stop recording for a channel and stream pairing . <p > Channels that include sessionId parameters are considered different than channels without sessionIds . Stopping a recording on a channel without a sessionId parameter will not stop the recording of any sessionId specific recordings that use the same channel and streamId . [CODESPLIT] public void stopRecording ( final String channel , final int streamId ) { lock . lock ( ) ; try { ensureOpen ( ) ; final long correlationId = aeron . nextCorrelationId ( ) ; if ( ! archiveProxy . stopRecording ( channel , streamId , correlationId , controlSessionId ) ) { throw new ArchiveException ( "failed to send stop recording request" ) ; } pollForResponse ( correlationId ) ; } finally { lock . unlock ( ) ; } }


Input: Stop recording a sessionId specific recording that pertains to the given { @link Publication } . [CODESPLIT] public void stopRecording ( final Publication publication ) { final String recordingChannel = ChannelUri . addSessionId ( publication . channel ( ) , publication . sessionId ( ) ) ; stopRecording ( recordingChannel , publication . streamId ( ) ) ; }


Input: Stop recording for a subscriptionId that has been returned from { @link #startRecording ( String int SourceLocation ) } or { @link #extendRecording ( long String int SourceLocation ) } . [CODESPLIT] public void stopRecording ( final long subscriptionId ) { lock . lock ( ) ; try { ensureOpen ( ) ; final long correlationId = aeron . nextCorrelationId ( ) ; if ( ! archiveProxy . stopRecording ( subscriptionId , correlationId , controlSessionId ) ) { throw new ArchiveException ( "failed to send stop recording request" ) ; } pollForResponse ( correlationId ) ; } finally { lock . unlock ( ) ; } }


Input: Start a replay for a length in bytes of a recording from a position . If the position is { @link #NULL_POSITION } then the stream will be replayed from the start . <p > The lower 32 - bits of the returned value contains the { @link Image#sessionId () } of the received replay . All 64 - bits are required to uniquely identify the replay when calling { @link #stopReplay ( long ) } . The lower 32 - bits can be obtained by casting the { @code long } value to an { @code int } . [CODESPLIT] public long startReplay ( final long recordingId , final long position , final long length , final String replayChannel , final int replayStreamId ) { lock . lock ( ) ; try { ensureOpen ( ) ; final long correlationId = aeron . nextCorrelationId ( ) ; if ( ! archiveProxy . replay ( recordingId , position , length , replayChannel , replayStreamId , correlationId , controlSessionId ) ) { throw new ArchiveException ( "failed to send replay request" ) ; } return pollForResponse ( correlationId ) ; } finally { lock . unlock ( ) ; } }


Input: Stop a replay session . [CODESPLIT] public void stopReplay ( final long replaySessionId ) { lock . lock ( ) ; try { ensureOpen ( ) ; final long correlationId = aeron . nextCorrelationId ( ) ; if ( ! archiveProxy . stopReplay ( replaySessionId , correlationId , controlSessionId ) ) { throw new ArchiveException ( "failed to send stop replay request" ) ; } pollForResponse ( correlationId ) ; } finally { lock . unlock ( ) ; } }


Input: Replay a length in bytes of a recording from a position and for convenience create a { @link Subscription } to receive the replay . If the position is { @link #NULL_POSITION } then the stream will be replayed from the start . [CODESPLIT] public Subscription replay ( final long recordingId , final long position , final long length , final String replayChannel , final int replayStreamId ) { lock . lock ( ) ; try { ensureOpen ( ) ; final ChannelUri replayChannelUri = ChannelUri . parse ( replayChannel ) ; final long correlationId = aeron . nextCorrelationId ( ) ; if ( ! archiveProxy . replay ( recordingId , position , length , replayChannel , replayStreamId , correlationId , controlSessionId ) ) { throw new ArchiveException ( "failed to send replay request" ) ; } final int replaySessionId = ( int ) pollForResponse ( correlationId ) ; replayChannelUri . put ( CommonContext . SESSION_ID_PARAM_NAME , Integer . toString ( replaySessionId ) ) ; return aeron . addSubscription ( replayChannelUri . toString ( ) , replayStreamId ) ; } finally { lock . unlock ( ) ; } }


Input: List all recording descriptors from a recording id with a limit of record count . <p > If the recording id is greater than the largest known id then nothing is returned . [CODESPLIT] public int listRecordings ( final long fromRecordingId , final int recordCount , final RecordingDescriptorConsumer consumer ) { lock . lock ( ) ; try { ensureOpen ( ) ; final long correlationId = aeron . nextCorrelationId ( ) ; if ( ! archiveProxy . listRecordings ( fromRecordingId , recordCount , correlationId , controlSessionId ) ) { throw new ArchiveException ( "failed to send list recordings request" ) ; } return pollForDescriptors ( correlationId , recordCount , consumer ) ; } finally { lock . unlock ( ) ; } }


Input: List recording descriptors from a recording id with a limit of record count for a given channelFragment and stream id . <p > If the recording id is greater than the largest known id then nothing is returned . [CODESPLIT] public int listRecordingsForUri ( final long fromRecordingId , final int recordCount , final String channelFragment , final int streamId , final RecordingDescriptorConsumer consumer ) { lock . lock ( ) ; try { ensureOpen ( ) ; final long correlationId = aeron . nextCorrelationId ( ) ; if ( ! archiveProxy . listRecordingsForUri ( fromRecordingId , recordCount , channelFragment , streamId , correlationId , controlSessionId ) ) { throw new ArchiveException ( "failed to send list recordings request" ) ; } return pollForDescriptors ( correlationId , recordCount , consumer ) ; } finally { lock . unlock ( ) ; } }


Input: List a recording descriptor for a single recording id . <p > If the recording id is greater than the largest known id then nothing is returned . [CODESPLIT] public int listRecording ( final long recordingId , final RecordingDescriptorConsumer consumer ) { lock . lock ( ) ; try { ensureOpen ( ) ; final long correlationId = aeron . nextCorrelationId ( ) ; if ( ! archiveProxy . listRecording ( recordingId , correlationId , controlSessionId ) ) { throw new ArchiveException ( "failed to send list recording request" ) ; } return pollForDescriptors ( correlationId , 1 , consumer ) ; } finally { lock . unlock ( ) ; } }


Input: Get the position recorded for an active recording . If no active recording then return { @link #NULL_POSITION } . [CODESPLIT] public long getRecordingPosition ( final long recordingId ) { lock . lock ( ) ; try { ensureOpen ( ) ; final long correlationId = aeron . nextCorrelationId ( ) ; if ( ! archiveProxy . getRecordingPosition ( recordingId , correlationId , controlSessionId ) ) { throw new ArchiveException ( "failed to send get recording position request" ) ; } return pollForResponse ( correlationId ) ; } finally { lock . unlock ( ) ; } }


Input: Find the last recording that matches the given criteria . [CODESPLIT] public long findLastMatchingRecording ( final long minRecordingId , final String channelFragment , final int streamId , final int sessionId ) { lock . lock ( ) ; try { ensureOpen ( ) ; final long correlationId = aeron . nextCorrelationId ( ) ; if ( ! archiveProxy . findLastMatchingRecording ( minRecordingId , channelFragment , streamId , sessionId , correlationId , controlSessionId ) ) { throw new ArchiveException ( "failed to send find last matching recording request" ) ; } return pollForResponse ( correlationId ) ; } finally { lock . unlock ( ) ; } }


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 void truncateRecording ( final long recordingId , final long position ) { lock . lock ( ) ; try { ensureOpen ( ) ; final long correlationId = aeron . nextCorrelationId ( ) ; if ( ! archiveProxy . truncateRecording ( recordingId , position , correlationId , controlSessionId ) ) { throw new ArchiveException ( "failed to send truncate recording request" ) ; } pollForResponse ( correlationId ) ; } finally { lock . unlock ( ) ; } }


Input: List active recording subscriptions in the archive . These are the result of requesting one of { @link #startRecording ( String int SourceLocation ) } or a { @link #extendRecording ( long String int SourceLocation ) } . The returned subscription id can be used for passing to { @link #stopRecording ( long ) } . [CODESPLIT] public int listRecordingSubscriptions ( final int pseudoIndex , final int subscriptionCount , final String channelFragment , final int streamId , final boolean applyStreamId , final RecordingSubscriptionDescriptorConsumer consumer ) { lock . lock ( ) ; try { ensureOpen ( ) ; final long correlationId = aeron . nextCorrelationId ( ) ; if ( ! archiveProxy . listRecordingSubscriptions ( pseudoIndex , subscriptionCount , channelFragment , streamId , applyStreamId , correlationId , controlSessionId ) ) { throw new ArchiveException ( "failed to send list recording subscriptions request" ) ; } return pollForSubscriptionDescriptors ( correlationId , subscriptionCount , consumer ) ; } finally { lock . unlock ( ) ; } }


Input: Dump the contents of a segment file to a { @link PrintStream } . [CODESPLIT] public static void dumpSegment ( final PrintStream out , final int messageDumpLimit , final UnsafeBuffer buffer ) { final DataHeaderFlyweight dataHeaderFlyweight = new DataHeaderFlyweight ( ) ; final int length = buffer . capacity ( ) ; int offset = 0 ; while ( offset < length ) { dataHeaderFlyweight . wrap ( buffer , offset , length - offset ) ; out . println ( offset + ": " + dataHeaderFlyweight . toString ( ) ) ; final int frameLength = dataHeaderFlyweight . frameLength ( ) ; if ( frameLength < DataHeaderFlyweight . HEADER_LENGTH ) { break ; } final int limit = min ( frameLength - HEADER_LENGTH , messageDumpLimit ) ; out . println ( LogInspector . formatBytes ( buffer , offset + HEADER_LENGTH , limit ) ) ; offset += BitUtil . align ( frameLength , FrameDescriptor . FRAME_ALIGNMENT ) ; } }


Input: Print the information for an available image to stdout . [CODESPLIT] public static void eventAvailableImage ( final Image image ) { final Subscription subscription = image . subscription ( ) ; System . out . format ( "new image on %s streamId %x sessionId %x from %s%n" , subscription . channel ( ) , subscription . streamId ( ) , image . sessionId ( ) , image . sourceIdentity ( ) ) ; }


Input: This handler is called when image is unavailable [CODESPLIT] public static void eventUnavailableImage ( final Image image ) { final Subscription subscription = image . subscription ( ) ; System . out . format ( "inactive image on %s streamId %d sessionId %x%n" , subscription . channel ( ) , subscription . streamId ( ) , image . sessionId ( ) ) ; }


Input: Return a reusable parameterized { @link FragmentHandler } that prints to stdout for the first stream ( STREAM ) [CODESPLIT] public static FragmentHandler reassembledStringMessage1 ( final int streamId ) { return ( buffer , offset , length , header ) -> { final byte [ ] data = new byte [ length ] ; buffer . getBytes ( offset , data ) ; System . out . format ( "message to stream %d from session %x term id %x term offset %d (%d@%d)%n" , streamId , header . sessionId ( ) , header . termId ( ) , header . termOffset ( ) , length , offset ) ; if ( length != 10000 ) { System . out . format ( "Received message was not assembled properly;" + " received length was %d, but was expecting 10000%n" , length ) ; } } ; }


Input: Return the controllable idle strategy { @link StatusIndicator } . [CODESPLIT] public static StatusIndicator controllableIdleStrategy ( final CountersReader countersReader ) { StatusIndicator statusIndicator = null ; final MutableInteger id = new MutableInteger ( - 1 ) ; countersReader . forEach ( ( counterId , label ) -> { if ( counterId == SystemCounterDescriptor . CONTROLLABLE_IDLE_STRATEGY . id ( ) && label . equals ( SystemCounterDescriptor . CONTROLLABLE_IDLE_STRATEGY . label ( ) ) ) { id . value = counterId ; } } ) ; if ( Aeron . NULL_VALUE != id . value ) { statusIndicator = new UnsafeBufferStatusIndicator ( countersReader . valuesBuffer ( ) , id . value ) ; } return statusIndicator ; }


Input: Return the read - only status indicator for the given send channel URI . [CODESPLIT] public static StatusIndicatorReader sendChannelStatus ( final CountersReader countersReader , final String channel ) { StatusIndicatorReader statusReader = null ; final MutableInteger id = new MutableInteger ( - 1 ) ; countersReader . forEach ( ( counterId , typeId , keyBuffer , label ) -> { if ( typeId == SendChannelStatus . SEND_CHANNEL_STATUS_TYPE_ID ) { if ( channel . startsWith ( keyBuffer . getStringAscii ( ChannelEndpointStatus . CHANNEL_OFFSET ) ) ) { id . value = counterId ; } } } ) ; if ( Aeron . NULL_VALUE != id . value ) { statusReader = new UnsafeBufferStatusIndicator ( countersReader . valuesBuffer ( ) , id . value ) ; } return statusReader ; }


Input: Return the read - only status indicator for the given receive channel URI . [CODESPLIT] public static StatusIndicatorReader receiveChannelStatus ( final CountersReader countersReader , final String channel ) { StatusIndicatorReader statusReader = null ; final MutableInteger id = new MutableInteger ( - 1 ) ; countersReader . forEach ( ( counterId , typeId , keyBuffer , label ) -> { if ( typeId == ReceiveChannelStatus . RECEIVE_CHANNEL_STATUS_TYPE_ID ) { if ( channel . startsWith ( keyBuffer . getStringAscii ( ChannelEndpointStatus . CHANNEL_OFFSET ) ) ) { id . value = counterId ; } } } ) ; if ( Aeron . NULL_VALUE != id . value ) { statusReader = new UnsafeBufferStatusIndicator ( countersReader . valuesBuffer ( ) , id . value ) ; } return statusReader ; }


Input: Set this limit for this buffer as the position at which the next append operation will occur . [CODESPLIT] public void limit ( final int limit ) { if ( limit < 0 || limit >= buffer . capacity ( ) ) { throw new IllegalArgumentException ( "limit outside range: capacity=" + buffer . capacity ( ) + " limit=" + limit ) ; } this . limit = limit ; }


Input: Append a source buffer to the end of the internal buffer resizing the internal buffer as required . [CODESPLIT] public BufferBuilder append ( final DirectBuffer srcBuffer , final int srcOffset , final int length ) { ensureCapacity ( length ) ; buffer . putBytes ( limit , srcBuffer , srcOffset , length ) ; limit += length ; return this ; }


Input: Poll for control response events . [CODESPLIT] public int poll ( ) { controlSessionId = - 1 ; correlationId = - 1 ; relevantId = - 1 ; templateId = - 1 ; errorMessage = null ; pollComplete = false ; return subscription . controlledPoll ( fragmentAssembler , fragmentLimit ) ; }


Input: Map a new loss report in the Aeron directory for a given length . [CODESPLIT] public static MappedByteBuffer mapLossReport ( final String aeronDirectoryName , final int reportFileLength ) { return mapNewFile ( file ( aeronDirectoryName ) , reportFileLength , false ) ; }