signature:
public class SimpleMonitor { /** * Renders the table . */
protected void printTable ( TextTableModel printTable ) { } }

implementation: for ( int i = 0 ; i < printTable . getRowCount ( ) ; i ++ ) { StringBuffer result = new StringBuffer ( ) ; for ( int j = 0 ; j < printTable . getColumnCount ( ) ; j ++ ) { String valueToPrint = printTable . get ( j , i ) ; valueToPrint = ( valueToPrint == null ) ? "" : valueToPrint ; result . append ( valueToPrint ) ; Integer maxColumnSize = printTable . getMaxColumnSize ( j ) ; int padding = ( ( maxColumnSize == null ) ? 0 : maxColumnSize ) - valueToPrint . length ( ) ; padding = ( padding < 0 ) ? 0 : padding ; for ( int s = 0 ; s < padding ; s ++ ) { result . append ( " " ) ; } result . append ( " % " ) ; } result . append ( "\n" ) ; System . out . print ( result ) ; }


signature:
public class SwingKeyCombinationBuilder { /** * { @ inheritDoc } */
public KeyStroke withKey ( String key ) { } }

implementation:
// Extract the modifiers as a specification string .
String keyString = modifiersToString ( modifiers ) ; // Reset the modifiers so the builder can be used again .
modifiers = 0 ; return KeyStroke . getKeyStroke ( keyString + key ) ;


signature:
public class SwingKeyCombinationBuilder { /** * Converts the modifiers to a specification string for KeyStroke .
 * @ param modifiers The modifiers .
 * @ return A fragment of the key specification string used by KeyStroke . */
private String modifiersToString ( int modifiers ) { } }

implementation: String result = "" ; if ( ( modifiers & InputEvent . SHIFT_MASK ) != 0 ) { result += "shift " ; } if ( ( modifiers & InputEvent . CTRL_MASK ) != 0 ) { result += "ctrl " ; } if ( ( modifiers & InputEvent . META_MASK ) != 0 ) { result += "meta " ; } if ( ( modifiers & InputEvent . ALT_MASK ) != 0 ) { result += "alt " ; } if ( ( modifiers & InputEvent . ALT_GRAPH_MASK ) != 0 ) { result += "altGraph " ; } return result ;


signature:
public class EnhancedTextTableImpl { /** * { @ inheritDoc } */
public void insertAttribute ( AttributeSet attributes , int c , int r ) { } }

implementation: attributeGrid . insertAttribute ( attributes , c , r ) ; updateListenersOnAttributeChange ( c , r ) ;


signature:
public class EnhancedTextTableImpl { /** * { @ inheritDoc } */
public void insertColumnAttribute ( AttributeSet attributes , int c ) { } }

implementation: attributeGrid . insertColumnAttribute ( attributes , c ) ; updateListenersOnAttributeChange ( c , - 1 ) ;


signature:
public class EnhancedTextTableImpl { /** * { @ inheritDoc } */
public void insertRowAttribute ( AttributeSet attributes , int r ) { } }

implementation: attributeGrid . insertRowAttribute ( attributes , r ) ; updateListenersOnAttributeChange ( - 1 , r ) ;


signature:
public class EnhancedTextTableImpl { /** * Notifies all interested listeners of an update to this model .
 * @ param col The column that changed , or < tt > - 1 < / tt > if change not applicable to columns .
 * @ param row The row that changed , or < tt > - 1 < / tt > if change not applicable to rows . */
protected void updateListenersOnAttributeChange ( int col , int row ) { } }

implementation: TextTableEvent event = new TextTableEvent ( this , row , col , true ) ; for ( TextTableListener listener : listeners ) { listener . changedUpdate ( event ) ; }


signature:
public class Validation { /** * Converts a string to an integer . The string must be a valid integer or the result will be zero .
 * @ param s The string to convert .
 * @ return The string as an integer , or 0 if it is not a valid integer . */
public static int toInteger ( String s ) { } }

implementation:
try { return Integer . parseInt ( s ) ; } catch ( NumberFormatException e ) { // Exception noted so can be ignored .
e = null ; return 0 ; }


signature:
public class Validation { /** * Converts a string to a date . The string must be a date in the correct format or this method will return null .
 * @ param s The string to convert .
 * @ return The string as a date or null if it is not a valid date . */
public static Date toDate ( String s ) { } }

implementation:
// Build a date formatter using the format specified by dateFormat
DateFormat dateFormatter = new SimpleDateFormat ( dateFormat ) ; try { return dateFormatter . parse ( s ) ; } catch ( ParseException e ) { // Exception noted so can be ignored .
e = null ; return null ; }


signature:
public class Validation { /** * Check that a string is a date in the format specified by dateFormat .
 * @ param s The string to check for being a date .
 * @ return True if the string is a date . */
public static boolean isDate ( String s ) { } }

implementation:
// Build a date formatter using the format specified by dateFormat
DateFormat dateFormatter = new SimpleDateFormat ( dateFormat ) ; try { dateFormatter . parse ( s ) ; return true ; } catch ( ParseException e ) { // Exception noted so can be ignored .
e = null ; return false ; }


signature:
public class Validation { /** * Checks that a string is a time in the format specified by timeFormat .
 * @ param s The string to check for being a time .
 * @ return True if the string is a time . */
public static boolean isTime ( String s ) { } }

implementation:
// Build a time formatter using the format specified by timeFormat
DateFormat dateFormatter = new SimpleDateFormat ( timeFormat ) ; try { dateFormatter . parse ( s ) ; return true ; } catch ( ParseException e ) { // Exception noted so can be ignored .
e = null ; return false ; }


signature:
public class Validation { /** * Checks that a string is a datetime in the format specified by dateTimeFormat .
 * @ param s The string to check for being a timestamp .
 * @ return True if the string is a timestamp . */
public static boolean isDateTime ( String s ) { } }

implementation:
DateFormat dateFormatter = new SimpleDateFormat ( dateTimeFormat ) ; try { dateFormatter . parse ( s ) ; return true ; } catch ( ParseException e ) { // Exception noted so can be ignored .
e = null ; return false ; }


signature:
public class TokenSource { /** * Creates a token source on a string .
 * @ param stringToTokenize The string to tokenize .
 * @ return A token source . */
public static TokenSource getTokenSourceForString ( String stringToTokenize ) { } }

implementation: SimpleCharStream inputStream = new SimpleCharStream ( new StringReader ( stringToTokenize ) , 1 , 1 ) ; PrologParserTokenManager tokenManager = new PrologParserTokenManager ( inputStream ) ; return new TokenSource ( tokenManager ) ;


signature:
public class TokenSource { /** * Creates a token source on a file .
 * @ param file The file to tokenize .
 * @ return A token source .
 * @ throws FileNotFoundException If the file cannot be found . */
public static TokenSource getTokenSourceForFile ( File file ) throws FileNotFoundException { } }

implementation:
// Create a token source to load the model rules from .
Reader ins = new FileReader ( file ) ; SimpleCharStream inputStream = new SimpleCharStream ( ins , 1 , 1 ) ; PrologParserTokenManager tokenManager = new PrologParserTokenManager ( inputStream ) ; return new TokenSource ( tokenManager ) ;


signature:
public class TokenSource { /** * Creates a token source on an input stream .
 * @ param in The input stream to tokenize .
 * @ return A token source . */
public static Source getTokenSourceForInputStream ( InputStream in ) { } }

implementation: SimpleCharStream inputStream = new SimpleCharStream ( in , 1 , 1 ) ; PrologParserTokenManager tokenManager = new PrologParserTokenManager ( inputStream ) ; return new TokenSource ( tokenManager ) ;


signature:
public class TokenSource { /** * Retrieves and removes the head token , or < tt > null < / tt > if there are no more tokens .
 * @ return The head token , or < tt > null < / tt > if there are no more tokens . */
public Token poll ( ) { } }

implementation: if ( token . next == null ) { token . next = tokenManager . getNextToken ( ) ; } token = token . next ; return token ;


signature:
public class TokenSource { /** * Retrieves , but does not remove , the head token , returning < tt > null < / tt > if there are no more tokens .
 * @ return The head token , returning < tt > null < / tt > if there are no more tokens . */
public Token peek ( ) { } }

implementation: if ( token . next == null ) { token . next = tokenManager . getNextToken ( ) ; } return token . next ;


signature:
public class OptimizeInstructions { /** * { @ inheritDoc } */
public void apply ( WAMInstruction next ) { } }

implementation:
shift ( next ) ; // Anonymous or singleton variable optimizations .
if ( ( UnifyVar == next . getMnemonic ( ) ) && isVoidVariable ( next ) ) { if ( state != State . UVE ) { voidCount = 0 ; } discard ( ( voidCount == 0 ) ? 1 : 2 ) ; WAMInstruction unifyVoid = new WAMInstruction ( UnifyVoid , WAMInstruction . REG_ADDR , ( byte ) ++ voidCount ) ; shift ( unifyVoid ) ; state = State . UVE ; /* log . fine ( next + " - > " + unifyVoid ) ; */
} else if ( ( SetVar == next . getMnemonic ( ) ) && isVoidVariable ( next ) ) { if ( state != State . SVE ) { voidCount = 0 ; } discard ( ( voidCount == 0 ) ? 1 : 2 ) ; WAMInstruction setVoid = new WAMInstruction ( SetVoid , WAMInstruction . REG_ADDR , ( byte ) ++ voidCount ) ; shift ( setVoid ) ; state = State . SVE ; /* log . fine ( next + " - > " + setVoid ) ; */
} else if ( ( GetVar == next . getMnemonic ( ) ) && ( next . getMode1 ( ) == WAMInstruction . REG_ADDR ) && ( next . getReg1 ( ) == next . getReg2 ( ) ) ) { discard ( 1 ) ; /* log . fine ( next + " - > eliminated " ) ; */
state = State . NM ; } // Constant optimizations .
else if ( ( UnifyVar == next . getMnemonic ( ) ) && isConstant ( next ) && isNonArg ( next ) ) { discard ( 1 ) ; FunctorName functorName = interner . getDeinternedFunctorName ( next . getFunctorNameReg1 ( ) ) ; WAMInstruction unifyConst = new WAMInstruction ( UnifyConstant , functorName ) ; shift ( unifyConst ) ; flush ( ) ; state = State . NM ; /* log . fine ( next + " - > " + unifyConst ) ; */
} else if ( ( GetStruc == next . getMnemonic ( ) ) && isConstant ( next ) && isNonArg ( next ) ) { discard ( 1 ) ; state = State . NM ; /* log . fine ( next + " - > eliminated " ) ; */
} else if ( ( GetStruc == next . getMnemonic ( ) ) && isConstant ( next ) && ! isNonArg ( next ) ) { discard ( 1 ) ; WAMInstruction getConst = new WAMInstruction ( GetConstant , next . getMode1 ( ) , next . getReg1 ( ) , next . getFn ( ) ) ; shift ( getConst ) ; flush ( ) ; state = State . NM ; /* log . fine ( next + " - > " + getConst ) ; */
} else if ( ( PutStruc == next . getMnemonic ( ) ) && isConstant ( next ) && isNonArg ( next ) ) { discard ( 1 ) ; state = State . NM ; /* log . fine ( next + " - > eliminated " ) ; */
} else if ( ( PutStruc == next . getMnemonic ( ) ) && isConstant ( next ) && ! isNonArg ( next ) ) { discard ( 1 ) ; WAMInstruction putConst = new WAMInstruction ( PutConstant , next . getMode1 ( ) , next . getReg1 ( ) , next . getFn ( ) ) ; shift ( putConst ) ; state = State . NM ; /* log . fine ( next + " - > " + putConst ) ; */
} else if ( ( SetVal == next . getMnemonic ( ) ) && isConstant ( next ) && isNonArg ( next ) ) { discard ( 1 ) ; FunctorName functorName = interner . getDeinternedFunctorName ( next . getFunctorNameReg1 ( ) ) ; WAMInstruction setConst = new WAMInstruction ( SetConstant , functorName ) ; shift ( setConst ) ; flush ( ) ; state = State . NM ; /* log . fine ( next + " - > " + setConst ) ; */
} // List optimizations .
else if ( ( GetStruc == next . getMnemonic ( ) ) && ( "cons" . equals ( next . getFn ( ) . getName ( ) ) && ( next . getFn ( ) . getArity ( ) == 2 ) ) ) { discard ( 1 ) ; WAMInstruction getList = new WAMInstruction ( GetList , next . getMode1 ( ) , next . getReg1 ( ) ) ; shift ( getList ) ; state = State . NM ; /* log . fine ( next + " - > " + getList ) ; */
} else if ( ( PutStruc == next . getMnemonic ( ) ) && ( "cons" . equals ( next . getFn ( ) . getName ( ) ) && ( next . getFn ( ) . getArity ( ) == 2 ) ) ) { discard ( 1 ) ; WAMInstruction putList = new WAMInstruction ( PutList , next . getMode1 ( ) , next . getReg1 ( ) ) ; shift ( putList ) ; state = State . NM ; /* log . fine ( next + " - > " + putList ) ; */
} // Default .
else { state = State . NM ; flush ( ) ; }


