signature:
public class SignatureReader { /** * Parses a JavaTypeSignature and makes the given visitor visit it .
 * @ param signature a string containing the signature that must be parsed .
 * @ param startOffset index of the first character of the signature to parsed .
 * @ param signatureVisitor the visitor that must visit this signature .
 * @ return the index of the first character after the parsed signature . */
private static int parseType ( final String signature , final int startOffset , final SignatureVisitor signatureVisitor ) { } }

implementation:
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 'Z' : case 'C' : case 'B' : case 'S' : case 'I' : case 'F' : case 'J' : case 'D' : case 'V' : // 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 'T' : // Case of TypeVariableSignature , an identifier between ' T ' and ' ; ' .
int endOffset = signature . indexOf ( ';' , offset ) ; signatureVisitor . visitTypeVariable ( signature . substring ( offset , endOffset ) ) ; return endOffset + 1 ; case 'L' : // 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 ( ) ; }


signature:
public class ModuleWriter { /** * 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 .
 * @ return the size in bytes of the Module , ModulePackages and ModuleMainClass attributes . */
int computeAttributesSize ( ) { } }

implementation:
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 ;


signature:
public class ModuleWriter { /** * Puts the Module , ModulePackages and ModuleMainClass attributes generated by this ModuleWriter
 * in the given ByteVector .
 * @ param output where the attributes must be put . */
void putAttributes ( final ByteVector output ) { } }

implementation:
// 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 ) ; }


signature:
public class URLDecoder { /** * 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 .
 * @ see # decodeQuery ( String , String ) */
public static String decode ( final String source , final String encoding ) { } }

implementation: return decode ( source , encoding , false ) ;


signature:
public class URLDecoder { /** * Decodes query name or value . */
public static String decodeQuery ( final String source , final String encoding ) { } }

implementation: return decode ( source , encoding , true ) ;


signature:
public class JoyDb { /** * 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 . */
@ Override @ SuppressWarnings ( "unchecked" ) public void start ( ) { } }

implementation:
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!" ) ;


signature:
public class JoyDb { /** * Checks if connection provider can return a connection . */
protected void checkConnectionProvider ( ) { } }

implementation: 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 ) ; }


signature:
public class JoyDb { /** * - - - - - print */
public void printEntities ( final int width ) { } }

implementation: 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 ) ;


signature:
public class TargetClassInfoReader { /** * Returns method signature for some method . If signature is not found , returns < code > null < / code > .
 * Founded signatures means that those method can be proxyfied . */
public MethodSignatureVisitor lookupMethodSignatureVisitor ( final int access , final String name , final String desc , final String className ) { } }

implementation: String key = ProxettaAsmUtil . createMethodSignaturesKey ( access , name , desc , className ) ; return methodSignatures . get ( key ) ;


signature:
public class TargetClassInfoReader { /** * - - - - - visits */
@ Override public void visit ( final int version , final int access , final String name , final String signature , final String superName , final String [ ] interfaces ) { } }

implementation: 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 ) ;


signature:
public class TargetClassInfoReader { /** * Stores method signature for target method . */
@ Override public MethodVisitor visitMethod ( final int access , final String name , final String desc , final String signature , final String [ ] exceptions ) { } }

implementation:
// 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 ) ;


signature:
public class TargetClassInfoReader { /** * Stores signatures for all super public methods not already overridden by target class .
 * All this methods will be accepted for proxyfication . */
@ Override public void visitEnd ( ) { } }

implementation:
// 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 ( ) ; }


signature:
public class TargetClassInfoReader { /** * Creates method signature from method name . */
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 ) { } }

implementation: MethodSignatureVisitor v = new MethodSignatureVisitor ( methodName , access , classname , description , exceptions , signature , declaredTypeGenerics , this ) ; new SignatureReader ( signature != null ? signature : description ) . accept ( v ) ; return v ;


signature:
public class CsvUtil { /** * Parse fields as csv string , */
public static String toCsvString ( final Object ... elements ) { } }

implementation:
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 ( ) ;


signature:
public class CsvUtil { /** * Converts CSV line to string array . */
public static String [ ] toStringArray ( final String line ) { } }

implementation:
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 ] ) ;


signature:
public class CtorResolver { /** * 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 . */
public CtorInjectionPoint resolve ( final Class type , final boolean useAnnotation ) { } }

implementation:
// 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 ) ;


signature:
public class ProxyAspectData { /** * Creates advice ' s class reader . */
private ClassReader createAdviceClassReader ( final Class < ? extends ProxyAdvice > advice ) { } }

implementation: InputStream inputStream = null ; try { inputStream = ClassLoaderUtil . getClassAsStream ( advice ) ; return new ClassReader ( inputStream ) ; } catch ( IOException ioex ) { throw new ProxettaException ( ioex ) ; } finally { StreamUtil . close ( inputStream ) ; }


signature:
public class ProxyAspectData { /** * Returns class reader for advice . */
private ClassReader getCachedAdviceClassReader ( final Class < ? extends ProxyAdvice > advice ) { } }

implementation: if ( adviceClassReaderCache == null ) { adviceClassReaderCache = TypeCache . createDefault ( ) ; } ClassReader adviceReader = adviceClassReaderCache . get ( advice ) ; if ( adviceReader == null ) { adviceReader = createAdviceClassReader ( advice ) ; adviceClassReaderCache . put ( advice , adviceReader ) ; } return adviceReader ;


signature:
public class PBKDF2Encryptor { /** * Symmetrically encrypts the string . */
public String encrypt ( final String str ) { } }

implementation:
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 ; }


signature:
public class PBKDF2Encryptor { /** * Symmetrically decrypts the string . */
public String decrypt ( String str ) { } }

implementation:
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 ; }


signature:
public class LoggerFactory { /** * Sets { @ link LoggerProvider } instance used for creating new { @ link Logger } s . */
public static void setLoggerProvider ( final LoggerProvider loggerProvider ) { } }

implementation: LoggerFactory . loggerProvider = loggerProvider :: createLogger ; if ( loggers != null ) { loggers . clear ( ) ; }


signature:
public class LoggerFactory { /** * Returns logger for given name . Repeated calls to this method with the
 * same argument should return the very same instance of the logger . */
public static Logger getLogger ( final String name ) { } }

implementation: if ( loggers == null ) { return loggerProvider . apply ( name ) ; } return loggers . computeIfAbsent ( name , loggerProvider ) ;


signature:
public class Cookie { /** * Sets the cookie name and checks for validity . */
private void setName ( final String name ) { } }

implementation: 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 ;


signature:
public class MadvocController { /** * 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 . */
public String invoke ( String actionPath , final HttpServletRequest servletRequest , final HttpServletResponse servletResponse ) throws Exception { } }