signature:
public class OptimizeInstructions { /** * Checks if the term argument to an instruction was a constant .
 * @ param instruction The instruction to test .
 * @ return < tt > true < / tt > iff the term argument to an instruction was a constant . < tt > false < / tt > will be returned if
 * this information was not recorded , and cannot be determined . */
public boolean isConstant ( WAMInstruction instruction ) { } }

implementation: Integer name = instruction . getFunctorNameReg1 ( ) ; if ( name != null ) { FunctorName functorName = interner . getDeinternedFunctorName ( name ) ; if ( functorName . getArity ( ) == 0 ) { return true ; } } return false ;


signature:
public class OptimizeInstructions { /** * Checks if the term argument to an instruction was a singleton , non - argument position variable . The variable must
 * also be non - permanent to ensure that singleton variables in queries are created .
 * @ param instruction The instruction to test .
 * @ return < tt > true < / tt > iff the term argument to the instruction was a singleton , non - argument position variable . */
private boolean isVoidVariable ( WAMInstruction instruction ) { } }

implementation: SymbolKey symbolKey = instruction . getSymbolKeyReg1 ( ) ; if ( symbolKey != null ) { Integer count = ( Integer ) symbolTable . get ( symbolKey , SymbolTableKeys . SYMKEY_VAR_OCCURRENCE_COUNT ) ; Boolean nonArgPositionOnly = ( Boolean ) symbolTable . get ( symbolKey , SymbolTableKeys . SYMKEY_VAR_NON_ARG ) ; Integer allocation = ( Integer ) symbolTable . get ( symbolKey , SymbolTableKeys . SYMKEY_ALLOCATION ) ; boolean singleton = ( count != null ) && count . equals ( 1 ) ; boolean nonArgPosition = ( nonArgPositionOnly != null ) && TRUE . equals ( nonArgPositionOnly ) ; boolean permanent = ( allocation != null ) && ( ( byte ) ( ( allocation & 0xff00 ) >> 8 ) == WAMInstruction . STACK_ADDR ) ; if ( singleton && nonArgPosition && ! permanent ) { return true ; } } return false ;


signature:
public class OptimizeInstructions { /** * Checks if the term argument to an instruction was in a non - argument position .
 * @ param instruction The instruction to test .
 * @ return < tt > true < / tt > iff the term argument to an instruction was in a non - argument position . < tt > false < / tt > will
 * be returned if this information was not recorded , and cannot be determined . */
private boolean isNonArg ( WAMInstruction instruction ) { } }

implementation: SymbolKey symbolKey = instruction . getSymbolKeyReg1 ( ) ; if ( symbolKey != null ) { Boolean nonArgPositionOnly = ( Boolean ) symbolTable . get ( symbolKey , SymbolTableKeys . SYMKEY_FUNCTOR_NON_ARG ) ; if ( TRUE . equals ( nonArgPositionOnly ) ) { return true ; } } return false ;


signature:
public class LojixTermWriter { /** * { @ inheritDoc } */
protected TermBuilder < com . thesett . aima . logic . fol . Term > createCompoundBuilder ( ) { } }

implementation: return new LojixTermBuilder ( interner ) ;


signature:
public class EnhancedTextTableGridRenderer { /** * Renders the table . */
public void renderTable ( ) { } }

implementation:
for ( int i = 0 ; i < tableModel . getRowCount ( ) ; i ++ ) { int colOffset = 0 ; for ( int j = 0 ; j < tableModel . getColumnCount ( ) ; j ++ ) { String valueToPrint = tableModel . get ( j , i ) ; valueToPrint = ( valueToPrint == null ) ? "" : valueToPrint ; gridModel . insert ( valueToPrint , colOffset , i ) ; AttributeSet attributes = tableModel . getAttributeAt ( j , i ) ; int columnSize = tableModel . getMaxColumnSize ( j ) ; if ( attributes != null ) { for ( int k = 0 ; k < columnSize ; k ++ ) { gridModel . insertAttribute ( attributes , colOffset + k , i ) ; } } // Pad spaces up to the column width if the contents are shorter .
int spaces = columnSize - valueToPrint . length ( ) ; while ( spaces > 0 ) { gridModel . insert ( " " , colOffset + valueToPrint . length ( ) + spaces -- - 1 , i ) ; } // Shift to the next column .
colOffset += columnSize ; } }


signature:
public class Clause { /** * Provides an iterator over the child terms , if there are any . Only functors and clauses are compound , and build
 * across a list of child arguments .
 * @ param reverse Set , if the children should be presented in reverse order .
 * @ return The sub - terms of a compound term . */
public Iterator < Operator < Term > > getChildren ( boolean reverse ) { } }

implementation: if ( ( traverser != null ) && ( traverser instanceof ClauseTraverser ) ) { return ( ( ClauseTraverser ) traverser ) . traverse ( this , reverse ) ; } else { LinkedList < Operator < Term > > resultList = null ; if ( ! reverse ) { resultList = new LinkedList < Operator < Term > > ( ) ; } else { resultList = new StackQueue < Operator < Term > > ( ) ; } if ( head != null ) { resultList . add ( head ) ; } if ( body != null ) { for ( Term bodyTerm : body ) { resultList . add ( bodyTerm ) ; } } return resultList . iterator ( ) ; }


signature:
public class Clause { /** * Makes a clone of the term , converting its variables to refer directly to their storage cells .
 * @ return A copy of this term , with entirely independent variables to the term it was copied from . */
public Clause queryConversion ( ) { } }

implementation: Clause copy = ( Clause ) super . queryConversion ( ) ; if ( head != null ) { copy . head = head . queryConversion ( ) ; } if ( body != null ) { copy . body = new Functor [ body . length ] ; for ( int i = 0 ; i < body . length ; i ++ ) { copy . body [ i ] = body [ i ] . queryConversion ( ) ; } } return copy ;


signature:
public class Clause { /** * { @ inheritDoc } */
public void accept ( TermVisitor visitor ) { } }

implementation: if ( visitor instanceof ClauseVisitor ) { ( ( ClauseVisitor ) visitor ) . visit ( this ) ; } else { super . accept ( visitor ) ; }


signature:
public class Clause { /** * { @ inheritDoc } */
public Clause acceptTransformer ( TermTransformer transformer ) { } }

implementation: Clause result ; if ( transformer instanceof ClauseTransformer ) { result = ( ( ClauseTransformer ) transformer ) . transform ( this ) ; } else { result = ( Clause ) super . acceptTransformer ( transformer ) ; } if ( head != null ) { result . head = ( Functor ) head . acceptTransformer ( transformer ) ; } if ( body != null ) { for ( int i = 0 ; i < body . length ; i ++ ) { result . body [ i ] = ( Functor ) body [ i ] . acceptTransformer ( transformer ) ; } } return result ;


signature:
public class TraversableState { /** * Works out all the possible successors by applying all the operators returned by the
 * { @ link Traversable # validOperators } method .
 * @ param reverse When set , indicates that the successors should be presented in reverse order .
 * @ return An iterator over all the { @ link Successor } s that can be reached by applying valid operators to this
 * state . */
public Iterator < Successor < O > > successors ( boolean reverse ) { } }

implementation: return new Filterator < Operator < O > , Successor < O > > ( validOperators ( reverse ) , new Function < Operator < O > , Successor < O > > ( ) { public Successor < O > apply ( Operator operator ) { return new Successor < O > ( getChildStateForOperator ( operator ) , operator , costOf ( operator ) ) ; } } ) ;


signature:
public class Functor { /** * Reports whether or not this term is a ground term . Constants ( functors of arity zero ) and numbers are ground
 * terms , as are functors all of the arguments of which are ground term .
 * @ return < tt > true < / tt > if this functor is a ground term , < tt > false < / tt > othewise . */
public boolean isGround ( ) { } }

implementation: for ( int i = 0 ; i < arity ; i ++ ) { if ( ! arguments [ i ] . isGround ( ) ) { return false ; } } return true ;


signature:
public class Functor { /** * Gets the argument within the functor with the specified index .
 * @ param index The index to get the argument for .
 * @ return The argument . */
public Term getArgument ( int index ) { } }

implementation: if ( ( arguments == null ) || ( index > ( arguments . length - 1 ) ) ) { return null ; } else { return arguments [ index ] ; }


signature:
public class Functor { /** * Compares this term for structural equality with another . Two terms are structurally equal if they are the same
 * functor with the same arguments , or are the same unbound variable , or the bound values of the left or right
 * variable operands are structurally equal . Structural equality is a stronger equality than unification and unlike
 * unification it does not produce any variable bindings . Two unified terms will always be structurally equal .
 * @ param term The term to compare with this one for structural equality .
 * @ return < tt > true < / tt > if the two terms are structurally eqaul , < tt > false < / tt > otherwise . */
public boolean structuralEquals ( Term term ) { } }

implementation:
Term comparator = term . getValue ( ) ; if ( this == comparator ) { return true ; } if ( ( comparator == null ) || ! ( getClass ( ) . isAssignableFrom ( comparator . getClass ( ) ) ) ) { return false ; } Functor functor = ( Functor ) comparator ; if ( ( arity != functor . arity ) || ( name != functor . name ) ) { return false ; } // Check the arguments of this functor and the comparator for structural equality .
boolean passedArgCheck = true ; if ( arguments != null ) { for ( int i = 0 ; i < arguments . length ; i ++ ) { Term leftArg = arguments [ i ] ; Term rightArg = functor . arguments [ i ] ; if ( ! leftArg . structuralEquals ( rightArg ) ) { passedArgCheck = false ; break ; } } } return passedArgCheck ;


signature:
public class Functor { /** * Provides an iterator over the child terms , if there are any . Only functors are compound , and built across a list
 * of child arguments .
 * @ param reverse Set , if the children should be presented in reverse order .
 * @ return The sub - terms of a compound term . */
public Iterator < Operator < Term > > getChildren ( boolean reverse ) { } }

implementation: if ( ( traverser != null ) && ( traverser instanceof FunctorTraverser ) ) { return ( ( FunctorTraverser ) traverser ) . traverse ( this , reverse ) ; } else { if ( arguments == null ) { return new LinkedList < Operator < Term > > ( ) . iterator ( ) ; } else if ( ! reverse ) { return Arrays . asList ( ( Operator < Term > [ ] ) arguments ) . iterator ( ) ; } else { List < Operator < Term > > argList = new LinkedList < Operator < Term > > ( ) ; for ( int i = arity - 1 ; i >= 0 ; i -- ) { argList . add ( arguments [ i ] ) ; } return argList . iterator ( ) ; } }


signature:
public class Functor { /** * Makes a clone of the term , converting its variables to refer directly to their storage cells .
 * @ return A copy of this term , with entirely independent variables to the term it was copied from . */
public Functor queryConversion ( ) { } }

implementation:
/* log . fine ( " public Functor queryConversion ( ) : called ) " ) ; */
Functor copy = ( Functor ) super . queryConversion ( ) ; if ( arguments != null ) { copy . arguments = new Term [ arguments . length ] ; for ( int i = 0 ; i < arguments . length ; i ++ ) { copy . arguments [ i ] = arguments [ i ] . queryConversion ( ) ; } } return copy ;


signature:
public class Functor { /** * { @ inheritDoc } */
public void accept ( TermVisitor visitor ) { } }

implementation: if ( visitor instanceof FunctorVisitor ) { ( ( FunctorVisitor ) visitor ) . visit ( this ) ; } else { super . accept ( visitor ) ; }


signature:
public class Functor { /** * { @ inheritDoc } */
public Functor acceptTransformer ( TermTransformer transformer ) { } }

implementation: Functor result ; if ( transformer instanceof FunctorTransformer ) { result = ( ( FunctorTransformer ) transformer ) . transform ( this ) ; } else { result = ( Functor ) super . acceptTransformer ( transformer ) ; } if ( arguments != null ) { for ( int i = 0 ; i < arguments . length ; i ++ ) { result . arguments [ i ] = arguments [ i ] . acceptTransformer ( transformer ) ; } } return result ;