implementation:
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 ;


signature:
public class MadvocController { /** * Invokes a result after the action invocation .
 * Results may be objects that specify which action result will be used
 * to render the result .
 * 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 .
 * Result value is first checked against aliased values . Then , it is resolved and then passed
 * to the founded { @ link ActionResult } .
 * @ see ActionResult # render ( jodd . madvoc . ActionRequest , Object ) */
@ SuppressWarnings ( "unchecked" ) public void render ( final ActionRequest actionRequest , final Object resultObject ) throws Exception { } }

implementation: 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 ( ) ) ;


signature:
public class MadvocController { /** * Creates new action object from { @ link ActionRuntime } using default constructor . */
protected Object createAction ( final Class actionClass ) { } }

implementation: try { return ClassUtil . newInstance ( actionClass ) ; } catch ( Exception ex ) { throw new MadvocException ( "Invalid Madvoc action" , ex ) ; }


signature:
public class MadvocController { /** * Creates new action request .
 * @ param actionPathaction path
 * @ param actionRuntimeaction runtime
 * @ param actionaction object
 * @ param servletRequesthttp request
 * @ param servletResponsehttp response
 * @ return action request */
protected ActionRequest createActionRequest ( final String actionPath , final String [ ] actionPathChunks , final ActionRuntime actionRuntime , final Object action , final HttpServletRequest servletRequest , final HttpServletResponse servletResponse ) { } }

implementation: return new ActionRequest ( this , actionPath , actionPathChunks , actionRuntime , action , servletRequest , servletResponse ) ;


signature:
public class PetiteFilterManager { /** * Acquires filter from Petite container . */
@ Override protected < R extends ActionFilter > R createWrapper ( final Class < R > wrapperClass ) { } }

implementation: return petiteContainer . createBean ( wrapperClass ) ;


signature:
public class ShutdownAwareScope { /** * Returns < code > true < / code > if bean is destroyable . */
protected boolean isBeanDestroyable ( final BeanData beanData ) { } }

implementation: DestroyMethodPoint [ ] dmp = beanData . definition ( ) . destroyMethodPoints ( ) ; return dmp != null && dmp . length != 0 ;


signature:
public class ShutdownAwareScope { /** * Checks if bean data is destroyable ( has destroy methods ) and
 * registers it for later { @ link # shutdown ( ) } . */
protected void registerDestroyableBeans ( final BeanData beanData ) { } }

implementation: if ( ! isBeanDestroyable ( beanData ) ) { return ; } if ( destroyableBeans == null ) { destroyableBeans = new ArrayList < > ( ) ; } destroyableBeans . add ( beanData ) ;


signature:
public class ShutdownAwareScope { /** * Removes destroyable bean from the list and calls it destroy methods .
 * If bean is not destroyable , does nothing . Bean gets destroyed only once . */
protected void destroyBean ( final BeanData beanData ) { } }

implementation: if ( destroyableBeans == null ) { return ; } if ( ! isBeanDestroyable ( beanData ) ) { return ; } if ( destroyableBeans . remove ( beanData ) ) { beanData . callDestroyMethods ( ) ; }


signature:
public class ShutdownAwareScope { /** * Shutdowns the scope and calls all collected destroyable beans . */
@ Override public void shutdown ( ) { } }

implementation: if ( destroyableBeans == null ) { return ; } for ( final BeanData destroyableBean : destroyableBeans ) { destroyableBean . callDestroyMethods ( ) ; } destroyableBeans . clear ( ) ;


signature:
public class MailServer { /** * Creates { @ link MailSession } { @ link Properties } .
 * @ return session { @ link Properties } */
protected Properties createSessionProperties ( ) { } }

implementation: 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 ;


signature:
public class ReceiverBuilder { /** * Receives the emails as specified by the builder . */
public ReceivedEmail [ ] get ( ) { } }

implementation: 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" ) ; } } } ) ;


signature:
public class LogBuffers { /** * Duplicate the underlying { @ link ByteBuffer } s and wrap them for thread local access .
 * @ return duplicates of the wrapped underlying { @ link ByteBuffer } s . */
public UnsafeBuffer [ ] duplicateTermBuffers ( ) { } }

implementation: 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 ;


signature:
public class ClusteredServiceContainer { /** * Launch the clustered service container and await a shutdown signal .
 * @ param args command line argument which is a list for properties files as URLs or filenames . */
public static void main ( final String [ ] args ) { } }

implementation: loadPropertiesFiles ( args ) ; try ( ClusteredServiceContainer container = launch ( ) ) { container . context ( ) . shutdownSignalBarrier ( ) . await ( ) ; System . out . println ( "Shutdown ClusteredServiceContainer..." ) ; }


signature:
public class PerImageIndicator { /** * Allocate a per { @ link io . aeron . driver . PublicationImage } indicator .
 * @ param tempBuffer to be used for labels and key .
 * @ param name of the counter for the label .
 * @ param countersManager from which to allocated the underlying storage .
 * @ param registrationId to be associated with the counter .
 * @ param sessionId for the stream of messages .
 * @ param streamId for the stream of messages .
 * @ param channel for the stream of messages .
 * @ return a new { @ link AtomicCounter } for tracking the indicator . */
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 ) { } }

implementation: final int counterId = StreamCounter . allocateCounterId ( tempBuffer , name , PER_IMAGE_TYPE_ID , countersManager , registrationId , sessionId , streamId , channel ) ; return new AtomicCounter ( countersManager . valuesBuffer ( ) , counterId , countersManager ) ;


signature:
public class RateReporter { /** * Run loop for the rate reporter */
public void run ( ) { } }

implementation: 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 ) ;


signature:
public class SamplesUtil { /** * Return a reusable , parametrised { @ link FragmentHandler } that calls into a
 * { @ link RateReporter } .
 * @ param reporter for the rate
 * @ return { @ link FragmentHandler } that records the rate information */
public static FragmentHandler rateReporterHandler ( final RateReporter reporter ) { } }

implementation: return ( buffer , offset , length , header ) -> reporter . onMessage ( 1 , length ) ;


signature:
public class SamplesUtil { /** * Generic error handler that just prints message to stdout .
 * @ param channel for the error
 * @ param streamId for the error
 * @ param sessionId for the error , if source
 * @ param message indicating what the error was
 * @ param cause of the error */
@ SuppressWarnings ( "unused" ) public static void printError ( final String channel , final int streamId , final int sessionId , final String message , final HeaderFlyweight cause ) { } }

implementation: System . out . println ( message ) ;


signature:
public class SamplesUtil { /** * Print the rates to stdout
 * @ param messagesPerSec being reported
 * @ param bytesPerSec being reported
 * @ param totalMessages being reported
 * @ param totalBytes being reported */
public static void printRate ( final double messagesPerSec , final double bytesPerSec , final long totalMessages , final long totalBytes ) { } }

implementation: System . out . println ( String . format ( "%.02g msgs/sec, %.02g payload bytes/sec, totals %d messages %d MB" , messagesPerSec , bytesPerSec , totalMessages , totalBytes / ( 1024 * 1024 ) ) ) ;


signature:
public class SamplesUtil { /** * Map an existing file as a read only buffer .
 * @ param location of file to map .
 * @ return the mapped file . */
public static MappedByteBuffer mapExistingFileReadOnly ( final File location ) { } }

implementation: 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 ;


signature:
public class ReplayMerge { /** * 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 . */
public void close ( ) { } }

implementation: 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 ) ; }


signature:
public class ReplayMerge { /** * Process the operation of the merge . Do not call the processing of fragments on the subscription .
 * @ return indication of work done processing the merge . */
public int doWork ( ) { } }

implementation: 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 ;


signature:
public class ReplayMerge { /** * 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 .
 * @ param fragmentHandler to call for fragments
 * @ param fragmentLimit for poll call
 * @ return number of fragments processed . */
public int poll ( final FragmentHandler fragmentHandler , final int fragmentLimit ) { } }

implementation: doWork ( ) ; return null == image ? 0 : image . poll ( fragmentHandler , fragmentLimit ) ;


signature:
public class Publication { /** * Get the current position to which the publication has advanced for this stream .
 * @ return the current position to which the publication has advanced for this stream or { @ link # CLOSED } . */
public long position ( ) { } }

implementation: if ( isClosed ) { return CLOSED ; } final long rawTail = rawTailVolatile ( logMetaDataBuffer ) ; final int termOffset = termOffset ( rawTail , termBufferLength ) ; return computePosition ( termId ( rawTail ) , termOffset , positionBitsToShift , initialTermId ) ;


signature:
public class Publication { /** * Non - blocking publish of a partial buffer containing a message .
 * @ param buffer containing message .
 * @ param offset offset in the buffer at which the encoded message begins .
 * @ param length in bytes of the encoded message .
 * @ return The new stream position , otherwise a negative error value of { @ link # NOT _ CONNECTED } ,
 * { @ link # BACK _ PRESSURED } , { @ link # ADMIN _ ACTION } , { @ link # CLOSED } , or { @ link # MAX _ POSITION _ EXCEEDED } . */
public final long offer ( final DirectBuffer buffer , final int offset , final int length ) { } }

implementation: return offer ( buffer , offset , length , null ) ;


signature:
public class Publication { /** * Non - blocking publish of a message composed of two parts , e . g . a header and encapsulated payload .
 * @ param bufferOne containing the first part of the message .
 * @ param offsetOne at which the first part of the message begins .
 * @ param lengthOne of the first part of the message .
 * @ param bufferTwo containing the second part of the message .
 * @ param offsetTwo at which the second part of the message begins .
 * @ param lengthTwo of the second part of the message .
 * @ return The new stream position , otherwise a negative error value of { @ link # NOT _ CONNECTED } ,
 * { @ link # BACK _ PRESSURED } , { @ link # ADMIN _ ACTION } , { @ link # CLOSED } , or { @ link # MAX _ POSITION _ EXCEEDED } . */
public final long offer ( final DirectBuffer bufferOne , final int offsetOne , final int lengthOne , final DirectBuffer bufferTwo , final int offsetTwo , final int lengthTwo ) { } }

implementation: return offer ( bufferOne , offsetOne , lengthOne , bufferTwo , offsetTwo , lengthTwo , null ) ;


signature:
public class ExclusivePublication { /** * Non - blocking publish of a partial buffer containing a message .
 * @ param buffer containing message .
 * @ param offset offset in the buffer at which the encoded message begins .
 * @ param length in bytes of the encoded message .
 * @ param reservedValueSupplier { @ link ReservedValueSupplier } for the frame .
 * @ return The new stream position , otherwise a negative error value of { @ link # NOT _ CONNECTED } ,
 * { @ link # BACK _ PRESSURED } , { @ link # ADMIN _ ACTION } , { @ link # CLOSED } , or { @ link # MAX _ POSITION _ EXCEEDED } . */
public long offer ( final DirectBuffer buffer , final int offset , final int length , final ReservedValueSupplier reservedValueSupplier ) { } }

implementation: 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 ;


signature:
public class ExclusivePublication { /** * Non - blocking publish of a message composed of two parts , e . g . a header and encapsulated payload .
 * @ param bufferOne containing the first part of the message .
 * @ param offsetOne at which the first part of the message begins .
 * @ param lengthOne of the first part of the message .
 * @ param bufferTwo containing the second part of the message .
 * @ param offsetTwo at which the second part of the message begins .
 * @ param lengthTwo of the second part of the message .
 * @ param reservedValueSupplier { @ link ReservedValueSupplier } for the frame .
 * @ return The new stream position , otherwise a negative error value of { @ link # NOT _ CONNECTED } ,
 * { @ link # BACK _ PRESSURED } , { @ link # ADMIN _ ACTION } , { @ link # CLOSED } , or { @ link # MAX _ POSITION _ EXCEEDED } . */
public long offer ( final DirectBuffer bufferOne , final int offsetOne , final int lengthOne , final DirectBuffer bufferTwo , final int offsetTwo , final int lengthTwo , final ReservedValueSupplier reservedValueSupplier ) { } }

implementation: 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 ;


signature:
public class ExclusivePublication { /** * Non - blocking publish by gathering buffer vectors into a message .
 * @ param vectors which make up the message .
 * @ param reservedValueSupplier { @ link ReservedValueSupplier } for the frame .
 * @ return The new stream position , otherwise a negative error value of { @ link # NOT _ CONNECTED } ,
 * { @ link # BACK _ PRESSURED } , { @ link # ADMIN _ ACTION } , { @ link # CLOSED } , or { @ link # MAX _ POSITION _ EXCEEDED } . */
public long offer ( final DirectBufferVector [ ] vectors , final ReservedValueSupplier reservedValueSupplier ) { } }

implementation: 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 ;