signature:
public class Functor { /** * Creates a string representation of this functors arguments , mostly used for debugging purposes .
 * @ return A string reprenestation of this functors arguments . */
protected String toStringArguments ( ) { } }

implementation: String result = "" ; if ( arity > 0 ) { result += "[ " ; for ( int i = 0 ; i < arity ; i ++ ) { Term nextArg = arguments [ i ] ; result += ( ( nextArg != null ) ? nextArg . toString ( ) : "<null>" ) + ( ( i < ( arity - 1 ) ) ? ", " : " " ) ; } result += " ]" ; } return result ;


signature:
public class SqlQueryEngine { /** * Execute a query to retrieve the summary . This do not have any group by element
 * @ param schemaDefinition The schema definition
 * @ param resultClazz The result object
 * @ param queryParameter The Query parameters object
 * @ return the summary object if exist . Otherwise throws an exception .
 * @ throws com . groupon . novie . internal . exception . NovieRuntimeException */
public < T extends MeasureAppender > T retrieveSummary ( SchemaDefinition schemaDefinition , Class < T > resultClazz , QueryParameter queryParameter ) throws NovieRuntimeException { } }

implementation: final SqlQueryBuilder < T > sqlQueryBuilder = new SqlQueryBuilder < T > ( schemaDefinition , resultClazz , queryParameter . partialCopy ( QueryParameterKind . GROUPS , QueryParameterKind . PAGE ) ) ; List < T > result = executeQuery ( sqlQueryBuilder ) ; if ( result . isEmpty ( ) ) { throw new NovieRuntimeException ( "Summary doesn't return any result." ) ; } if ( result . size ( ) > 1 ) { throw new NovieRuntimeException ( "Summary returns more than one result." ) ; } return result . get ( 0 ) ;


signature:
public class SqlQueryEngine { /** * Execute a query to retrieve the records .
 * @ param schemaDefinition The schema definition
 * @ param resultClazz The result object
 * @ param queryParameter The Query parameters object
 * @ return the summary object if exist . Otherwise throws an exception .
 * @ throws com . groupon . novie . internal . exception . NovieRuntimeException */
public < T extends MeasureAppender > List < T > retrieveRecords ( SchemaDefinition schemaDefinition , Class < T > resultClazz , QueryParameter queryParameter ) throws NovieRuntimeException { } }

implementation: final SqlQueryBuilder < T > sqlQueryBuilder = new SqlQueryBuilder < T > ( schemaDefinition , resultClazz , queryParameter ) ; return executeQuery ( sqlQueryBuilder ) ;


signature:
public class SqlQueryEngine { /** * Private methode called by the public ones to effectively run the query .
 * @ param sqlQueryBuilder the QueryBuilder used to run the query
 * @ return a list of resultObject
 * @ throws NovieRuntimeException */
private < T extends MeasureAppender > List < T > executeQuery ( final SqlQueryBuilder < T > sqlQueryBuilder ) throws NovieRuntimeException { } }

implementation: sqlQueryBuilder . buildQuery ( ) ; final String queryString = sqlQueryBuilder . getQueryString ( ) ; LOG . debug ( queryString ) ; long beforeQuery = System . currentTimeMillis ( ) ; List < T > returnValue = jdbcTemplate . query ( queryString , sqlQueryBuilder . getMapSqlParameterSource ( ) , sqlQueryBuilder ) ; if ( LOG . isInfoEnabled ( ) ) { LOG . info ( "SQL query successfully ran in " + ( System . currentTimeMillis ( ) - beforeQuery ) + "ms." ) ; } if ( LOG . isDebugEnabled ( ) ) { StringBuilder sb = new StringBuilder ( ) ; for ( Entry < String , Object > e : sqlQueryBuilder . getMapSqlParameterSource ( ) . getValues ( ) . entrySet ( ) ) { if ( sb . length ( ) > 0 ) { sb . append ( "," ) ; } sb . append ( e . getKey ( ) ) ; sb . append ( "=" ) ; sb . append ( e . getValue ( ) ) ; } sb . insert ( 0 , "Parameters [" ) ; sb . append ( "]" ) ; LOG . debug ( sb . toString ( ) ) ; } return returnValue ;


signature:
public class MachineMonitor { /** * { @ inheritDoc } */
public void onReset ( WAMResolvingMachineDPI dpi ) { } }

implementation: internalRegisters = new InternalRegisterBean ( 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , false ) ; internalRegisters . addPropertyChangeListener ( registerSetMonitor ) ; internalRegisters . addPropertyChangeListener ( breakpointMonitor ) ; internalRegisters . updateRegisters ( dpi . getInternalRegisters ( ) ) ; layoutRegisters = new InternalMemoryLayoutBean ( 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ) ; layoutRegisters . addPropertyChangeListener ( layoutMonitor ) ; layoutRegisters . updateRegisters ( dpi . getMemoryLayout ( ) ) ;


signature:
public class MachineMonitor { /** * { @ inheritDoc } */
public void onCodeUpdate ( WAMResolvingMachineDPI dpi , int start , int length ) { } }

implementation: ByteBuffer codeBuffer = dpi . getCodeBuffer ( start , length ) ; byteCodeMonitor . onCodeUpdate ( codeBuffer , start , length , dpi . getVariableAndFunctorInterner ( ) , dpi ) ;


signature:
public class MachineMonitor { /** * { @ inheritDoc } */
public void onExecute ( WAMResolvingMachineDPI dpi ) { } }

implementation: internalRegisters . updateRegisters ( dpi . getInternalRegisters ( ) ) ; layoutRegisters . updateRegisters ( dpi . getMemoryLayout ( ) ) ;


signature:
public class MachineMonitor { /** * { @ inheritDoc } */
public void onStep ( WAMResolvingMachineDPI dpi ) { } }

implementation: internalRegisters . updateRegisters ( dpi . getInternalRegisters ( ) ) ; layoutRegisters . updateRegisters ( dpi . getMemoryLayout ( ) ) ; breakpointMonitor . pause ( ) ;


signature:
public class WAMInstruction { /** * Disassembles the instructions from the specified byte buffer , starting at a given location ( ip ) . An interner for
 * the functor names encountered in the instruction buffer must also be supplied , in order to look up the functor
 * names by encoded value .
 * @ param start The start offset into the buffer to disassemble .
 * @ param length The length of data in the buffer to disassemble .
 * @ param codeBuf The code buffer .
 * @ param interner The interner to look up interned names with .
 * @ param codeView A view onto the machines code buffer .
 * @ return A list of instructions disassembles from the code buffer . */
public static SizeableList < WAMInstruction > disassemble ( int start , int length , ByteBuffer codeBuf , VariableAndFunctorInterner interner , WAMCodeView codeView ) { } }

implementation:
SizeableList < WAMInstruction > result = new SizeableLinkedList < WAMInstruction > ( ) ; int ip = start ; while ( ip < ( start + length ) ) { // Decode the instruction and its arguments .
byte iCode = codeBuf . get ( ip ) ; WAMInstruction instruction = new WAMInstruction ( iCode ) ; instruction . mnemonic . disassembleArguments ( instruction , ip , codeBuf , interner ) ; // Restore any label on the instruction .
Integer label = codeView . getNameForAddress ( ip ) ; if ( label != null ) { FunctorName name = interner . getDeinternedFunctorName ( label ) ; if ( name instanceof WAMLabel ) { instruction . label = ( WAMLabel ) name ; } } result . add ( instruction ) ; ip += instruction . mnemonic . length ( ) ; } return result ;


signature:
public class WAMInstruction { /** * Writes out the instruction plus arguments in the byte code format to the specified location within a code buffer .
 * @ param codeBuffer The code buffer to write to .
 * @ param machine The binary machine to write the code into .
 * @ throws LinkageException If required symbols to link to cannot be found in the binary machine . */
public void emmitCode ( ByteBuffer codeBuffer , WAMMachine machine ) throws LinkageException { } }

implementation: mnemonic . emmitCode ( this , codeBuffer , machine ) ;


signature:
public class JavaType { /** * { @ inheritDoc } */
public T getDefaultInstance ( ) { } }

implementation:
Object result ; // For basic Java types return the standard default value . For others , try the default constructor .
switch ( type ) { case BOOLEAN : result = DEFAULT_BOOLEAN ; break ; case CHARACTER : result = DEFAULT_CHARACTER ; break ; case BYTE : result = DEFAULT_BYTE ; break ; case SHORT : result = DEFAULT_SHORT ; break ; case INTEGER : result = DEFAULT_INTEGER ; break ; case LONG : result = DEFAULT_LONG ; break ; case FLOAT : result = DEFAULT_FLOAT ; break ; case DOUBLE : result = DEFAULT_DOUBLE ; break ; case OTHER : default : try { result = underlyingClass . newInstance ( ) ; } catch ( InstantiationException e ) { throw new IllegalStateException ( e ) ; } catch ( IllegalAccessException e ) { throw new IllegalStateException ( e ) ; } break ; } return ( T ) result ;


signature:
public class JavaType { /** * { @ inheritDoc } */
public T getRandomInstance ( ) throws RandomInstanceNotSupportedException { } }

implementation:
Object result = null ; // For basic Java types return the standard default value . For others , try the default constructor .
switch ( type ) { case BOOLEAN : result = RANDOM . nextBoolean ( ) ; break ; case CHARACTER : result = ( char ) RANDOM . nextInt ( ) ; break ; case BYTE : result = ( byte ) RANDOM . nextInt ( ) ; break ; case SHORT : result = ( short ) RANDOM . nextInt ( ) ; break ; case INTEGER : result = RANDOM . nextInt ( ) ; break ; case LONG : result = RANDOM . nextLong ( ) ; break ; case FLOAT : result = RANDOM . nextFloat ( ) ; break ; case DOUBLE : result = RANDOM . nextDouble ( ) ; break ; case OTHER : default : if ( String . class . equals ( underlyingClass ) ) { byte [ ] bytes = new byte [ 6 ] ; RANDOM . nextBytes ( bytes ) ; result = new String ( bytes ) ; } break ; } if ( result != null ) { return ( T ) result ; } else { throw new RandomInstanceNotSupportedException ( "Type does not support random instance creation." , null ) ; }


signature:
public class JavaType { /** * Sets the basic type of this type depending on the class .
 * @ param c The underlying class . */
private void setBasicType ( Class c ) { } }

implementation: if ( Boolean . class . equals ( c ) ) { type = BasicTypes . BOOLEAN ; } else if ( Character . class . equals ( c ) ) { type = BasicTypes . CHARACTER ; } else if ( Byte . class . equals ( c ) ) { type = BasicTypes . BYTE ; } else if ( Short . class . equals ( c ) ) { type = BasicTypes . SHORT ; } else if ( Integer . class . equals ( c ) ) { type = BasicTypes . INTEGER ; } else if ( Long . class . equals ( c ) ) { type = BasicTypes . LONG ; } else if ( Float . class . equals ( c ) ) { type = BasicTypes . FLOAT ; } else if ( Double . class . equals ( c ) ) { type = BasicTypes . DOUBLE ; } else { type = BasicTypes . OTHER ; }


signature:
public class ResolutionEngine { /** * Consults an input stream , reading first order logic clauses from it , and inserting them into the resolvers
 * knowledge base .
 * @ param stream The input stream to consult .
 * @ throws SourceCodeException If any code read from the input stream fails to parse , compile or link . */
public void consultInputStream ( InputStream stream ) throws SourceCodeException { } }

implementation:
// Create a token source to read from the specified input stream .
Source < Token > tokenSource = TokenSource . getTokenSourceForInputStream ( stream ) ; getParser ( ) . setTokenSource ( tokenSource ) ; // Consult the type checking rules and add them to the knowledge base .
while ( true ) { Sentence < S > sentence = getParser ( ) . parse ( ) ; if ( sentence == null ) { break ; } getCompiler ( ) . compile ( sentence ) ; }


signature:
public class ResolutionEngine { /** * Prints all of the logic variables in the results of a query .
 * @ param solution An iterable over the variables in the solution .
 * @ return All the variables printed as a string , one per line . */
public String printSolution ( Iterable < Variable > solution ) { } }

implementation: String result = "" ; for ( Variable var : solution ) { result += printVariableBinding ( var ) + "\n" ; } return result ;