signature:
public class ExclusivePublication { /** * 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 .
 * < 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 ( ) ;
 * if ( publication . tryClaim ( messageLength , bufferClaim ) > 0L )
 * try
 * final MutableDirectBuffer buffer = bufferClaim . buffer ( ) ;
 * final int offset = bufferClaim . offset ( ) ;
 * / / Work with buffer directly or wrap with a flyweight
 * finally
 * bufferClaim . commit ( ) ;
 * } < / pre >
 * @ param length of the range to claim , in bytes . .
 * @ param bufferClaim to be populated if the claim succeeds .
 * @ return The new stream position , otherwise a negative error value of { @ link # NOT _ CONNECTED } ,
 * { @ link # BACK _ PRESSURED } , { @ link # ADMIN _ ACTION } , { @ link # CLOSED } , or { @ link # MAX _ POSITION _ EXCEEDED } .
 * @ throws IllegalArgumentException if the length is greater than { @ link # maxPayloadLength ( ) } within an MTU .
 * @ see BufferClaim # commit ( )
 * @ see BufferClaim # abort ( ) */
public long tryClaim ( final int length , final BufferClaim bufferClaim ) { } }

implementation: 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 ;


signature:
public class ExclusivePublication { /** * Append a padding record log of a given length to make up the log to a position .
 * @ param length of the range to claim , in bytes . .
 * @ return The new stream position , otherwise a negative error value of { @ link # NOT _ CONNECTED } ,
 * { @ link # BACK _ PRESSURED } , { @ link # ADMIN _ ACTION } , { @ link # CLOSED } , or { @ link # MAX _ POSITION _ EXCEEDED } .
 * @ throws IllegalArgumentException if the length is greater than { @ link # maxMessageLength ( ) } . */
public long appendPadding ( final int length ) { } }

implementation: 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 ;


signature:
public class DestinationMessageFlyweight { /** * Set channel field in ASCII
 * @ param channel field value
 * @ return flyweight */
public DestinationMessageFlyweight channel ( final String channel ) { } }

implementation: lengthOfChannel = buffer . putStringAscii ( offset + CHANNEL_OFFSET , channel ) ; return this ;


signature:
public class AeronArchive { /** * Notify the archive that this control session is closed so it can promptly release resources then close the
 * local resources associated with the client . */
public void close ( ) { } }

implementation: 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 ( ) ; }


signature:
public class AeronArchive { /** * Connect to an Aeron archive by providing a { @ link Context } . This will create a control session .
 * Before connecting { @ link Context # conclude ( ) } will be called .
 * If an exception occurs then { @ link Context # close ( ) } will be called .
 * @ param ctx for connection configuration .
 * @ return the newly created Aeron Archive client . */
public static AeronArchive connect ( final Context ctx ) { } }

implementation: 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 ; }


signature:
public class AeronArchive { /** * 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 .
 * @ param ctx for the archive connection .
 * @ return the { @ link AsyncConnect } that can be polled for completion . */
public static AsyncConnect asyncConnect ( final Context ctx ) { } }

implementation: 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 ; }


signature:
public class AeronArchive { /** * 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 .
 * @ return the error String otherwise null if no error is found . */
public String pollForErrorResponse ( ) { } }

implementation: 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 ( ) ; }


signature:
public class AeronArchive { /** * Check if an error has been returned for the control session and throw a { @ link ArchiveException } if
 * { @ link Context # errorHandler ( ErrorHandler ) } is not set .
 * To check for an error response without raising an exception then try { @ link # pollForErrorResponse ( ) } .
 * @ see # pollForErrorResponse ( ) */
public void checkForErrorResponse ( ) { } }

implementation: 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 ( ) ; }


signature:
public class AeronArchive { /** * 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 .
 * This is a sessionId specific recording .
 * @ param channel for the publication .
 * @ param streamId for the publication .
 * @ return the { @ link Publication } ready for use . */
public Publication addRecordedPublication ( final String channel , final int streamId ) { } }

implementation: 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 ;


signature:
public class AeronArchive { /** * Add an { @ link ExclusivePublication } and set it up to be recorded .
 * This is a sessionId specific recording .
 * @ param channel for the publication .
 * @ param streamId for the publication .
 * @ return the { @ link ExclusivePublication } ready for use . */
public ExclusivePublication addRecordedExclusivePublication ( final String channel , final int streamId ) { } }

implementation: 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 ;


signature:
public class AeronArchive { /** * Start recording a channel and stream pairing .
 * 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 .
 * @ param channel to be recorded .
 * @ param streamId to be recorded .
 * @ param sourceLocation of the publication to be recorded .
 * @ return the subscriptionId , i . e . { @ link Subscription # registrationId ( ) } , of the recording . */
public long startRecording ( final String channel , final int streamId , final SourceLocation sourceLocation ) { } }

implementation: 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 ( ) ; }


signature:
public class AeronArchive { /** * Stop recording for a channel and stream pairing .
 * 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 .
 * @ param channel to stop recording for .
 * @ param streamId to stop recording for . */
public void stopRecording ( final String channel , final int streamId ) { } }

implementation: 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 ( ) ; }


signature:
public class AeronArchive { /** * Stop recording a sessionId specific recording that pertains to the given { @ link Publication } .
 * @ param publication to stop recording for . */
public void stopRecording ( final Publication publication ) { } }

implementation: final String recordingChannel = ChannelUri . addSessionId ( publication . channel ( ) , publication . sessionId ( ) ) ; stopRecording ( recordingChannel , publication . streamId ( ) ) ;


signature:
public class AeronArchive { /** * Stop recording for a subscriptionId that has been returned from
 * { @ link # startRecording ( String , int , SourceLocation ) } or
 * { @ link # extendRecording ( long , String , int , SourceLocation ) } .
 * @ param subscriptionId is the { @ link Subscription # registrationId ( ) } for the recording in the archive . */
public void stopRecording ( final long subscriptionId ) { } }

implementation: 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 ( ) ; }


signature:
public class AeronArchive { /** * 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 .
 * 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 } .
 * @ param recordingId to be replayed .
 * @ param position from which the replay should begin or { @ link # NULL _ POSITION } if from the start .
 * @ param length of the stream to be replayed . Use { @ link Long # MAX _ VALUE } to follow a live recording or
 * { @ link # NULL _ LENGTH } to replay the whole stream of unknown length .
 * @ param replayChannel to which the replay should be sent .
 * @ param replayStreamId to which the replay should be sent .
 * @ return the id of the replay session which will be the same as the { @ link Image # sessionId ( ) } of the received
 * replay for correlation with the matching channel and stream id in the lower 32 bits . */
public long startReplay ( final long recordingId , final long position , final long length , final String replayChannel , final int replayStreamId ) { } }

implementation: 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 ( ) ; }


signature:
public class AeronArchive { /** * Stop a replay session .
 * @ param replaySessionId to stop replay for . */
public void stopReplay ( final long replaySessionId ) { } }

implementation: 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 ( ) ; }


signature:
public class AeronArchive { /** * 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 .
 * @ param recordingId to be replayed .
 * @ param position from which the replay should begin or { @ link # NULL _ POSITION } if from the start .
 * @ param length of the stream to be replayed or { @ link Long # MAX _ VALUE } to follow a live recording .
 * @ param replayChannel to which the replay should be sent .
 * @ param replayStreamId to which the replay should be sent .
 * @ return the { @ link Subscription } for consuming the replay . */
public Subscription replay ( final long recordingId , final long position , final long length , final String replayChannel , final int replayStreamId ) { } }

implementation: 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 ( ) ; }


signature:
public class AeronArchive { /** * List all recording descriptors from a recording id with a limit of record count .
 * If the recording id is greater than the largest known id then nothing is returned .
 * @ param fromRecordingId at which to begin the listing .
 * @ param recordCount to limit for each query .
 * @ param consumer to which the descriptors are dispatched .
 * @ return the number of descriptors found and consumed . */
public int listRecordings ( final long fromRecordingId , final int recordCount , final RecordingDescriptorConsumer consumer ) { } }

implementation: 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 ( ) ; }


signature:
public class AeronArchive { /** * List recording descriptors from a recording id with a limit of record count for a given channelFragment and
 * stream id .
 * If the recording id is greater than the largest known id then nothing is returned .
 * @ param fromRecordingId at which to begin the listing .
 * @ param recordCount to limit for each query .
 * @ param channelFragment for a contains match on the original channel stored with the archive descriptor .
 * @ param streamId to match .
 * @ param consumer to which the descriptors are dispatched .
 * @ return the number of descriptors found and consumed . */
public int listRecordingsForUri ( final long fromRecordingId , final int recordCount , final String channelFragment , final int streamId , final RecordingDescriptorConsumer consumer ) { } }

implementation: 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 ( ) ; }


signature:
public class AeronArchive { /** * List a recording descriptor for a single recording id .
 * If the recording id is greater than the largest known id then nothing is returned .
 * @ param recordingId at which to begin the listing .
 * @ param consumer to which the descriptors are dispatched .
 * @ return the number of descriptors found and consumed . */
public int listRecording ( final long recordingId , final RecordingDescriptorConsumer consumer ) { } }

implementation: 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 ( ) ; }


signature:
public class AeronArchive { /** * Get the position recorded for an active recording . If no active recording then return { @ link # NULL _ POSITION } .
 * @ param recordingId of the active recording for which the position is required .
 * @ return the recorded position for the active recording or { @ link # NULL _ POSITION } if recording not active .
 * @ see # getStopPosition ( long ) */
public long getRecordingPosition ( final long recordingId ) { } }

implementation: 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 ( ) ; }


signature:
public class AeronArchive { /** * Find the last recording that matches the given criteria .
 * @ param minRecordingId to search back to .
 * @ param channelFragment for a contains match on the original channel stored with the archive descriptor .
 * @ param streamId of the recording to match .
 * @ param sessionId of the recording to match .
 * @ return the recordingId if found otherwise { @ link Aeron # NULL _ VALUE } if not found . */
public long findLastMatchingRecording ( final long minRecordingId , final String channelFragment , final int streamId , final int sessionId ) { } }

implementation: 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 ( ) ; }


signature:
public class AeronArchive { /** * 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 .
 * @ param recordingId of the stopped recording to be truncated .
 * @ param position to which the recording will be truncated . */
public void truncateRecording ( final long recordingId , final long position ) { } }

implementation: 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 ( ) ; }


signature:
public class AeronArchive { /** * 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 ) } .
 * @ param pseudoIndex in the active list at which to begin for paging .
 * @ param subscriptionCount to get in a listing .
 * @ param channelFragment to do a contains match on the stripped channel URI . Empty string is match all .
 * @ param streamId to match on the subscription .
 * @ param applyStreamId true if the stream id should be matched .
 * @ param consumer for the matched subscription descriptors .
 * @ return the count of matched subscriptions . */
public int listRecordingSubscriptions ( final int pseudoIndex , final int subscriptionCount , final String channelFragment , final int streamId , final boolean applyStreamId , final RecordingSubscriptionDescriptorConsumer consumer ) { } }

implementation: 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 ( ) ; }


signature:
public class SegmentInspector { /** * Dump the contents of a segment file to a { @ link PrintStream } .
 * @ param out for the dumped contents .
 * @ param messageDumpLimit for the number of bytes per message fragment to dump .
 * @ param buffer the wraps the segment file . */
public static void dumpSegment ( final PrintStream out , final int messageDumpLimit , final UnsafeBuffer buffer ) { } }

implementation: 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 ) ; }


signature:
public class MultipleSubscribersWithFragmentAssembly { /** * Print the information for an available image to stdout .
 * @ param image that has been created */
public static void eventAvailableImage ( final Image image ) { } }

implementation: 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 ( ) ) ;


signature:
public class MultipleSubscribersWithFragmentAssembly { /** * This handler is called when image is unavailable
 * @ param image that has gone inactive */
public static void eventUnavailableImage ( final Image image ) { } }

implementation: final Subscription subscription = image . subscription ( ) ; System . out . format ( "inactive image on %s streamId %d sessionId %x%n" , subscription . channel ( ) , subscription . streamId ( ) , image . sessionId ( ) ) ;


signature:
public class MultipleSubscribersWithFragmentAssembly { /** * Return a reusable , parameterized { @ link FragmentHandler } that prints to stdout for the first stream ( STREAM )
 * @ param streamId to show when printing
 * @ return subscription data handler function that prints the message contents */
public static FragmentHandler reassembledStringMessage1 ( final int streamId ) { } }

implementation: 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 ) ; } } ;


signature:
public class StatusUtil { /** * Return the controllable idle strategy { @ link StatusIndicator } .
 * @ param countersReader that holds the status indicator .
 * @ return status indicator to use or null if not found . */
public static StatusIndicator controllableIdleStrategy ( final CountersReader countersReader ) { } }

implementation: 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 ;


signature:
public class StatusUtil { /** * Return the read - only status indicator for the given send channel URI .
 * @ param countersReader that holds the status indicator .
 * @ param channel for the send channel .
 * @ return read - only status indicator that can be used to query the status of the send channel or null
 * @ see ChannelEndpointStatus for status values and indications . */
public static StatusIndicatorReader sendChannelStatus ( final CountersReader countersReader , final String channel ) { } }

implementation: 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 ;


signature:
public class StatusUtil { /** * Return the read - only status indicator for the given receive channel URI .
 * @ param countersReader that holds the status indicator .
 * @ param channel for the receive channel .
 * @ return read - only status indicator that can be used to query the status of the receive channel or null .
 * @ see ChannelEndpointStatus for status values and indications . */
public static StatusIndicatorReader receiveChannelStatus ( final CountersReader countersReader , final String channel ) { } }

implementation: 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 ;


signature:
public class BufferBuilder { /** * Set this limit for this buffer as the position at which the next append operation will occur .
 * @ param limit to be the new value . */
public void limit ( final int limit ) { } }