signature:
public class ResolutionEngine { /** * Prints all of the logic variables in the results of a query .
 * @ param variables An iterable over the variables in the solution .
 * @ return All the variables printed as a string , one per line . */
public String printSolution ( Map < String , Variable > variables ) { } }

implementation: String result = "" ; for ( Map . Entry < String , Variable > entry : variables . entrySet ( ) ) { result += printVariableBinding ( entry . getValue ( ) ) + "\n" ; } return result ;


signature:
public class ResolutionEngine { /** * Prints a variable binding in the form ' Var = value ' .
 * @ param var The variable to print .
 * @ return The variable binding in the form ' Var = value ' . */
public String printVariableBinding ( Term var ) { } }

implementation: return var . toString ( getInterner ( ) , true , false ) + " = " + var . getValue ( ) . toString ( getInterner ( ) , false , true ) ;


signature:
public class ResolutionEngine { /** * Transforms an iterator over sets of variable bindings , resulting from a query , to an iterator over a map from the
 * string name of variables to their bindings , for the same sequence of query solutions .
 * @ param solutions The resolution solutions to convert to map form .
 * @ return An iterator over a map from the string name of variables to their bindings , for the solutions . */
public Iterable < Map < String , Variable > > expandResultSetToMap ( Iterator < Set < Variable > > solutions ) { } }

implementation: return new Filterator < Set < Variable > , Map < String , Variable > > ( solutions , new Function < Set < Variable > , Map < String , Variable > > ( ) { public Map < String , Variable > apply ( Set < Variable > variables ) { Map < String , Variable > results = new HashMap < String , Variable > ( ) ; for ( Variable var : variables ) { String varName = getInterner ( ) . getVariableName ( var . getName ( ) ) ; results . put ( varName , var ) ; } return results ; } } ) ;


signature:
public class ResolutionEngine { /** * { @ inheritDoc } */
public void setOperator ( String operatorName , int priority , OpSymbol . Associativity associativity ) { } }

implementation: parser . setOperator ( operatorName , priority , associativity ) ;


signature:
public class BaseBuiltIn { /** * { @ inheritDoc } */
public SizeableLinkedList < WAMInstruction > compileBodyArguments ( Functor expression , boolean isFirstBody , FunctorName clauseName , int bodyNumber ) { } }

implementation: return null ;


signature:
public class SocketReadThread { /** * A dedicated thread loop for reading the stream and sending incoming
 * packets to the appropriate router . */
public void run ( ) { } }

implementation:
try { readStream ( ) ; } catch ( EOFException eof ) { // Normal disconnect
} catch ( SocketException se ) { // Do nothing if the exception occured while shutting down the
// component otherwise
// log the error and try to establish a new connection
if ( ! shutdown ) { component . getManager ( ) . getLog ( ) . error ( se ) ; component . connectionLost ( ) ; } } catch ( XmlPullParserException ie ) { component . getManager ( ) . getLog ( ) . error ( ie ) ; } catch ( Exception e ) { component . getManager ( ) . getLog ( ) . warn ( e ) ; }


signature:
public class SocketReadThread { /** * Read the incoming stream until it ends . */
private void readStream ( ) throws Exception { } }

implementation:
while ( ! shutdown ) { Element doc = reader . parseDocument ( ) . getRootElement ( ) ; if ( doc == null ) { // Stop reading the stream since the server has sent an end of
// stream element and
// probably closed the connection
return ; } Packet packet ; String tag = doc . getName ( ) ; if ( "message" . equals ( tag ) ) { packet = new Message ( doc ) ; } else if ( "presence" . equals ( tag ) ) { packet = new Presence ( doc ) ; } else if ( "iq" . equals ( tag ) ) { packet = getIQ ( doc ) ; } else { throw new XmlPullParserException ( "Unknown packet type was read: " + tag ) ; } // Request the component to process the received packet
component . processPacket ( packet ) ; }


signature:
public class Type1UUID { /** * Initializer for type 1 UUIDs . Creates random generator and genenerates
 * the node portion of the UUID using the IP address . */
private static synchronized void initializeForType1 ( ) { } }

implementation:
if ( type1Initialized == true ) { return ; } // note that secure random is very slow the first time
// it is used ; consider switching to a standard random
RANDOM = new SecureRandom ( ) ; _seq = ( short ) RANDOM . nextInt ( MAX_14BIT ) ; byte [ ] ip = null ; try { ip = InetAddress . getLocalHost ( ) . getAddress ( ) ; } catch ( IOException ioe ) { throw new NestableRuntimeException ( ioe ) ; } IP = new byte [ 6 ] ; RANDOM . nextBytes ( IP ) ; System . arraycopy ( ip , 0 , IP , 2 , ip . length ) ; type1Initialized = true ;


signature:
public class Type1UUID { /** * Creates a type 1 UUID */
public static byte [ ] next ( ) { } }

implementation:
if ( type1Initialized == false ) { initializeForType1 ( ) ; } // set ip addr
byte [ ] uuid = new byte [ 16 ] ; System . arraycopy ( IP , 0 , uuid , 10 , IP . length ) ; // Set time info . Have to do this processing within a synchronized
// block because of the statics . . .
long now = 0 ; synchronized ( Type1UUID . class ) { // Get the time to use for this uuid . This method has the side
// effect of modifying the clock sequence , as well .
now = getTime ( ) ; // Insert the resulting clock sequence into the uuid
uuid [ IDX_TIME_SEQ ] = ( byte ) ( ( _seq & 0x3F00 ) >>> 8 ) ; uuid [ IDX_VARIATION ] |= 0x80 ; uuid [ IDX_TIME_SEQ + 1 ] = ( byte ) ( _seq & 0xFF ) ; } // have to break up time because bytes are spread through uuid
byte [ ] timeBytes = toBytes ( now ) ; // Copy time low
System . arraycopy ( timeBytes , TS_TIME_LO_IDX , uuid , IDX_TIME_LO , TS_TIME_LO_LEN ) ; // Copy time mid
System . arraycopy ( timeBytes , TS_TIME_MID_IDX , uuid , IDX_TIME_MID , TS_TIME_MID_LEN ) ; // Copy time hi
System . arraycopy ( timeBytes , TS_TIME_HI_IDX , uuid , IDX_TIME_HI , TS_TIME_HI_LEN ) ; // Set version ( time - based )
uuid [ IDX_TYPE ] |= TYPE_TIME_BASED ; // 0001 0000
return uuid ;


signature:
public class Type1UUID { /** * package - visibility for testing */
static long getTime ( ) { } }

implementation: if ( RANDOM == null ) initializeForType1 ( ) ; long newTime = getUUIDTime ( ) ; if ( newTime <= _lastMillis ) { incrementSequence ( ) ; newTime = getUUIDTime ( ) ; } _lastMillis = newTime ; return newTime ;


signature:
public class Type1UUID { /** * Gets the appropriately modified timestamep for the UUID . Must be called
 * from a synchronized block .
 * @ return long timestamp in 100ns intervals since the Gregorian change
 * offset */
private static long getUUIDTime ( ) { } }

implementation:
if ( _currentMillis != System . currentTimeMillis ( ) ) { _currentMillis = System . currentTimeMillis ( ) ; _counter = 0 ; // reset counter
} // check to see if we have created too many uuid ' s for this timestamp
if ( _counter + 1 >= MILLI_MULT ) { // Original algorithm threw exception . Seemed like overkill .
// Let ' s just increment the timestamp instead and start over . . .
_currentMillis ++ ; _counter = 0 ; } // calculate time as current millis plus offset times 100 ns ticks
long currentTime = ( _currentMillis + GREG_OFFSET ) * MILLI_MULT ; // return the uuid time plus the artificial tick counter incremented
return currentTime + _counter ++ ;


signature:
public class Player { /** * stops the playing / indicates that the playing stopped .
 * this method has no effect if runsInPlay is enabled in the constructor . < br > */
public void stopMusicPlayback ( ) { } }

implementation: if ( runsInPlay || ! isPlaying ) return ; lock . lock ( ) ; try { if ( blockRequest != null ) blockRequest . signal ( ) ; } finally { lock . unlock ( ) ; } isPlaying = false ; stopSound ( ) ; endedSound ( ) ; rollBackToDefault ( ) ; super . stop ( ) ;


signature:
public class Player { /** * checks if the trackInfo is an update and fires the appropriate Event . This method should not be called
 * without an active playlist , or an NullPointerException will be thrown .
 * this method : < br >
 * - fires nothing if the trackInfo equals the current trackInfo . < br >
 * - fires an trackInfoUpdate if the trackInfo contains information not found in the current . < br > */
@ SuppressWarnings ( "unused" ) public void updateCurrentTrackInfo ( TrackInfo trackInfo ) { } }

implementation: if ( playlist . getCurrent ( ) . equals ( trackInfo ) || playlist . getCurrent ( ) . isNew ( trackInfo ) ) return ; this . playlist = playlist . update ( playlist . getCurrent ( ) , trackInfo ) ; trackInfoUpdate ( playlist , trackInfo ) ;


signature:
public class Player { /** * call this method if the trackInfo object in the playlist was updated . Only the trackinfo object will be sent via
 * Event
 * @ param playlist the playlist
 * @ param info the new trackInfo object */
@ SuppressWarnings ( "unused" ) public void trackInfoUpdate ( Playlist playlist , TrackInfo info ) { } }

implementation: this . playlist = playlist ; updatePlayInfo ( info ) ;


signature:
public class Player { /** * fires an update event which notifies that parameters have changed
 * @ param volume the optional volume */
@ Override public void updatePlayInfo ( Volume volume ) { } }

implementation: if ( this . volume . equals ( volume ) ) return ; this . volume = volume ; MusicHelper . super . updatePlayInfo ( volume ) ;


signature:
public class Player { /** * updates the Info about the current song
 * @ param playlist the playlist , or null
 * @ param progress the progress , or null
 * @ param volume the volume , or null */
@ SuppressWarnings ( "unused" ) public void updatePlayInfo ( Playlist playlist , Progress progress , Volume volume ) { } }

implementation: if ( playlist != null ) this . playlist = playlist ; if ( progress != null ) this . progress = progress ; if ( volume != null ) this . volume = volume ; updatePlayInfo ( playlist , progress , null , volume ) ;


signature:
public class Player { /** * fires an update event which notifies that parameters have changed
 * @ param playlist the optional playlist
 * @ param progress the optional progress
 * @ param trackInfo the optional trackInfo
 * @ param volume the optional volume */
@ Override public void updatePlayInfo ( Playlist playlist , Progress progress , TrackInfo trackInfo , Volume volume ) { } }

implementation: if ( playlist != null ) this . playlist = playlist ; if ( progress != null ) this . progress = progress ; if ( volume != null ) this . volume = volume ; MusicHelper . super . updatePlayInfo ( playlist , progress , null , volume ) ;


signature:
public class Player { /** * This method is called when an object wants to get a Resource .
 * Don ' t use the Resources provided as arguments , they are just the requests .
 * There is a timeout after 1 second .
 * @ param resources a list of resources without data
 * @ param event if an event caused the action , it gets passed . It can also be null .
 * @ return a list of resources with data */
@ Override public List < ResourceModel > provideResource ( List < ? extends ResourceModel > resources , Optional < EventModel > event ) { } }

implementation: return informationProvider . provideResource ( resources , event ) ;


signature:
public class Player { /** * method that uses the data from the OutputExtensions to generate a final output that will then be rendered .
 * @ param data the data generated
 * @ param eventModel the Event which caused the whole thing */
@ Override public void renderFinalOutput ( List < T > data , EventModel eventModel ) { } }

implementation: if ( StartMusicRequest . verify ( eventModel , capabilities , this , activators ) ) { if ( isOutputRunning ( ) ) { playerError ( PlayerError . ERROR_ALREADY_PLAYING , eventModel . getSource ( ) ) ; } else { handleEventRequest ( eventModel ) ; } } else if ( eventModel . getListResourceContainer ( ) . providesResource ( Collections . singletonList ( MusicUsageResource . ID ) ) ) { if ( isOutputRunning ( ) ) { eventModel . getListResourceContainer ( ) . provideResource ( MusicUsageResource . ID ) . forEach ( resourceModel -> playerError ( PlayerError . ERROR_ALREADY_PLAYING , resourceModel . getProvider ( ) ) ) ; } else { handleResourceRequest ( eventModel ) ; } } else { handleCommands ( eventModel ) ; }


signature:
public class Player { /** * handles the a request to start playing music via Resource
 * @ param eventModel the eventModel */
private void handleResourceRequest ( EventModel eventModel ) { } }

implementation:
if ( MusicUsageResource . isPermanent ( eventModel ) ) { ResourceModel resourceModel = eventModel . getListResourceContainer ( ) . provideResource ( MusicUsageResource . ID ) . stream ( ) . filter ( MusicUsageResource :: isPermanent ) . findAny ( ) . orElse ( null ) ; // should not happen
// a partially applied function which takes an Identification an returns an Optional StartMusicRequest
Function < Identification , Optional < StartMusicRequest > > getStartMusicRequest = own -> StartMusicRequest . createStartMusicRequest ( resourceModel . getProvider ( ) , own ) ; // if we have a trackInfo we create it with the trackInfo as a parameter
getStartMusicRequest = TrackInfoResource . getTrackInfo ( eventModel ) . map ( trackInfo -> ( Function < Identification , Optional < StartMusicRequest > > ) own -> StartMusicRequest . createStartMusicRequest ( resourceModel . getProvider ( ) , own , trackInfo ) ) . orElse ( getStartMusicRequest ) ; // if we have a trackInfo we create it with the playlist as a parameter
getStartMusicRequest = PlaylistResource . getPlaylist ( eventModel ) . map ( playlist -> ( Function < Identification , Optional < StartMusicRequest > > ) own -> StartMusicRequest . createStartMusicRequest ( resourceModel . getProvider ( ) , own , playlist ) ) . orElse ( getStartMusicRequest ) ; // composes a new Function which appends the Volume to the result
getStartMusicRequest = getStartMusicRequest . andThen ( VolumeResource . getVolume ( eventModel ) . flatMap ( volume -> IdentificationManagerM . getInstance ( ) . getIdentification ( this ) . map ( identification -> new VolumeResource ( identification , volume ) ) ) . map ( resource -> ( Function < Optional < StartMusicRequest > , Optional < StartMusicRequest > > ) opt -> opt . map ( event -> ( StartMusicRequest ) event . addResource ( resource ) ) ) . orElse ( Function . identity ( ) ) :: apply ) ; IdentificationManagerM . getInstance ( ) . getIdentification ( this ) . flatMap ( getStartMusicRequest :: apply ) . ifPresent ( this :: fire ) ; } else { play ( eventModel ) ; if ( ! runsInPlay ) { blockRequest = lock . newCondition ( ) ; lock . lock ( ) ; try { blockRequest . await ( 10 , TimeUnit . MINUTES ) ; } catch ( InterruptedException e ) { debug ( "interrupted" , e ) ; } finally { lock . unlock ( ) ; } } }


signature:
public class Player { /** * handles the commands encoded as Resources / EventIds
 * @ param eventModel the eventModel to check */
private void handleCommands ( EventModel eventModel ) { } }

implementation: Consumer < Runnable > checkOrCall = runnable -> { List < ResourceModel > resourceModels = eventModel . getListResourceContainer ( ) . provideResource ( SelectorResource . RESOURCE_ID ) ; if ( resourceModels . isEmpty ( ) ) { runnable . run ( ) ; } else { resourceModels . stream ( ) . map ( resourceModel -> resourceModel . getResource ( ) instanceof Identification ? ( ( Identification ) resourceModel . getResource ( ) ) : null ) . filter ( Objects :: nonNull ) . filter ( this :: isOwner ) . findAny ( ) . ifPresent ( id -> runnable . run ( ) ) ; } } ; if ( eventModel . containsDescriptor ( MuteEvent . ID ) ) { checkOrCall . accept ( this :: mute ) ; } if ( eventModel . containsDescriptor ( UnMuteEvent . ID ) ) { checkOrCall . accept ( this :: unMute ) ; } if ( eventModel . containsDescriptor ( StopEvent . ID ) ) { checkOrCall . accept ( this :: stopMusicPlayback ) ; } if ( StopMusic . verify ( eventModel , this ) ) { stopMusicPlayback ( ) ; } if ( PlayerCommand . verify ( eventModel , this ) ) { getCommandHandler ( ) . handleCommandResources ( eventModel ) ; }


signature:
public class Player { /** * handles the a request to start playing music via Event
 * @ param eventModel the StartMusicRequest */
private void handleEventRequest ( EventModel eventModel ) { } }

implementation:
playingThread = submit ( ( Runnable ) ( ) -> { // noinspection RedundantIfStatement
if ( runsInPlay ) { isRunning = false ; } else { isRunning = true ; } isPlaying = true ; fireStartMusicRequest ( eventModel ) ; } ) . thenRun ( ( ) -> play ( eventModel ) ) . thenRun ( ( ) -> { if ( runsInPlay ) { isRunning = false ; isPlaying = false ; endedSound ( ) ; } } ) ;


signature:
public class Player { /** * this method will be called to create and fire the StartMusicRequest
 * @ param eventModel the cause */
protected void fireStartMusicRequest ( EventModel eventModel ) { } }

implementation: Optional < Playlist > playlist = PlaylistResource . getPlaylist ( eventModel ) ; Optional < Progress > progress = ProgressResource . getProgress ( eventModel ) ; Optional < TrackInfo > trackInfo = TrackInfoResource . getTrackInfo ( eventModel ) ; Optional < Volume > volume = VolumeResource . getVolume ( eventModel ) ; startedSound ( playlist . orElse ( null ) , progress . orElse ( null ) , trackInfo . orElse ( null ) , volume . orElse ( null ) , isUsingJava ) ;


signature:
public class Player { /** * sets every information into its default state ( playlist , volume , etc . . . ) */
public void rollBackToDefault ( ) { } }

implementation: playlist = new Playlist ( new ArrayList < > ( ) ) ; volume = Volume . createVolume ( 50 ) . orElse ( null ) ; progress = new Progress ( 0 , 0 ) ; playbackState = PlaybackState . PLAY ; if ( playingThread != null ) playingThread . cancel ( true ) ; isRunning = false ; isPlaying = false ;


signature:
public class PacketReader { /** * Initializes the reader in order to be used . The reader is initialized
 * during the first connection and when reconnecting due to an abruptly
 * disconnection . */
protected void init ( ) { } }

implementation:
done = false ; connectionID = null ; readerThread = new Thread ( ) { public void run ( ) { parsePackets ( this ) ; } } ; readerThread . setName ( "Smack Packet Reader (" + connection . connectionCounterValue + ")" ) ; readerThread . setDaemon ( true ) ; // Create an executor to deliver incoming packets to listeners . We ' ll
// use a single
// thread with an unbounded queue .
listenerExecutor = Executors . newSingleThreadExecutor ( new ThreadFactory ( ) { public Thread newThread ( Runnable runnable ) { Thread thread = new Thread ( runnable , "Smack Listener Processor (" + connection . connectionCounterValue + ")" ) ; thread . setDaemon ( true ) ; return thread ; } } ) ; resetParser ( ) ;


signature:
public class PacketReader { /** * Starts the packet reader thread and returns once a connection to the
 * server has been established . A connection will be attempted for a maximum
 * of five seconds . An XMPPException will be thrown if the connection fails .
 * @ throws XMPPException
 * if the server fails to send an opening stream back for more
 * than five seconds . */
synchronized public void startup ( ) throws XMPPException { } }

implementation:
final List < Exception > errors = new LinkedList < Exception > ( ) ; AbstractConnectionListener connectionErrorListener = new AbstractConnectionListener ( ) { @ Override public void connectionClosedOnError ( Exception e ) { errors . add ( e ) ; } } ; connection . addConnectionListener ( connectionErrorListener ) ; readerThread . start ( ) ; // Wait for stream tag before returning . We ' ll wait a couple of seconds
// before
// giving up and throwing an error .
try { // A waiting thread may be woken up before the wait time or a notify
// ( although this is a rare thing ) . Therefore , we continue waiting
// until either a connectionID has been set ( and hence a notify was
// made ) or the total wait time has elapsed .
int waitTime = SmackConfiguration . getPacketReplyTimeout ( ) ; wait ( 3 * waitTime ) ; } catch ( InterruptedException ie ) { // Ignore .
} connection . removeConnectionListener ( connectionErrorListener ) ; if ( connectionID == null ) { throw new XMPPException ( "Connection failed. No response from server." ) ; } else if ( ! errors . isEmpty ( ) ) { throw new XMPPException ( errors . iterator ( ) . next ( ) ) ; } else { connection . connectionID = connectionID ; }


signature:
public class PacketReader { /** * Shuts the packet reader down . */
public void shutdown ( ) { } }

implementation:
// Notify connection listeners of the connection closing if done hasn ' t
// already been set .
if ( ! done ) { for ( ConnectionListener listener : connection . getConnectionListeners ( ) ) { try { listener . connectionClosed ( ) ; } catch ( Exception e ) { // Catch and print any exception so we can recover
// from a faulty listener and finish the shutdown process
LOGGER . log ( Level . ERROR , "Error in listener while closing connection" , e ) ; } } } done = true ; // Shut down the listener executor .
listenerExecutor . shutdown ( ) ;


signature:
public class PacketReader { /** * Resets the parser using the latest connection ' s reader . Reseting the
 * parser is necessary when the plain connection has been secured or when a
 * new opening stream element is going to be sent by the server . */
private void resetParser ( ) { } }

implementation: try { innerReader = new XPPPacketReader ( ) ; innerReader . setXPPFactory ( XmlPullParserFactory . newInstance ( ) ) ; innerReader . getXPPParser ( ) . setInput ( connection . reader ) ; reset = true ; } catch ( Exception xppe ) { LOGGER . log ( Level . WARN , "Error while resetting parser" , xppe ) ; }


signature:
public class PacketReader { /** * Parse top - level packets in order to process them further .
 * @ param thread
 * the thread that is being used by the reader to parse incoming
 * packets . */
private void parsePackets ( Thread thread ) { } }

implementation: try { while ( ! done ) { if ( reset ) { startStream ( ) ; LOGGER . debug ( "Started xmlstream..." ) ; reset = false ; continue ; } Element doc = innerReader . parseDocument ( ) . getRootElement ( ) ; if ( doc == null ) { connection . disconnect ( ) ; LOGGER . debug ( "End of xmlstream." ) ; continue ; } Packet packet = null ; LOGGER . debug ( "Processing packet " + doc . asXML ( ) ) ; packet = parseFromPlugins ( doc , packet ) ; if ( packet == null ) { packet = parseFromCore ( doc ) ; } if ( packet != null ) { processPacket ( packet ) ; } } } catch ( Exception e ) { if ( ! done && ! connection . isSocketClosed ( ) ) { connection . notifyConnectionError ( e ) ; if ( ! connection . isConnected ( ) ) { releaseConnectionIDLock ( ) ; } } }


signature:
public class PacketReader { /** * Processes a packet after it ' s been fully parsed by looping through the
 * installed packet collectors and listeners and letting them examine the
 * packet to see if they are a match with the filter .
 * @ param packet
 * the packet to process . */
private void processPacket ( Packet packet ) { } }

implementation:
if ( packet == null ) { return ; } // Loop through all collectors and notify the appropriate ones .
for ( PacketCollector collector : connection . getPacketCollectors ( ) ) { collector . processPacket ( packet ) ; } // Deliver the incoming packet to listeners .
listenerExecutor . submit ( new ListenerNotification ( packet ) ) ;


signature:
public class AbstractApplicationOption { /** * Sets the CLI option .
 * @ param option CLI option , only used if not null */
protected final void setCliOption ( Option option ) { } }

implementation: if ( option != null ) { this . cliOption = option ; } if ( this . cliOption . getDescription ( ) != null ) { this . descr = this . cliOption . getDescription ( ) ; } else { this . cliOption . setDescription ( this . descr ) ; }


signature:
public class ChatManager { /** * Creates a new chat and returns it .
 * @ param userJID
 * the user this chat is with .
 * @ param listener
 * the listener which will listen for new messages from this
 * chat .
 * @ return the created chat . */
public Chat createChat ( String userJID , MessageListener listener ) { } }

implementation: return createChat ( userJID , null , listener ) ;


signature:
public class ChatManager { /** * Try to get a matching chat for the given user JID , based on the
 * { @ link MatchMode } . < li > NONE - return null < li > SUPPLIED _ JID - match the
 * jid in the from field of the message exactly . < li > BARE _ JID - if not match
 * for from field , try the bare jid .
 * @ param userJID
 * jid in the from field of message .
 * @ return Matching chat , or null if no match found . */
private Chat getUserChat ( String userJID ) { } }