implementation: if ( limit < 0 || limit >= buffer . capacity ( ) ) { throw new IllegalArgumentException ( "limit outside range: capacity=" + buffer . capacity ( ) + " limit=" + limit ) ; } this . limit = limit ;


signature:
public class BufferBuilder { /** * Append a source buffer to the end of the internal buffer , resizing the internal buffer as required .
 * @ param srcBuffer from which to copy .
 * @ param srcOffset in the source buffer from which to copy .
 * @ param length in bytes to copy from the source buffer .
 * @ return the builder for fluent API usage . */
public BufferBuilder append ( final DirectBuffer srcBuffer , final int srcOffset , final int length ) { } }

implementation: ensureCapacity ( length ) ; buffer . putBytes ( limit , srcBuffer , srcOffset , length ) ; limit += length ; return this ;


signature:
public class ControlResponsePoller { /** * Poll for control response events .
 * @ return the number of fragments read during the operation . Zero if no events are available . */
public int poll ( ) { } }

implementation: controlSessionId = - 1 ; correlationId = - 1 ; relevantId = - 1 ; templateId = - 1 ; errorMessage = null ; pollComplete = false ; return subscription . controlledPoll ( fragmentAssembler , fragmentLimit ) ;


signature:
public class LossReportUtil { /** * Map a new loss report in the Aeron directory for a given length .
 * @ param aeronDirectoryName in which to create the file .
 * @ param reportFileLength for the file .
 * @ return the newly mapped buffer for the file . */
public static MappedByteBuffer mapLossReport ( final String aeronDirectoryName , final int reportFileLength ) { } }

implementation: return mapNewFile ( file ( aeronDirectoryName ) , reportFileLength , false ) ;


signature:
public class ImageControlledFragmentAssembler { /** * The implementation of { @ link ControlledFragmentHandler } that reassembles and forwards whole messages .
 * @ param buffer containing the data .
 * @ param offset at which the data begins .
 * @ param length of the data in bytes .
 * @ param header representing the meta data for the data .
 * @ return { @ link io . aeron . logbuffer . ControlledFragmentHandler . Action } to be taken after processing fragment . */
public Action onFragment ( final DirectBuffer buffer , final int offset , final int length , final Header header ) { } }

implementation: final byte flags = header . flags ( ) ; Action action = Action . CONTINUE ; if ( ( flags & UNFRAGMENTED ) == UNFRAGMENTED ) { action = delegate . onFragment ( buffer , offset , length , header ) ; } else { if ( ( flags & BEGIN_FRAG_FLAG ) == BEGIN_FRAG_FLAG ) { builder . reset ( ) . append ( buffer , offset , length ) ; } else { final int limit = builder . limit ( ) ; builder . append ( buffer , offset , length ) ; if ( ( flags & END_FRAG_FLAG ) == END_FRAG_FLAG ) { final int msgLength = builder . limit ( ) ; action = delegate . onFragment ( builder . buffer ( ) , 0 , msgLength , header ) ; if ( Action . ABORT == action ) { builder . limit ( limit ) ; } else { builder . reset ( ) ; } } } } return action ;


signature:
public class StreamStat { /** * Take a snapshot of all the counters and group them by streams .
 * @ return a snapshot of all the counters and group them by streams . */
public Map < StreamCompositeKey , List < StreamPosition > > snapshot ( ) { } }

implementation: final Map < StreamCompositeKey , List < StreamPosition > > streams = new HashMap < > ( ) ; counters . forEach ( ( counterId , typeId , keyBuffer , label ) -> { if ( ( typeId >= PUBLISHER_LIMIT_TYPE_ID && typeId <= RECEIVER_POS_TYPE_ID ) || typeId == SENDER_LIMIT_TYPE_ID || typeId == PER_IMAGE_TYPE_ID || typeId == PUBLISHER_POS_TYPE_ID ) { final StreamCompositeKey key = new StreamCompositeKey ( keyBuffer . getInt ( SESSION_ID_OFFSET ) , keyBuffer . getInt ( STREAM_ID_OFFSET ) , keyBuffer . getStringAscii ( CHANNEL_OFFSET ) ) ; final StreamPosition position = new StreamPosition ( keyBuffer . getLong ( REGISTRATION_ID_OFFSET ) , counters . getCounterValue ( counterId ) , typeId ) ; streams . computeIfAbsent ( key , ( ignore ) -> new ArrayList < > ( ) ) . add ( position ) ; } } ) ; return streams ;


signature:
public class StreamStat { /** * Print a snapshot of the stream positions to a { @ link PrintStream } .
 * Each stream will be printed on its own line .
 * @ param out to which the stream snapshot will be written .
 * @ return the number of streams printed . */
public int print ( final PrintStream out ) { } }

implementation: final Map < StreamCompositeKey , List < StreamPosition > > streams = snapshot ( ) ; final StringBuilder builder = new StringBuilder ( ) ; for ( final Map . Entry < StreamCompositeKey , List < StreamPosition > > entry : streams . entrySet ( ) ) { builder . setLength ( 0 ) ; final StreamCompositeKey key = entry . getKey ( ) ; builder . append ( "sessionId=" ) . append ( key . sessionId ( ) ) . append ( " streamId=" ) . append ( key . streamId ( ) ) . append ( " channel=" ) . append ( key . channel ( ) ) . append ( " :" ) ; for ( final StreamPosition streamPosition : entry . getValue ( ) ) { builder . append ( ' ' ) . append ( labelName ( streamPosition . typeId ( ) ) ) . append ( ':' ) . append ( streamPosition . id ( ) ) . append ( ':' ) . append ( streamPosition . value ( ) ) ; } out . println ( builder ) ; } return streams . size ( ) ;


signature:
public class OptimalMulticastDelayGenerator { /** * Generate a new randomized delay value in the units of { @ code maxBackoffT } } .
 * @ return delay in units of { @ code maxBackoffT } . */
public double generateNewOptimalDelay ( ) { } }

implementation: final double x = uniformRandom ( randMax ) + baseX ; return constantT * Math . log ( x * factorT ) ;


signature:
public class UnicastFlowControl { /** * { @ inheritDoc } */
public long onStatusMessage ( final StatusMessageFlyweight flyweight , final InetSocketAddress receiverAddress , final long senderLimit , final int initialTermId , final int positionBitsToShift , final long timeNs ) { } }

implementation: final long position = computePosition ( flyweight . consumptionTermId ( ) , flyweight . consumptionTermOffset ( ) , positionBitsToShift , initialTermId ) ; lastPosition = Math . max ( lastPosition , position ) ; timeOfLastStatusMessage = timeNs ; return Math . max ( senderLimit , position + flyweight . receiverWindowLength ( ) ) ;