implementation: if ( matchMode == MatchMode . NONE ) { return null ; } Chat match = jidChats . get ( userJID ) ; if ( match == null && ( matchMode == MatchMode . BARE_JID ) ) { match = baseJidChats . get ( StringUtils . parseBareAddress ( userJID ) ) ; } return match ;


signature:
public class DNSUtil { /** * Returns a list of HostAddresses under which the specified XMPP server can
 * be reached at for server - to - server communication . A DNS lookup for a SRV
 * record in the form " _ xmpp - server . _ tcp . example . com " is attempted ,
 * according to section 14.4 of RFC 3920 . If that lookup fails , a lookup in
 * the older form of " _ jabber . _ tcp . example . com " is attempted since servers
 * that implement an older version of the protocol may be listed using that
 * notation . If that lookup fails as well , it ' s assumed that the XMPP server
 * lives at the host resolved by a DNS lookup at the specified domain on the
 * default port of 5269.
 * As an example , a lookup for " example . com " may return
 * " im . example . com : 5269 " .
 * @ param domain
 * the domain .
 * @ return List of HostAddress , which encompasses the hostname and port that
 * the XMPP server can be reached at for the specified domain . */
public static List < HostAddress > resolveXMPPServerDomain ( final String domain ) { } }

implementation: if ( dnsResolver == null ) { List < HostAddress > addresses = new ArrayList < HostAddress > ( 1 ) ; addresses . add ( new HostAddress ( domain , 5269 ) ) ; return addresses ; } return resolveDomain ( domain , 's' ) ;


signature:
public class InternalContent { /** * Convert a new content object to an internal version .
 * @ param contentManager
 * the content manager now managing this content object .
 * @ param readOnly sets this contentManager to be either read - only or not . */
void internalize ( ContentManagerImpl contentManager , boolean readOnly ) { } }

implementation: this . contentManager = contentManager ; updated = false ; newcontent = false ; this . readOnly = readOnly ;


signature:
public class InternalContent { /** * Reset the object back to its last saved state . */
public void reset ( Map < String , Object > updatedMap ) { } }

implementation: if ( ! readOnly ) { this . content = ImmutableMap . copyOf ( updatedMap ) ; updatedContent . clear ( ) ; updated = false ; LOGGER . debug ( "Reset to {} " , updatedMap ) ; }


signature:
public class InternalContent { /** * set a property , creating if it does not exist , overwriting if it does .
 * @ param key
 * the key for the property
 * @ param value
 * the value for the property in storage format created with
 * StorageContentUtils . toStore ( ) . Must not be null . */
public void setProperty ( String key , Object value ) { } }

implementation: if ( readOnly ) { return ; } if ( value == null ) { throw new IllegalArgumentException ( "value must not be null" ) ; } Object o = content . get ( key ) ; if ( ! value . equals ( o ) ) { updatedContent . put ( key , value ) ; updated = true ; } else if ( updatedContent . containsKey ( key ) && ! value . equals ( updatedContent . get ( key ) ) ) { updatedContent . put ( key , value ) ; updated = true ; }


signature:
public class OrFilter { /** * Adds a filter to the filter list for the OR operation . A packet will pass
 * the filter if any filter in the list accepts it .
 * @ param filter
 * a filter to add to the filter list . */
public void addFilter ( PacketFilter filter ) { } }

implementation:
if ( filter == null ) { throw new IllegalArgumentException ( "Parameter cannot be null." ) ; } // If there is no more room left in the filters array , expand it .
if ( size == filters . length ) { PacketFilter [ ] newFilters = new PacketFilter [ filters . length + 2 ] ; for ( int i = 0 ; i < filters . length ; i ++ ) { newFilters [ i ] = filters [ i ] ; } filters = newFilters ; } // Add the new filter to the array .
filters [ size ] = filter ; size ++ ;


signature:
public class ModificationRequest { /** * Process the request in a stream .
 * @ param request
 * @ throws IOException
 * @ throws FileUploadException
 * @ throws StorageClientException
 * @ throws AccessDeniedException */
public void processRequest ( HttpServletRequest request ) throws IOException , FileUploadException , StorageClientException , AccessDeniedException { } }

implementation:
boolean debug = LOGGER . isDebugEnabled ( ) ; if ( ServletFileUpload . isMultipartContent ( request ) ) { if ( debug ) { LOGGER . debug ( "Multipart POST " ) ; } feedback . add ( "Multipart Upload" ) ; ServletFileUpload upload = new ServletFileUpload ( ) ; FileItemIterator iterator = upload . getItemIterator ( request ) ; while ( iterator . hasNext ( ) ) { FileItemStream item = iterator . next ( ) ; if ( debug ) { LOGGER . debug ( "Got Item {}" , item ) ; } String name = item . getFieldName ( ) ; InputStream stream = item . openStream ( ) ; if ( item . isFormField ( ) ) { ParameterType pt = ParameterType . typeOfRequestParameter ( name ) ; String propertyName = RequestUtils . propertyName ( pt . getPropertyName ( name ) ) ; RequestUtils . accumulate ( stores . get ( pt ) , propertyName , RequestUtils . toValue ( name , Streams . asString ( stream ) ) ) ; feedback . add ( pt . feedback ( propertyName ) ) ; } else { if ( streamProcessor != null ) { feedback . addAll ( streamProcessor . processStream ( name , StorageClientUtils . getObjectName ( item . getName ( ) ) , item . getContentType ( ) , stream , this ) ) ; } } } if ( debug ) { LOGGER . debug ( "No More items " ) ; } } else { if ( debug ) { LOGGER . debug ( "Trad Post " ) ; } // use traditional unstreamed operations .
@ SuppressWarnings ( "unchecked" ) Map < String , String [ ] > parameters = request . getParameterMap ( ) ; if ( debug ) { LOGGER . debug ( "Traditional POST {} " , parameters ) ; } Set < Entry < String , String [ ] > > entries = parameters . entrySet ( ) ; for ( Entry < String , String [ ] > param : entries ) { String name = ( String ) param . getKey ( ) ; ParameterType pt = ParameterType . typeOfRequestParameter ( name ) ; String propertyName = RequestUtils . propertyName ( pt . getPropertyName ( name ) ) ; RequestUtils . accumulate ( stores . get ( pt ) , propertyName , RequestUtils . toValue ( name , param . getValue ( ) ) ) ; feedback . add ( pt . feedback ( propertyName ) ) ; } }


signature:
public class ModificationRequest { /** * Clear the current set of properties to add and remove . */
public void resetProperties ( ) { } }

implementation: for ( Entry < ParameterType , Map < String , Object > > e : stores . entrySet ( ) ) { e . getValue ( ) . clear ( ) ; }


signature:
public class Signature { /** * Calculate an RFC2104 compliant HMAC ( Hash - based Message Authentication Code )
 * @ param data
 * The data to be signed . This data is pushed through a hex converter in this
 * method , so there is no need to do this before generating the HMAC .
 * @ param key
 * The signing key .
 * @ return The Base64 - encoded RFC 2104 - compliant HMAC signature .
 * @ throws java . security . SignatureException
 * when signature generation fails */
public static String calculateRFC2104HMAC ( String data , String key ) throws java . security . SignatureException { } }

implementation:
if ( data == null ) { throw new IllegalArgumentException ( "String data == null" ) ; } if ( key == null ) { throw new IllegalArgumentException ( "String key == null" ) ; } try { // Get an hmac _ sha1 key from the raw key bytes
byte [ ] keyBytes = key . getBytes ( "UTF-8" ) ; SecretKeySpec signingKey = new SecretKeySpec ( keyBytes , HMAC_SHA1_ALGORITHM ) ; // Get an hmac _ sha1 Mac instance and initialize with the signing key
Mac mac = Mac . getInstance ( HMAC_SHA1_ALGORITHM ) ; mac . init ( signingKey ) ; // Compute the hmac on input data bytes
byte [ ] rawHmac = mac . doFinal ( data . getBytes ( "UTF-8" ) ) ; // Convert raw bytes to encoding
return Base64 . encodeBase64URLSafeString ( rawHmac ) ; } catch ( NoSuchAlgorithmException e ) { throw new SignatureException ( "Failed to generate HMAC : " + e . getMessage ( ) , e ) ; } catch ( InvalidKeyException e ) { throw new SignatureException ( "Failed to generate HMAC : " + e . getMessage ( ) , e ) ; } catch ( UnsupportedEncodingException e ) { throw new SignatureException ( "Failed to generate HMAC : " + e . getMessage ( ) , e ) ; }


signature:
public class BatchServlet { /** * Takes the original request and starts the batching .
 * @ param request
 * @ param response
 * @ throws IOException
 * @ throws ServletException */
@ SuppressWarnings ( "unchecked" ) protected void batchRequest ( HttpServletRequest request , HttpServletResponse response , boolean allowModify ) throws IOException , ServletException { } }

implementation: String json = request . getParameter ( REQUESTS_PARAMETER ) ; String template = request . getParameter ( REQUEST_TEMPLATE ) ; if ( template != null && template . length ( ) > 0 ) { if ( templateService . checkTemplateExists ( template ) ) { StringWriter processedTemplate = new StringWriter ( ) ; templateService . process ( request . getParameterMap ( ) , "UTF-8" , processedTemplate , template ) ; json = processedTemplate . toString ( ) ; } else { response . sendError ( HttpServletResponse . SC_BAD_REQUEST , "Template specified in request parameter t does not exist" ) ; } } batchProcessor . batchRequest ( request , response , json , allowModify ) ;


signature:
public class AclModification { /** * TODO : Unit test */
public static void addAcl ( boolean grant , Permission permssion , String key , List < AclModification > modifications ) { } }

implementation: if ( grant ) { key = AclModification . grantKey ( key ) ; } else { key = AclModification . denyKey ( key ) ; } modifications . add ( new AclModification ( key , permssion . getPermission ( ) , AclModification . Operation . OP_OR ) ) ;


signature:
public class AclModification { /** * TODO : Unit test */
public static void removeAcl ( boolean grant , Permission permssion , String key , List < AclModification > modifications ) { } }

implementation: if ( grant ) { key = AclModification . grantKey ( key ) ; } else { key = AclModification . denyKey ( key ) ; } modifications . add ( new AclModification ( key , ~ permssion . getPermission ( ) , AclModification . Operation . OP_AND ) ) ;


signature:
public class AclModification { /** * TODO : Unit test */
public static void filterAcl ( Map < String , Object > acl , boolean grant , Permission permission , boolean set , List < AclModification > modifications ) { } }

implementation:
int perm = permission . getPermission ( ) ; Operation op = Operation . OP_OR ; if ( ! set ) { perm = 0xffff ^ perm ; op = Operation . OP_AND ; } for ( Entry < String , Object > ace : acl . entrySet ( ) ) { String key = ace . getKey ( ) ; if ( AclModification . isGrant ( key ) == grant ) { // clear the bit if set .
modifications . add ( new AclModification ( key , perm , op ) ) ; } }


signature:
public class AclModification { /** * TODO : Unit test */
public static String getPrincipal ( String principalKey ) { } }

implementation: if ( principalKey == null ) { return principalKey ; } if ( principalKey . length ( ) <= GRANTED_MARKER . length ( ) ) { return null ; } if ( principalKey . endsWith ( GRANTED_MARKER ) ) { return principalKey . substring ( 0 , principalKey . length ( ) - GRANTED_MARKER . length ( ) ) ; } else if ( principalKey . endsWith ( DENIED_MARKER ) ) { return principalKey . substring ( 0 , principalKey . length ( ) - DENIED_MARKER . length ( ) ) ; } else { return null ; }


signature:
public class AclModification { /** * TODO : Unit test */
public static Permission [ ] listPermissions ( int perms ) { } }

implementation: List < Permission > permissions = Lists . newArrayList ( ) ; for ( Permission p : Permissions . PRIMARY_PERMISSIONS ) { if ( ( perms & p . getPermission ( ) ) == p . getPermission ( ) ) { permissions . add ( p ) ; } } return permissions . toArray ( new Permission [ permissions . size ( ) ] ) ;


signature:
public class SynchronizedTransactionalSortedBidiMap { /** * Factory method to create a synchronized map .
 * @ param map the map to decorate , must not be null
 * @ throws IllegalArgumentException if map is null */
public static < K , V > TransactionalSortedBidiMap < K , V > decorate ( TransactionalSortedBidiMap < K , V > map ) { } }

implementation: return new SynchronizedTransactionalSortedBidiMap < K , V > ( map ) ;


signature: public class SynchronizedTransactionalSortedBidiMap { public void commit ( ) { } }

implementation: SyncUtils . synchronizeWrite ( lock , new Callback < Object > ( ) { @ Override protected void doAction ( ) { getTransactionalSortedBidiMap ( ) . commit ( ) ; } } ) ;


signature:
public class PacketWriter { /** * Initializes the writer in order to be used . It is called at the first
 * connection and also is invoked if the connection is disconnected by an
 * error . */
protected void init ( ) { } }

implementation: this . writer = connection . writer ; done = false ; writerThread = new Thread ( ) { public void run ( ) { writePackets ( this ) ; } } ; writerThread . setName ( "Smack Packet Writer (" + connection . connectionCounterValue + ")" ) ; writerThread . setDaemon ( true ) ;


signature:
public class PacketWriter { /** * Sends the specified packet to the server .
 * @ param packet
 * the packet to send . */
public void sendPacket ( Packet packet ) { } }

implementation:
if ( ! done ) { // Invoke interceptors for the new packet that is about to be sent .
// Interceptors
// may modify the content of the packet .
connection . firePacketInterceptors ( packet ) ; try { queue . put ( packet ) ; } catch ( InterruptedException ie ) { LOGGER . log ( Level . ERROR , "Failed to queue packet to send to server: " + packet . toString ( ) , ie ) ; return ; } synchronized ( queue ) { queue . notifyAll ( ) ; } // Process packet writer listeners . Note that we ' re using the
// sending
// thread so it ' s expected that listeners are fast .
connection . firePacketSendingListeners ( packet ) ; }


signature:
public class PacketWriter { /** * Returns the next available packet from the queue for writing .
 * @ return the next packet for writing . */
private Packet nextPacket ( ) { } }

implementation:
Packet packet = null ; // Wait until there ' s a packet or we ' re done .
while ( ! done && ( packet = queue . poll ( ) ) == null ) { try { synchronized ( queue ) { queue . wait ( ) ; } } catch ( InterruptedException ie ) { // Do nothing
} } return packet ;


signature:
public class PacketWriter { /** * Sends to the server a new stream element . This operation may be requested
 * several times so we need to encapsulate the logic in one place . This
 * message will be sent while doing TLS , SASL and resource binding .
 * @ throws IOException
 * If an error occurs while sending the stanza to the server . */
void openStream ( ) throws IOException { } }

implementation: StringBuilder stream = new StringBuilder ( ) ; stream . append ( "<stream:stream" ) ; stream . append ( " to=\"" ) . append ( connection . getServiceName ( ) ) . append ( "\"" ) ; stream . append ( " xmlns=\"jabber:client\"" ) ; stream . append ( " xmlns:stream=\"http://etherx.jabber.org/streams\"" ) ; stream . append ( " version=\"1.0\">" ) ; writer . write ( stream . toString ( ) ) ; writer . flush ( ) ;


signature:
public class GoodwillAccessor { /** * Get the Goodwill schema associated to a schema name .
 * Typical invocation :
 * < pre >
 * try {
 * GoodwillSchema type = accessor . getSchema ( " test " ) . get ( ) ;
 * catch ( Exception e ) {
 * / / Connection exception ? Goodwill server down ?
 * < / pre >
 * @ param schemaName schema name to lookup
 * @ return a future on the Schema */
public Future < GoodwillSchema > getSchema ( final String schemaName ) { } }

implementation: try { return client . prepareGet ( String . format ( "%s/%s" , url , schemaName ) ) . addHeader ( "Accept" , "application/json" ) . execute ( new AsyncCompletionHandler < GoodwillSchema > ( ) { @ Override public GoodwillSchema onCompleted ( final Response response ) throws Exception { if ( response . getStatusCode ( ) != 200 ) { return null ; } final InputStream in = response . getResponseBodyAsStream ( ) ; try { return mapper . readValue ( in , GoodwillSchema . class ) ; } finally { closeStream ( in ) ; } } @ Override public void onThrowable ( final Throwable t ) { log . warn ( "Got exception looking up the schema" , t ) ; } } ) ; } catch ( IOException e ) { log . warn ( "Got exception looking up the schema" , e ) ; return null ; }


signature:
public class GoodwillAccessor { /** * Get all schemata .
 * Use schemata , instead of schemas , which is closer to the original σχήματα .
 * @ return a future on a list of Schema
 * @ see # getSchema ( String ) for an invocation example */
public Future < List < GoodwillSchema > > getSchemata ( ) { } }

implementation: try { return client . prepareGet ( url ) . addHeader ( "Accept" , "application/json" ) . execute ( new AsyncCompletionHandler < List < GoodwillSchema > > ( ) { @ Override public List < GoodwillSchema > onCompleted ( final Response response ) throws Exception { if ( response . getStatusCode ( ) != 200 ) { return null ; } InputStream in = response . getResponseBodyAsStream ( ) ; try { final HashMap < String , List < GoodwillSchema > > map = mapper . readValue ( in , new TypeReference < HashMap < String , List < GoodwillSchema > > > ( ) { } ) ; return map . get ( "types" ) ; } finally { closeStream ( in ) ; } } @ Override public void onThrowable ( final Throwable t ) { log . warn ( "Got exception looking up the schema list" , t ) ; } } ) ; } catch ( IOException e ) { log . warn ( "Got exception looking up the schema list" , e ) ; return null ; }


signature:
public class GoodwillAccessor { /** * note : if called from base - class constructor , couldn ' t sub - class ; hence just make static */
private static AsyncHttpClient createHttpClient ( ) { } }

implementation:
// Don ' t limit the number of connections per host
// See https : / / github . com / ning / async - http - client / issues / issue / 28
final AsyncHttpClientConfig . Builder builder = new AsyncHttpClientConfig . Builder ( ) ; builder . setMaximumConnectionsPerHost ( - 1 ) ; return new AsyncHttpClient ( builder . build ( ) ) ;


signature:
public class Event { /** * Creates a new Event Object
 * @ param type the Type of the Event , try to use the predefined Event types
 * @ param source the source of the Event , most likely a this reference .
 * @ return an Optional , that may be empty if type is null or empty or source is null */
public static Optional < Event > createEvent ( String type , Identification source ) { } }