signature:
public class UnicastFlowControl { /** * { @ inheritDoc } */
public long onIdle ( final long timeNs , final long senderLimit , final long senderPosition , final boolean isEos ) { } }

implementation: if ( isEos && shouldLinger ) { if ( lastPosition >= senderPosition || ( ( timeOfLastStatusMessage + RECEIVER_TIMEOUT_NS ) - timeNs < 0 ) ) { shouldLinger = false ; } } return senderLimit ;


signature:
public class RecordingDescriptorPoller { /** * Reset the poller to dispatch the descriptors returned from a query .
 * @ param correlationId for the response .
 * @ param recordCount of descriptors to expect .
 * @ param consumer to which the recording descriptors are to be dispatched . */
public void reset ( final long correlationId , final int recordCount , final RecordingDescriptorConsumer consumer ) { } }

implementation: this . correlationId = correlationId ; this . consumer = consumer ; this . remainingRecordCount = recordCount ; isDispatchComplete = false ;


signature:
public class LossReportReader { /** * Read a { @ link LossReport } contained in the buffer . This can be done concurrently .
 * @ param buffer containing the loss report .
 * @ param entryConsumer to be called to accept each entry in the report .
 * @ return the number of entries read . */
public static int read ( final AtomicBuffer buffer , final EntryConsumer entryConsumer ) { } }

implementation: final int capacity = buffer . capacity ( ) ; int recordsRead = 0 ; int offset = 0 ; while ( offset < capacity ) { final long observationCount = buffer . getLongVolatile ( offset + OBSERVATION_COUNT_OFFSET ) ; if ( observationCount <= 0 ) { break ; } ++ recordsRead ; final String channel = buffer . getStringAscii ( offset + CHANNEL_OFFSET ) ; final String source = buffer . getStringAscii ( offset + CHANNEL_OFFSET + SIZE_OF_INT + channel . length ( ) ) ; entryConsumer . accept ( observationCount , buffer . getLong ( offset + TOTAL_BYTES_LOST_OFFSET ) , buffer . getLong ( offset + FIRST_OBSERVATION_OFFSET ) , buffer . getLong ( offset + LAST_OBSERVATION_OFFSET ) , buffer . getInt ( offset + SESSION_ID_OFFSET ) , buffer . getInt ( offset + STREAM_ID_OFFSET ) , channel , source ) ; final int recordLength = CHANNEL_OFFSET + ( SIZE_OF_INT * 2 ) + channel . length ( ) + source . length ( ) ; offset += BitUtil . align ( recordLength , ENTRY_ALIGNMENT ) ; } return recordsRead ;


signature:
public class DataHeaderFlyweight { /** * Return an initialised default Data Frame Header .
 * @ param sessionId for the header
 * @ param streamId for the header
 * @ param termId for the header
 * @ return byte array containing the header */
public static UnsafeBuffer createDefaultHeader ( final int sessionId , final int streamId , final int termId ) { } }

implementation: final UnsafeBuffer buffer = new UnsafeBuffer ( BufferUtil . allocateDirectAligned ( HEADER_LENGTH , CACHE_LINE_LENGTH ) ) ; buffer . putByte ( VERSION_FIELD_OFFSET , CURRENT_VERSION ) ; buffer . putByte ( FLAGS_FIELD_OFFSET , ( byte ) BEGIN_AND_END_FLAGS ) ; buffer . putShort ( TYPE_FIELD_OFFSET , ( short ) HDR_TYPE_DATA , LITTLE_ENDIAN ) ; buffer . putInt ( SESSION_ID_FIELD_OFFSET , sessionId , LITTLE_ENDIAN ) ; buffer . putInt ( STREAM_ID_FIELD_OFFSET , streamId , LITTLE_ENDIAN ) ; buffer . putInt ( TERM_ID_FIELD_OFFSET , termId , LITTLE_ENDIAN ) ; buffer . putLong ( RESERVED_VALUE_OFFSET , DEFAULT_RESERVE_VALUE ) ; return buffer ;


signature:
public class CounterMessageFlyweight { /** * Fill the key buffer .
 * @ param keyBuffer containing the optional key for the counter .
 * @ param keyOffset within the keyBuffer at which the key begins .
 * @ param keyLength of the key in the keyBuffer .
 * @ return flyweight */
public CounterMessageFlyweight keyBuffer ( final DirectBuffer keyBuffer , final int keyOffset , final int keyLength ) { } }

implementation: buffer . putInt ( KEY_LENGTH_OFFSET , keyLength ) ; if ( null != keyBuffer && keyLength > 0 ) { buffer . putBytes ( keyBufferOffset ( ) , keyBuffer , keyOffset , keyLength ) ; } return this ;


signature:
public class CounterMessageFlyweight { /** * Fill the label buffer .
 * @ param labelBuffer containing the mandatory label for the counter .
 * @ param labelOffset within the labelBuffer at which the label begins .
 * @ param labelLength of the label in the labelBuffer .
 * @ return flyweight */
public CounterMessageFlyweight labelBuffer ( final DirectBuffer labelBuffer , final int labelOffset , final int labelLength ) { } }

implementation: buffer . putInt ( labelOffset ( ) , labelLength ) ; buffer . putBytes ( labelBufferOffset ( ) , labelBuffer , labelOffset , labelLength ) ; return this ;


signature:
public class Subscription { /** * Poll the { @ link Image } s under the subscription for available message fragments .
 * Each fragment read will be a whole message if it is under MTU length . If larger than MTU then it will come
 * as a series of fragments ordered within a session .
 * To assemble messages that span multiple fragments then use { @ link FragmentAssembler } .
 * @ param fragmentHandler callback for handling each message fragment as it is read .
 * @ param fragmentLimit number of message fragments to limit when polling across multiple { @ link Image } s .
 * @ return the number of fragments received */
public int poll ( final FragmentHandler fragmentHandler , final int fragmentLimit ) { } }

implementation: final Image [ ] images = this . images ; final int length = images . length ; int fragmentsRead = 0 ; int startingIndex = roundRobinIndex ++ ; if ( startingIndex >= length ) { roundRobinIndex = startingIndex = 0 ; } for ( int i = startingIndex ; i < length && fragmentsRead < fragmentLimit ; i ++ ) { fragmentsRead += images [ i ] . poll ( fragmentHandler , fragmentLimit - fragmentsRead ) ; } for ( int i = 0 ; i < startingIndex && fragmentsRead < fragmentLimit ; i ++ ) { fragmentsRead += images [ i ] . poll ( fragmentHandler , fragmentLimit - fragmentsRead ) ; } return fragmentsRead ;