implementation: try { return Optional . of ( new Event ( type , source , new ArrayList < > ( ) ) ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; }


signature:
public class Event { /** * Creates a new Event Object
 * @ param type the Type of the Event , try to use the predefined Event types
 * @ param source the source of the Event , most likely a this reference .
 * @ param descriptors the descriptors
 * @ return an Optional , that may be empty if type is null or empty or source is null */
public static Optional < Event > createEvent ( String type , Identification source , List < String > descriptors ) { } }

implementation: try { return Optional . of ( new Event ( type , source , descriptors ) ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; }


signature:
public class Event { /** * returns a List containing all the Descriptors and the type .
 * @ return a List containing the Descriptors */
@ Override public List < String > getAllInformations ( ) { } }

implementation: ArrayList < String > strings = new ArrayList < > ( descriptors ) ; strings . add ( type ) ; return strings ;


signature:
public class Event { /** * sets the Descriptors ( but not the Event - Type ) .
 * @ param descriptor a String describing the Event .
 * @ return the resulting Event ( which is the same instance ) */
public Event addDescriptor ( String descriptor ) { } }

implementation: List < String > newDescriptors = new ArrayList < > ( ) ; newDescriptors . addAll ( descriptors ) ; newDescriptors . add ( descriptor ) ; return new Event ( getType ( ) , getSource ( ) , newDescriptors ) ;


signature:
public class Event { /** * returns whether the event contains the specific descriptor .
 * this method also checks whether it matches the type .
 * @ param descriptor a String with the ID of the Descriptor
 * @ return boolean when the Event contains the descriptor , false when not . */
@ Override public boolean containsDescriptor ( String descriptor ) { } }

implementation: return descriptors . contains ( descriptor ) || type . equals ( descriptor ) ;


signature:
public class Event { /** * adds the Consumer to the specified EventLifeCycle .
 * In its current implementation the invocation of the Callback method is parallel , but the notificaton of the listners not .
 * @ param eventLifeCycle the EventLifeCycle to target
 * @ param cycleCallback the callback */
@ SuppressWarnings ( "unused" ) public Event addEventLifeCycleListener ( EventLifeCycle eventLifeCycle , Consumer < EventLifeCycle > cycleCallback ) { } }

implementation: lifeCycleListeners . compute ( eventLifeCycle , ( unused , list ) -> { if ( list == null ) list = new ArrayList < > ( ) ; list . add ( cycleCallback ) ; return list ; } ) ; return this ;


signature:
public class SimplePermanentSoundOutputPlugin { /** * Default implementation waits until a new Event has been received and then processes it .
 * This method is made to be overwritten as seen fit by the developer
 * @ return the recently added Event - instance to be processed by the outputPlugin
 * @ throws InterruptedException if interrupted while waiting */
@ Override public EventModel blockingQueueHandling ( ) throws InterruptedException { } }

implementation: EventModel eventModel = super . blockingQueueHandling ( ) ; if ( eventModel . containsDescriptor ( MuteEvent . ID ) ) { List < ResourceModel > resourceModels = eventModel . getListResourceContainer ( ) . provideResource ( SelectorResource . RESOURCE_ID ) ; if ( resourceModels . isEmpty ( ) ) { mute ( ) ; } else { resourceModels . stream ( ) . map ( resourceModel -> resourceModel . getResource ( ) instanceof Identification ? ( ( Identification ) resourceModel . getResource ( ) ) : null ) . filter ( Objects :: nonNull ) . filter ( this :: isOwner ) . findAny ( ) . ifPresent ( id -> mute ( ) ) ; } } if ( eventModel . containsDescriptor ( UnMuteEvent . ID ) ) { List < ResourceModel > resourceModels = eventModel . getListResourceContainer ( ) . provideResource ( SelectorResource . RESOURCE_ID ) ; if ( resourceModels . isEmpty ( ) ) { unMute ( ) ; } else { resourceModels . stream ( ) . map ( resourceModel -> resourceModel . getResource ( ) instanceof Identification ? ( ( Identification ) resourceModel . getResource ( ) ) : null ) . filter ( Objects :: nonNull ) . filter ( this :: isOwner ) . findAny ( ) . ifPresent ( id -> unMute ( ) ) ; } } if ( eventModel . containsDescriptor ( StopEvent . ID ) ) { List < ResourceModel > resourceModels = eventModel . getListResourceContainer ( ) . provideResource ( SelectorResource . RESOURCE_ID ) ; if ( resourceModels . isEmpty ( ) ) { stopSound ( ) ; } else { resourceModels . stream ( ) . map ( resourceModel -> resourceModel . getResource ( ) instanceof Identification ? ( ( Identification ) resourceModel . getResource ( ) ) : null ) . filter ( Objects :: nonNull ) . filter ( this :: isOwner ) . findAny ( ) . ifPresent ( id -> stopSound ( ) ) ; } } return eventModel ;


signature:
public class SimplePermanentSoundOutputPlugin { /** * use this method to start playing sound ( only plays sound if it is not already playing )
 * @ param function the function which plays the sound
 * @ return the Future */
public Optional < CompletableFuture < Void > > startPlaying ( Runnable function ) { } }

implementation: if ( isCurrentlyPlayingSound ) return Optional . empty ( ) ; CompletableFuture < Void > voidCompletableFuture = submit ( ( Runnable ) ( ) -> startedSound ( isUsingJava ) ) . thenRun ( ( ) -> { try { isCurrentlyPlayingSound = true ; function . run ( ) ; } finally { submit ( ( Runnable ) this :: endedSound ) ; isCurrentlyPlayingSound = false ; } } ) ; return Optional . of ( voidCompletableFuture ) ;


signature:
public class TaskEngine { /** * Shuts down the task engine service . */
public void shutdown ( ) { } }

implementation: if ( executor != null ) { executor . shutdownNow ( ) ; executor = null ; } if ( timer != null ) { timer . cancel ( ) ; timer = null ; }


signature:
public class SynchronizedFilterableCollection { /** * Factory method to create a synchronized map .
 * @ param map the map to decorate , must not be null
 * @ throws IllegalArgumentException if map is null */
public static < E > FilterableCollection < E > decorate ( FilterableCollection < E > collection ) { } }

implementation: return new SynchronizedFilterableCollection < E > ( collection ) ;


signature: public class SynchronizedFilterableCollection { public FilterableCollection < E > filteredCollection ( final Filter < ? super E > filter ) { } }

implementation: return SyncUtils . synchronizeRead ( lock , new Callback < FilterableCollection < E > > ( ) { @ Override protected void doAction ( ) { FilterableCollection < E > _col = getFilterableCollection ( ) . filteredCollection ( filter ) ; _return ( new SynchronizedFilterableCollection < E > ( _col , lock ) ) ; } } ) ;


signature:
public class Files { /** * Identical File Contents
 * < p > Uses
 * < a href = " http : / / en . wikipedia . org / wiki / Memory - mapped _ file " > Memory Mapped Files < / a >
 * for fast comparison of large files . This is about 4 times faster than calling < / p > < pre >
 * < a href = " http : / / commons . apache . org / proper / commons - io / apidocs / org / apache / commons / io / FileUtils . html # contentEquals % 28java . io . File , % 20java . io . File % 29 " > org . apache . commons . io . FileUtils . contentEquals ( File file1 , File file2 ) < / a > < / pre >
 * < p > with identical 4
 * < a href = " http : / / en . wikipedia . org / wiki / Gibibyte " > GiB < / a >
 * files . Performance may suffer slightly for smaller files .
 * A future version may be optimized for smaller files too . < / p >
 * < p > Useful for checking if media files , such as music and video ,
 * have identical or duplicate content . Video files can easily
 * be over 4 GiB in size . Technically this method will compare
 * files as large as the file system supports . < / p >
 * < p > Performance is about 16 seconds for two 4 GiB files with
 * identical content on an Intel Xeon 5580 at 3.2 GHz using a
 * file system on a LSI MegaRAID SAS 9266-8i . < / p >
 * @ param file1 1st file to be compared
 * @ param file2 2nd file to be compared
 * @ return true when both files have identical contents
 * @ throws IllegalArgumentException if the arguments are not files .
 * @ throws IOException if there is a problem with File I / O
 * @ throws RuntimeException if there was a problem unmapping the
 * buffers or closing the channels , which may leave one or more
 * files locked for read . */
public static Boolean contentEquals ( Path file1 , Path file2 ) throws IOException { } }

implementation:
if ( ! java . nio . file . Files . isRegularFile ( file1 ) ) throw new IllegalArgumentException ( file1 + "is not a regular file" ) ; if ( ! java . nio . file . Files . isRegularFile ( file2 ) ) throw new IllegalArgumentException ( file2 + "is not a regular file" ) ; FileChannel channel1 = null ; FileChannel channel2 = null ; MappedByteBuffer buffer1 = null ; MappedByteBuffer buffer2 = null ; try { long size1 = java . nio . file . Files . size ( file1 ) ; long size2 = java . nio . file . Files . size ( file2 ) ; if ( size1 != size2 ) return false ; long position = 0 ; long length = Math . min ( Integer . MAX_VALUE , size1 - position ) ; channel1 = FileChannel . open ( file1 ) ; channel2 = FileChannel . open ( file2 ) ; // Cannot map files larger than Integer . MAX _ VALUE ,
// so we have to do it in pieces .
while ( length > 0 ) { buffer1 = channel1 . map ( MapMode . READ_ONLY , position , length ) ; buffer2 = channel2 . map ( MapMode . READ_ONLY , position , length ) ; // if ( ! buffer1 . equals ( buffer2 ) ) return false ;
// The line above is much slower than the line below .
// It should not be , but it is , possibly because it is
// loading the entire buffer into memory before comparing
// the contents . See the corresponding unit test . EK
for ( int i = 0 ; i < length ; i ++ ) if ( buffer1 . get ( ) != buffer2 . get ( ) ) return false ; position += length ; length = Math . min ( Integer . MAX_VALUE , size1 - position ) ; cleanDirectByteBuffer ( buffer1 ) ; buffer1 = null ; cleanDirectByteBuffer ( buffer2 ) ; buffer2 = null ; } } finally { // Is is important to clean up so we do not hold any
// file locks , in case the caller wants to do something
// else with the files .
// In terms of functional programming , holding a lock after
// returning to the caller would be an unwelcome side - effect .
cleanDirectByteBuffer ( buffer1 ) ; cleanDirectByteBuffer ( buffer2 ) ; if ( channel1 != null ) try { channel1 . close ( ) ; } catch ( IOException e ) { if ( channel2 != null ) channel2 . close ( ) ; throw e ; } if ( channel2 != null ) channel2 . close ( ) ; } return true ;


signature:
public class Files { /** * Clean or unmap a direct ByteBuffer
 * < p > DirectByteBuffers are garbage collected by using a phantom reference and a
 * reference queue . Every once a while , the JVM checks the reference queue and
 * cleans the DirectByteBuffers . However , as this doesn ' t happen immediately
 * after discarding all references to a DirectByteBuffer , it ' s easy get
 * { @ link OutOfMemoryError } problems using direct ByteBuffers . < / p >
 * < p > Also , if a file is still mapped , via { @ link MappedByteBuffer } , then it is
 * locked and cannot be destroyed or possibly written to if it was previously
 * mapped read . Trying to destroy or write to a locked file will result in an
 * { @ link IOException } < / p >
 * < p > This function explicitly calls the cleaner method of a { @ link ByteBuffer } using
 * reflection because it is not publicly accessible . < / p >
 * @ param byteBuffer The DirectByteBuffer that will be " cleaned " . Returns immediately if
 * the argument is null .
 * @ throws IllegalArgumentException if byteBuffer isn ' t direct
 * @ throws RuntimeException if cleaning may have failed */
public static void cleanDirectByteBuffer ( final ByteBuffer byteBuffer ) { } }

implementation:
if ( byteBuffer == null ) return ; if ( ! byteBuffer . isDirect ( ) ) throw new IllegalArgumentException ( "byteBuffer isn't direct!" ) ; AccessController . doPrivileged ( new PrivilegedAction < Void > ( ) { public Void run ( ) { try { Method cleanerMethod = byteBuffer . getClass ( ) . getMethod ( "cleaner" ) ; cleanerMethod . setAccessible ( true ) ; Object cleaner = cleanerMethod . invoke ( byteBuffer ) ; Method cleanMethod = cleaner . getClass ( ) . getMethod ( "clean" ) ; cleanMethod . setAccessible ( true ) ; cleanMethod . invoke ( cleaner ) ; } catch ( NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e ) { throw new RuntimeException ( "Could not clean MappedByteBuffer -- File may still be locked!" ) ; } return null ; // nothing to return
} } ) ;


signature:
public class TransactionalHashMap { /** * Rolls back the changes to the map . */
public void rollback ( ) { } }

implementation: if ( auto_commit ) return ; String id = getCurrentThreadId ( ) ; Entry < K , V > tab [ ] = table ; for ( int i = 0 ; i < tab . length ; i ++ ) { Entry < K , V > prev = table [ i ] ; Entry < K , V > e = prev ; while ( e != null ) { Entry < K , V > next = e . next ; if ( e . is ( Entry . ADDED , id ) ) { modCount ++ ; size -- ; if ( prev == e ) table [ i ] = next ; else prev . next = next ; } else if ( e . is ( Entry . DELETED , id ) ) e . setStatus ( Entry . NO_CHANGE , null ) ; prev = e ; e = next ; } }


signature:
public class TransactionalHashMap { /** * Checks that this entry is valid for the current thread
 * @ param entry the entry to be checked
 * @ return true if entry is valid , otherwise false */
private boolean validEntry ( final Entry < K , V > entry ) { } }

implementation: if ( auto_commit || entry == null ) return ( entry != null ) ; String id = getCurrentThreadId ( ) ; return ! ( ( entry . is ( Entry . DELETED , id ) ) || ( entry . is ( Entry . ADDED , null ) && entry . is ( Entry . NO_CHANGE , id ) ) ) ;


signature:
public class TransactionalHashMap { /** * Returns internal representation for key . Use NULL _ KEY if key is null . */
@ SuppressWarnings ( "unchecked" ) static < T > T maskNull ( T key ) { } }

implementation: return ( key == null ? ( T ) NULL_KEY : key ) ;


signature:
public class TransactionalHashMap { /** * Returns a hash value for the specified object . In addition to
 * the object ' s own hashCode , this method applies a " supplemental
 * hash function , " which defends against poor quality hash functions .
 * This is critical because HashMap uses power - of two length
 * hash tables . < p >
 * The shift distances in this function were chosen as the result
 * of an automated search over the entire four - dimensional search space . */
static int hash ( Object x ) { } }


signature:
public class TransactionalHashMap { /** * Check for equality of non - null reference x and possibly - null y . */
static boolean eq ( Object x , Object y ) { } }

implementation: return x == y || x . equals ( y ) ;


signature:
public class TransactionalHashMap { /** * Returns the value to which the specified key is mapped in this identity
 * hash map , or < tt > null < / tt > if the map contains no mapping for this key .
 * A return value of < tt > null < / tt > does not < i > necessarily < / i > indicate
 * that the map contains no mapping for the key ; it is also possible that
 * the map explicitly maps the key to < tt > null < / tt > . The
 * < tt > containsKey < / tt > method may be used to distinguish these two cases .
 * @ param key the key whose associated value is to be returned .
 * @ return the value to which this map maps the specified key , or
 * < tt > null < / tt > if the map contains no mapping for this key .
 * @ see # put ( Object , Object ) */
@ Override public V get ( Object key ) { } }

implementation: Object k = maskNull ( key ) ; int hash = hash ( k ) ; int i = indexFor ( hash , table . length ) ; Entry < K , V > e = table [ i ] ; while ( true ) { if ( e == null ) return null ; if ( e . hash == hash && validEntry ( e ) && eq ( k , e . key ) ) return e . value ; e = e . next ; }


signature:
public class TransactionalHashMap { /** * Returns the entry associated with the specified key in the
 * HashMap . Returns null if the HashMap contains no mapping
 * for this key . */
Entry < K , V > getEntry ( Object key ) { } }

implementation: Object k = maskNull ( key ) ; int hash = hash ( k ) ; int i = indexFor ( hash , table . length ) ; Entry < K , V > e = table [ i ] ; while ( e != null && ! ( e . hash == hash && validEntry ( e ) && eq ( k , e . key ) ) ) e = e . next ; return e ;


signature:
public class TransactionalHashMap { /** * Associates the specified value with the specified key in this map .
 * If the map previously contained a mapping for this key , the old
 * value is replaced .
 * @ param key key with which the specified value is to be associated .
 * @ param value value to be associated with the specified key .
 * @ return previous value associated with specified key , or < tt > null < / tt >
 * if there was no mapping for key . A < tt > null < / tt > return can
 * also indicate that the HashMap previously associated
 * < tt > null < / tt > with the specified key . */
@ Override public V put ( K key , V value ) throws ConcurrentModificationException { } }

implementation:
K k = maskNull ( key ) ; int hash = hash ( k ) ; int i = indexFor ( hash , table . length ) ; V oldValue = null ; for ( Entry < K , V > e = table [ i ] ; e != null ; e = e . next ) { if ( e . hash == hash && eq ( k , e . key ) ) { // check if someone else has a pending add for the same key
if ( e . is ( Entry . ADDED , null ) && ! e . is ( Entry . ADDED , getCurrentThreadId ( ) ) ) throw new ConcurrentModificationException ( ) ; if ( validEntry ( e ) ) { oldValue = e . value ; // if not transactional can reuse entries
if ( auto_commit ) { e . value = value ; return oldValue ; } else e . setStatus ( Entry . DELETED , getCurrentThreadId ( ) ) ; } } } modCount ++ ; addEntry ( hash , k , value , i ) ; return oldValue ;


signature:
public class TransactionalHashMap { /** * Rehashes the contents of this map into a new array with a
 * larger capacity . This method is called automatically when the
 * number of keys in this map reaches its threshold .
 * If current capacity is MAXIMUM _ CAPACITY , this method does not
 * resize the map , but but sets threshold to Integer . MAX _ VALUE .
 * This has the effect of preventing future calls .
 * @ param newCapacity the new capacity , MUST be a power of two ;
 * must be greater than current capacity unless current
 * capacity is MAXIMUM _ CAPACITY ( in which case value
 * is irrelevant ) . */
@ SuppressWarnings ( "unchecked" ) void resize ( int newCapacity ) { } }

implementation: Entry < K , V > [ ] oldTable = table ; int oldCapacity = oldTable . length ; if ( oldCapacity == MAXIMUM_CAPACITY ) { threshold = Integer . MAX_VALUE ; return ; } Entry < K , V > [ ] newTable = new Entry [ newCapacity ] ; transfer ( newTable ) ; table = newTable ; threshold = ( int ) ( newCapacity * loadFactor ) ;