signature:
public class Subscription { /** * Poll in a controlled manner the { @ link Image } s under the subscription for available message fragments .
 * Control is applied to fragments in the stream . If more fragments can be read on another stream
 * they will even if BREAK or ABORT is returned from the fragment handler .
 * Each fragment read will be a whole message if it is under MTU length . If larger than MTU then it will come
 * as a series of fragments ordered within a session .
 * To assemble messages that span multiple fragments then use { @ link ControlledFragmentAssembler } .
 * @ param fragmentHandler callback for handling each message fragment as it is read .
 * @ param fragmentLimit number of message fragments to limit when polling across multiple { @ link Image } s .
 * @ return the number of fragments received
 * @ see ControlledFragmentHandler */
public int controlledPoll ( final ControlledFragmentHandler fragmentHandler , final int fragmentLimit ) { } }

implementation: final Image [ ] images = this . images ; final int length = images . length ; int fragmentsRead = 0 ; int startingIndex = roundRobinIndex ++ ; if ( startingIndex >= length ) { roundRobinIndex = startingIndex = 0 ; } for ( int i = startingIndex ; i < length && fragmentsRead < fragmentLimit ; i ++ ) { fragmentsRead += images [ i ] . controlledPoll ( fragmentHandler , fragmentLimit - fragmentsRead ) ; } for ( int i = 0 ; i < startingIndex && fragmentsRead < fragmentLimit ; i ++ ) { fragmentsRead += images [ i ] . controlledPoll ( fragmentHandler , fragmentLimit - fragmentsRead ) ; } return fragmentsRead ;


signature:
public class Subscription { /** * Poll the { @ link Image } s under the subscription for available message fragments in blocks .
 * This method is useful for operations like bulk archiving and messaging indexing .
 * @ param blockHandler to receive a block of fragments from each { @ link Image } .
 * @ param blockLengthLimit for each { @ link Image } polled .
 * @ return the number of bytes consumed . */
public long blockPoll ( final BlockHandler blockHandler , final int blockLengthLimit ) { } }

implementation: long bytesConsumed = 0 ; for ( final Image image : images ) { bytesConsumed += image . blockPoll ( blockHandler , blockLengthLimit ) ; } return bytesConsumed ;


signature:
public class Subscription { /** * Poll the { @ link Image } s under the subscription for available message fragments in blocks .
 * This method is useful for operations like bulk archiving a stream to file .
 * @ param rawBlockHandler to receive a block of fragments from each { @ link Image } .
 * @ param blockLengthLimit for each { @ link Image } polled .
 * @ return the number of bytes consumed . */
public long rawPoll ( final RawBlockHandler rawBlockHandler , final int blockLengthLimit ) { } }

implementation: long bytesConsumed = 0 ; for ( final Image image : images ) { bytesConsumed += image . rawPoll ( rawBlockHandler , blockLengthLimit ) ; } return bytesConsumed ;


signature:
public class Subscription { /** * Return the { @ link Image } associated with the given sessionId .
 * @ param sessionId associated with the { @ link Image } .
 * @ return Image associated with the given sessionId or null if no Image exist . */
public Image imageBySessionId ( final int sessionId ) { } }

implementation: Image result = null ; for ( final Image image : images ) { if ( sessionId == image . sessionId ( ) ) { result = image ; break ; } } return result ;


signature:
public class Subscription { /** * Iterate over the { @ link Image } s for this subscription .
 * @ param consumer to handle each { @ link Image } . */
public void forEachImage ( final Consumer < Image > consumer ) { } }

implementation: for ( final Image image : images ) { consumer . accept ( image ) ; }


signature:
public class ArchivingMediaDriver { /** * Launch a new { @ link ArchivingMediaDriver } with provided contexts .
 * @ param driverCtx for configuring the { @ link MediaDriver } .
 * @ param archiveCtx for configuring the { @ link Archive } .
 * @ return a new { @ link ArchivingMediaDriver } with the provided contexts . */
public static ArchivingMediaDriver launch ( final MediaDriver . Context driverCtx , final Archive . Context archiveCtx ) { } }

implementation: final MediaDriver driver = MediaDriver . launch ( driverCtx ) ; final Archive archive = Archive . launch ( archiveCtx . mediaDriverAgentInvoker ( driver . sharedAgentInvoker ( ) ) . errorHandler ( driverCtx . errorHandler ( ) ) . errorCounter ( driverCtx . systemCounters ( ) . get ( SystemCounterDescriptor . ERRORS ) ) ) ; return new ArchivingMediaDriver ( driver , archive ) ;


signature: public class Catalog { public static boolean originalChannelContains ( final RecordingDescriptorDecoder descriptorDecoder , final byte [ ] channelFragment ) { } }

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


signature:
public class Catalog { /** * On catalog load we verify entries are in coherent state and attempt to recover entries data where untimely
 * termination of recording has resulted in an unaccounted for stopPosition / stopTimestamp . This operation may be
 * expensive for large catalogs .
 * @ param fixOnRefresh set if the catalog should have its entries fixed . */
private void refreshCatalog ( final boolean fixOnRefresh ) { } }

implementation: if ( fixOnRefresh ) { forEach ( this :: refreshAndFixDescriptor ) ; } else { forEach ( ( ( headerEncoder , headerDecoder , descriptorEncoder , descriptorDecoder ) -> nextRecordingId ++ ) ) ; }


signature:
public class TermAppender { /** * Claim length of a the term buffer for writing in the message with zero copy semantics .
 * @ param header for writing the default header .
 * @ param length of the message to be written .
 * @ param bufferClaim to be updated with the claimed region .
 * @ param activeTermId used for flow control .
 * @ return the resulting offset of the term after the append on success otherwise { @ link # FAILED } . */
public int claim ( final HeaderWriter header , final int length , final BufferClaim bufferClaim , final int activeTermId ) { } }

implementation: final int frameLength = length + HEADER_LENGTH ; final int alignedLength = align ( frameLength , FRAME_ALIGNMENT ) ; final UnsafeBuffer termBuffer = this . termBuffer ; final int termLength = termBuffer . capacity ( ) ; final long rawTail = getAndAddRawTail ( alignedLength ) ; final int termId = termId ( rawTail ) ; final long termOffset = rawTail & 0xFFFF_FFFFL ; checkTerm ( activeTermId , termId ) ; long resultingOffset = termOffset + alignedLength ; if ( resultingOffset > termLength ) { resultingOffset = handleEndOfLogCondition ( termBuffer , termOffset , header , termLength , termId ) ; } else { final int frameOffset = ( int ) termOffset ; header . write ( termBuffer , frameOffset , frameLength , termId ) ; bufferClaim . wrap ( termBuffer , frameOffset , frameLength ) ; } return ( int ) resultingOffset ;