signature:
public class Log { /** * Creates a new logger .
 * @ param name a name for the logger
 * @ param level the logging level for the logger
 * @ param file the file to output all logging to
 * @ return the created logger */
public static Logger createLogger ( String name , Level level , String file ) { } }

implementation:
LoggerContext lc = ( LoggerContext ) LoggerFactory . getILoggerFactory ( ) ; PatternLayoutEncoder ple = new PatternLayoutEncoder ( ) ; ple . setPattern ( "%date %level [%thread] %logger{10} [%file:%line]%n%msg%n%n" ) ; ple . setContext ( lc ) ; ple . start ( ) ; FileAppender < ILoggingEvent > fileAppender = new FileAppender < ILoggingEvent > ( ) ; fileAppender . setFile ( file ) ; fileAppender . setEncoder ( ple ) ; fileAppender . setAppend ( false ) ; fileAppender . setContext ( lc ) ; fileAppender . start ( ) ; logger = ( Logger ) LoggerFactory . getLogger ( name ) ; logger . detachAndStopAllAppenders ( ) ; // detach console ( doesn ' t seem to work )
logger . addAppender ( fileAppender ) ; // attach file appender
logger . setLevel ( level ) ; logger . setAdditive ( true ) ; // set to true if root should log too
return logger ;


signature:
public class Plan { /** * Performs a single step of this plan , i . e . , progresses this intention . */
public void step ( ) { } }

implementation: if ( body == null || body . length == 0 || index < 0 || index >= body . length ) { return ; } body [ index ++ ] . step ( ) ;


signature:
public class AgentType { /** * Sets the list of goals for this agent .
 * @ param arr array of goal IDs */
public void setGoals ( byte [ ] arr ) { } }

implementation: if ( arr == null ) { goals = null ; return ; } goals = new byte [ arr . length ] ; System . arraycopy ( arr , 0 , goals , 0 , goals . length ) ;


signature:
public class AgentType { /** * < p > addGoal . < / p >
 * @ param goal a byte . */
public void addGoal ( byte goal ) { } }

implementation: goals = GoalPlanType . grow ( goals , 1 ) ; goals [ goals . length - 1 ] = goal ;


signature:
public class Program { /** * Waits for user to press a key before continuing . Useful for connecting to a profiler */
static void pauseForUserInput ( ) { } }

implementation: System . out . println ( "Press the Enter/Return key to continue.." ) ; Scanner in = new Scanner ( System . in ) ; in . nextLine ( ) ; in . close ( ) ;


signature:
public class Program { /** * Initialises the intention selection pools .
 * @ param nagents total number of agents to distribution between the intention selection pools
 * @ param ncores total number of cores */
public static void initIntentionSelectionPools ( int nagents , int ncores ) { } }

implementation: Main . poolsize = ( nagents > ncores ) ? ( nagents / ncores ) : 1 ; Main . npools = ( nagents > ncores ) ? ncores : nagents ;


signature:
public class Program { /** * Starts the intention selection threads that each handle a pool of agents .
 * @ param config the global configuration object */
static void initIntentionSelectionThreads ( Config config ) { } }

implementation: int ncores = config . getNumThreads ( ) ; Main . intentionSelectors = new IntentionSelector [ ncores ] ; for ( int i = 0 ; i < Main . npools ; i ++ ) { Main . intentionSelectors [ i ] = new IntentionSelector ( i , config . getRandomSeed ( ) ) ; }


signature:
public class Program { /** * Starts the intention selection threads . */
static void startIntentionSelectionThreads ( ) { } }

implementation:
for ( int i = 0 ; i < Main . npools ; i ++ ) { Thread thread = new Thread ( Main . intentionSelectors [ i ] ) ; thread . setName ( "jill-" + i ) ; thread . start ( ) ; // start and wait at the entry barrier
}


signature:
public class Program { /** * Stops the intention selection threads . */
static void shutdownIntentionSelectionThreads ( ) { } }

implementation: for ( int i = 0 ; i < Main . npools ; i ++ ) { Main . intentionSelectors [ i ] . shutdown ( ) ; }


signature:
public class Program { /** * Loads any configured extensions ( see { @ link JillExtension } ) .
 * @ param config a valid configuration
 * @ return true if successfully loaded , false otherwise */
static boolean loadExtensions ( Config config ) { } }

implementation: if ( config . getExtensions ( ) == null ) { return true ; } for ( Config . ExtensionData extensionData : config . getExtensions ( ) ) { JillExtension extension = ProgramLoader . loadExtension ( extensionData . getClassname ( ) ) ; if ( extension != null ) { Program . registerExtension ( extension ) ; extension . init ( extensionData . getArgs ( ) . toArray ( new String [ 0 ] ) ) ; } else { return false ; } } return true ;


signature:
public class Program { /** * Registers a new Jill extension .
 * @ param extension the extension to register */
public static void registerExtension ( JillExtension extension ) { } }

implementation: if ( extension != null ) { GlobalState . eventHandlers . add ( extension ) ; Main . logger . info ( "Registered Jill extension: " + extension ) ; } else { Main . logger . warn ( "Cannot register null extension; will ignore." ) ; }


signature:
public class TokenAgent3 { /** * { @ inheritDoc } . */
@ Override public void start ( PrintStream writer , String [ ] params ) { } }

implementation:
parse ( params ) ; out = writer ; // Create a new belief set about neighbours
BeliefSetField [ ] fields = { new BeliefSetField ( "name" , String . class , true ) , } ; try { // Attach this belief set to this agent
this . createBeliefSet ( beliefset , fields ) ; int numAgents = GlobalState . agents . size ( ) ; // Cannot have more neighbours than agents
if ( neighbourhood >= numAgents ) { Log . error ( "Agent " + getName ( ) + " cannot add " + neighbourhood + " neighbours, when there are only " + numAgents + " agents all up" ) ; System . exit ( - 1 ) ; } // Add beliefs about neighbours
for ( int i = 1 ; i <= neighbourhood ; i ++ ) { int neighbour = ( getId ( ) + i ) % numAgents ; this . addBelief ( beliefset , Integer . toString ( neighbour ) ) ; Log . debug ( "Agent " + getName ( ) + " added neighbour " + neighbour ) ; } Log . debug ( "Agent " + getName ( ) + " is initialising with neighbourhood size of " + neighbourhood + " on each side (so " + ( neighbourhood * 2 ) + " neighbours)" ) ; // Let Agent 0 start the token passing
if ( getId ( ) == 0 ) { Log . debug ( "round 1" ) ; Token3 token = new Token3 ( 1 , 1 ) ; token . setHops ( 1 ) ; send ( 1 , token ) ; } } catch ( BeliefBaseException e ) { Log . error ( e . getMessage ( ) ) ; }


signature:
public class TokenAgent3 { /** * Parses the command line arguments .
 * @ param args the command line arguments */
public static void parse ( String [ ] args ) { } }

implementation:
for ( int i = 0 ; i < args . length ; i ++ ) { switch ( args [ i ] ) { case "-neighbourhood" : if ( i + 1 < args . length ) { i ++ ; try { neighbourhood = Integer . parseInt ( args [ i ] ) ; } catch ( NumberFormatException e ) { Log . warn ( "Value '" + args [ i ] + "' is not a number" ) ; } } break ; case "-rounds" : if ( i + 1 < args . length ) { i ++ ; try { rounds = Integer . parseInt ( args [ i ] ) ; } catch ( NumberFormatException e ) { Log . warn ( "Value '" + args [ i ] + "' is not a number" ) ; } } break ; default : // Ignore all other arguments
break ; } }


signature:
public class GlobalState { /** * Resets the global state . */
public static void reset ( ) { } }

implementation: agentTypes = new AObjectCatalog ( "agentTypes" , 5 , 5 ) ; goalTypes = new AObjectCatalog ( "goalTypes" , 10 , 5 ) ; planTypes = new AObjectCatalog ( "planTypes" , 20 , 5 ) ; agents = null ; beliefbase = null ; eventHandlers = new HashSet < JillExtension > ( ) ;


signature:
public class ProgramLoader { /** * Creates a given number of agents of a given Class , and adds the newly created agents to the
 * given store .
 * @ param className the fully qualified Java classname for the agents begin created
 * @ param num the number of agents ( class instances ) to create
 * @ param agents the store to which these agents should be added
 * @ return true if agents were successfully created and added , false otherwise */
public static boolean loadAgent ( String className , int num , AObjectCatalog agents ) { } }

implementation:
// Load the Agent class
Class < ? > aclass = loadClass ( className , Agent . class ) ; if ( aclass == null ) { return false ; } // Save this agent type to the catalog of known agent types
AgentType atype = new AgentType ( className ) ; atype . setAgentClass ( aclass ) ; GlobalState . agentTypes . push ( atype ) ; // Find the goals that this agent has
String [ ] goals = getGoalsFromAgentInfoAnnotation ( aclass ) ; if ( goals . length == 0 ) { return false ; } // First pass : get the goals and their plans ( flat goal - plan list )
loadGoalPlanNodes ( atype , goals ) ; // Second pass : complete the goal - plan hierarchy
completeGoalPlanHierarchy ( ) ; // Now create the specified number of instances of this agent type
createAgentsInCatalog ( agents , atype , aclass , num ) ; // return success
return true ;


signature:
public class ProgramLoader { /** * Loads the given plan classes and sets up parent - child links with the given goal type .
 * @ param gtype the goal for which the list of plans is provided
 * @ param plans list of plans to be loaded
 * @ return true if successful , false otherwise */
private static boolean processPlansForGoal ( GoalType gtype , String [ ] plans ) { } }

implementation:
for ( int j = 0 ; j < plans . length ; j ++ ) { // Load the Plan class
Class < ? > pclass = loadClass ( plans [ j ] , Plan . class ) ; if ( pclass == null ) { return false ; } // Found the plan class , so add this plan to the catalog of known plan types
logger . info ( "Found Plan " + pclass . getName ( ) + " that handles Goal " + gtype . getName ( ) ) ; PlanType ptype = new PlanType ( pclass . getName ( ) ) ; ptype . setPlanClass ( pclass ) ; GlobalState . planTypes . push ( ptype ) ; // Set up the parent / child links between them ( makings of a goal - plan tree )
ptype . addParent ( ( byte ) gtype . getId ( ) ) ; gtype . addChild ( ( byte ) ptype . getId ( ) ) ; } return true ;


signature:
public class ProgramLoader { /** * Completes the Goal - Plan hierarchy linkages between all { @ link GlobalState # goalTypes } and
 * { @ link GlobalState # planTypes } .
 * @ return true if successful , false otherwise */
private static boolean completeGoalPlanHierarchy ( ) { } }

implementation:
for ( int i = 0 ; i < GlobalState . planTypes . size ( ) ; i ++ ) { PlanType ptype = ( PlanType ) GlobalState . planTypes . get ( i ) ; String [ ] postsGoals = getGoalsFromPlanInfoAnnotation ( ptype . getPlanClass ( ) ) ; // A @ PlanInfo is optional , and only present if this plan posts goals
if ( postsGoals == null ) { continue ; } // But if @ PlanInfo was given then it cannot be incomplete
if ( postsGoals . length == 0 ) { return false ; } // All good , so find the goals that this plan posts and set up the Goal - Plan tree links
for ( String goalname : postsGoals ) { GoalType gtype = ( GoalType ) GlobalState . goalTypes . find ( goalname ) ; if ( gtype == null ) { logger . error ( "Plan " + ptype . getName ( ) + " posts goal " + goalname + "which is not a known goal type." ) ; return false ; } // Found a goal posted by the plan , so setup the parent - child links
ptype . addChild ( ( byte ) gtype . getId ( ) ) ; gtype . addParent ( ( byte ) ptype . getId ( ) ) ; } } return true ;


signature:
public class ProgramLoader { /** * Creates the specified number of agent instances of the given type and adds them to the catalog .
 * @ param agents the catalog to add agents to
 * @ param atype the type of agents to create
 * @ param aclass the class of that agent type
 * @ param num the number of instances of that agent ( class ) to create */
private static void createAgentsInCatalog ( AObjectCatalog agents , AgentType atype , Class < ? > aclass , int num ) { } }

implementation:
int added = 0 ; try { for ( int i = 0 ; i < num ; i ++ ) { // Create a new instance ( name prefix ' a ' for agents )
Agent agent = ( Agent ) ( aclass . getConstructor ( String . class ) . newInstance ( "a" + Integer . toString ( i ) ) ) ; // Assign the static goal plan tree hierarchy to this instance
agent . setGoals ( atype . getGoals ( ) ) ; // Add this instance to the catalog of agent instances
agents . push ( agent ) ; added ++ ; } logger . info ( "Finished loading {} agents" , added ) ; } catch ( NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e ) { logger . error ( "Could not create instance of class " + aclass . getName ( ) ) ; }


signature:
public class ProgramLoader { /** * Gets the list of goals specified in the @ AgentInfo annotation of the given agent class .
 * @ param aclass the agent class containing the @ AgentInfo annotation
 * @ return list of goals specified in the @ AgentInfo annotation , or an empty array if unsuccessful */
private static String [ ] getGoalsFromAgentInfoAnnotation ( Class < ? > aclass ) { } }

implementation:
// Find the goals that this agent has
Annotation annotation = aclass . getAnnotation ( AgentInfo . class ) ; if ( annotation == null ) { logger . error ( "Agent " + aclass . getName ( ) + " is missing the " + "@AgentInfo(hasGoals={\"package.GoalClass1, package.GoalClass2, ...\"}) " + knowsNothing + "about this agent's goals and plans." ) ; return new String [ 0 ] ; } AgentInfo ainfo = ( AgentInfo ) annotation ; String [ ] goals = ainfo . hasGoals ( ) ; if ( goals . length == 0 ) { logger . error ( "Agent " + aclass . getName ( ) + " does not have any goals defined. Was expecting something like " + "@AgentInfo(hasGoals={\"package.GoalClass1, package.GoalClass2, ...\"}) " + knowsNothing + "about this agent's goals and plans." ) ; } return goals ;


signature:
public class ProgramLoader { /** * Gets the list of plans specified in the @ GoalInfo annotation of the given goal class .
 * @ param gclass the goal class containing the @ GoalInfo annotation
 * @ return list of plans specified in the @ GoalInfo annotation , or an empty array if unsuccessful */
private static String [ ] getPlansFromGoalsInfoAnnotation ( Class < ? > gclass ) { } }

implementation:
// Find the plans that this goal has
Annotation annotation = gclass . getAnnotation ( GoalInfo . class ) ; if ( annotation == null ) { logger . error ( "Goal " + gclass . getName ( ) + " is missing the " + "@GoalInfo(hasPlans={\"package.PlanClass1, package.PlanClass2, ...\"}) " + knowsNothing + "about which plans can handle this goal." ) ; return new String [ 0 ] ; } GoalInfo ginfo = ( GoalInfo ) annotation ; String [ ] plans = ginfo . hasPlans ( ) ; if ( plans . length == 0 ) { logger . error ( "Goal " + gclass . getName ( ) + " does not have any plans defined. Was expecting something like " + "@GoalInfo(hasPlans={\"package.PlanClass1, package.PlanClass2, ...\"}) " + knowsNothing + "about which plans can handle this goal." ) ; } return plans ;


signature:
public class ProgramLoader { /** * Gets the list of goals specified in the @ PlanInfo annotation of the given plan class .
 * @ param pclass the plan class containing the @ PlanInfo annotation
 * @ return list of goals specified in the @ PlanInfo annotation ; or null if the annotioan was not
 * present ; or an empty array if the annotation has errors */
private static String [ ] getGoalsFromPlanInfoAnnotation ( Class < ? > pclass ) { } }

implementation:
Annotation annotation = pclass . getAnnotation ( PlanInfo . class ) ; PlanInfo pinfo = ( PlanInfo ) annotation ; // A @ PlanInfo is optional , and only present if this plan posts goals
if ( pinfo == null ) { return null ; } String [ ] postsGoals = pinfo . postsGoals ( ) ; if ( postsGoals . length == 0 ) { logger . error ( "Plan " + pclass . getName ( ) + " has incomplete " + "@PlanInfo(postsGoals={\"package.GoalClass1\", \"package.GoalClass2\", ...})) " + "annotation" ) ; } else { logger . info ( "Plan " + pclass . getName ( ) + " posts " + postsGoals . length + " goals" ) ; } return postsGoals ;


signature:
public class ProgramLoader { /** * Loads the class of given name and type .
 * @ param className the fully qualified class name
 * @ param classType the class type to check against
 * @ return the loaded class , or null if unsuccessful */
private static Class < ? > loadClass ( String className , Class < ? > classType ) { } }

implementation: Class < ? > aclass = null ; try { aclass = Class . forName ( className ) ; } catch ( ClassNotFoundException e ) { logger . error ( "Class not found: " + className , e ) ; return null ; } if ( ! classType . isAssignableFrom ( aclass ) ) { logger . error ( "Class '" + className + "' is not of type " + classType . getName ( ) ) ; return null ; } logger . info ( "Found class " + className + " of type " + classType . getName ( ) ) ; return aclass ;


signature:
public class ProgramLoader { /** * Loads a Jill extension .
 * @ param className the fully qalified Java classname of the extension
 * @ return an instance of the Jill extension class */
public static JillExtension loadExtension ( String className ) { } }

implementation:
JillExtension extension = null ; Class < ? > eclass ; try { // Check that we have the extension class , else abort
eclass = Class . forName ( className ) ; if ( ! JillExtension . class . isAssignableFrom ( eclass ) ) { logger . error ( "Class '" + className + "' does not implement " + JillExtension . class . getName ( ) ) ; return null ; } logger . info ( "Loading extension " + className ) ; extension = ( JillExtension ) ( eclass . newInstance ( ) ) ; } catch ( ClassNotFoundException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException e ) { logger . error ( "Could not load extension " + className , e ) ; } return extension ;


signature:
public class AObject { /** * Checks if two objects have the same name . The check is case sensitive .
 * @ param obj1 the first object
 * @ param obj2 the second object
 * @ return true if the objects have the same non - null non - empty name , and false otherwise */
public static boolean isNameEqual ( AObject obj1 , AObject obj2 ) { } }

implementation:
// Not equal if the names are null , or empty , or not the same size
if ( obj1 . name == null || obj2 . name == null || obj1 . name . length != obj2 . name . length || obj1 . name . length == 0 ) { return false ; } // Not equal if any name character is different
for ( int i = 0 ; i < obj1 . name . length ; i ++ ) { if ( obj1 . name [ i ] != obj2 . name [ i ] ) { return false ; } } // Else equal
return true ;


signature:
public class ArgumentsLoader { /** * Returns a usage string for the Jill command line arguments .
 * @ return the usage string */
public static String usage ( ) { } }

implementation: return GlobalConstant . APP_HEADER + "\n\n" + "usage: " + Main . class . getName ( ) + "  [options] --agent-class <agentclass> --num-agents <numagents>" + "\n" + "   --config <string>                 load configuration from string" + "\n" + "   --configfile <file>               load configuration from file" + "\n" + "   --exit-on-idle <boolean>          forces system exit when all agents are " + "idle (default is '" + GlobalConstant . EXIT_ON_IDLE + "')\n" + "   --help                            print this usage message and exit \n" + "   --plan-selection-policy <policy>  policy for selecting from plan instances " + "(FIRST, RANDOM, or LAST (default is '" + GlobalConstant . PLAN_SELECTION_POLICY + "')\n" + "   --plan-instances-limit <number>   maximum number of applicable plan instances " + "to consider (default is '" + GlobalConstant . PLAN_INSTANCES_LIMIT + "')\n" ;


signature:
public class ArgumentsLoader { /** * Parses the given command line arguments .
 * @ param args the command line arguments */
public static void parse ( String [ ] args ) { } }

implementation:
for ( int i = 0 ; args != null && i < args . length ; i ++ ) { // First parse args that don ' t require an option
if ( "--help" . equals ( args [ i ] ) ) { abort ( null ) ; } // Now parse args that must be accompanied by an option
if ( i + 1 < args . length ) { parseArgumentWithOption ( args [ i ] , args [ ++ i ] ) ; // force increment the counter
} } // Abort if required args were not given
if ( config == null ) { abort ( "Configuration file or string was not given" ) ; } else if ( config . getAgents ( ) == null || config . getAgents ( ) . isEmpty ( ) ) { abort ( "Configuration is missing agents specification" ) ; }


signature:
public class ArgumentsLoader { /** * Parses the given command line argument and associated option . Will abort if an unrecoverable
 * error occurs .
 * @ param arg the argument to parse
 * @ param opt the options to parse for that argument */
private static void parseArgumentWithOption ( String arg , String opt ) { } }

implementation:
switch ( arg ) { case "--config" : config = loadConfigFromString ( opt ) ; break ; case "--configfile" : config = loadConfigFromFile ( opt ) ; break ; case "--exit-on-idle" : GlobalConstant . EXIT_ON_IDLE = Boolean . parseBoolean ( opt ) ; break ; case "--plan-selection-policy" : try { GlobalConstant . PLAN_SELECTION_POLICY = GlobalConstant . PlanSelectionPolicy . valueOf ( opt ) ; } catch ( IllegalArgumentException e ) { abort ( "Unknown plan selection policy '" + opt + "'" ) ; } break ; case "--plan-instances-limit" : try { GlobalConstant . PLAN_INSTANCES_LIMIT = Integer . parseInt ( opt ) ; } catch ( NumberFormatException e ) { abort ( "Option value '" + opt + "' is not a number" ) ; } break ; default : // Ignore any other arguments ( which may be used by components external to Jill )
break ; }


signature:
public class ArgumentsLoader { /** * Loads the Jill startup configuration object . < p > Configuration is specified at run time via one
 * of the following two options : < ul > < li > { @ code - - config < string > } < / li > < li >
 * { @ code - - configfile < file > } < / li > < / ul > The contents of { @ code < string > } or { @ code < file > } are
 * parsed in exactly the same way . The expected syntax is JSON format . If both options are
 * specified , then last specified option will overrule . < / p >
 * @ return the Jill startup configuration object */
static Config loadConfigFromString ( String str ) { } }

implementation: Gson gson = new Gson ( ) ; Config config = null ; try { config = gson . fromJson ( str , Config . class ) ; } catch ( JsonSyntaxException e ) { abort ( "Invalid JSON syntax in " + str + ": " + e . getMessage ( ) ) ; } return config ;


signature:
public class BeliefBase { /** * Sample program to test belief base evaluation speeds .
 * @ param args command line arguments
 * @ throws BeliefBaseException on belief base update or evaluation errors */
public static void main ( String [ ] args ) throws BeliefBaseException { } }

implementation:
// Configure logging
Log . createLogger ( "" , Level . INFO , "BeliefBase.log" ) ; // BeliefBase bb = new H2BeliefBase ( " jdbc : h2 : mem : agents ; CACHE _ SIZE = 1048576 " ) ;
String bs1 = "neighbour" ; String bs2 = "hascar" ; long t0 ; long t1 ; int numAgents = 10000 ; int numNeighbours = 1000 ; BeliefBase bb = new ABeliefStore ( numAgents , 4 ) ; Log . info ( "Initialising " + numAgents + " agents with " + numNeighbours + " beliefs each" ) ; BeliefSetField [ ] fields1 = { new BeliefSetField ( "name" , String . class , true ) , new BeliefSetField ( "gender" , String . class , false ) , } ; BeliefSetField [ ] fields2 = { new BeliefSetField ( "name" , String . class , true ) , new BeliefSetField ( "car" , Boolean . class , false ) , } ; long t2 = System . currentTimeMillis ( ) ; for ( int i = 0 ; i < numAgents ; i ++ ) { t0 = System . currentTimeMillis ( ) ; bb . createBeliefSet ( i , bs1 , fields1 ) ; t1 = System . currentTimeMillis ( ) ; Log . debug ( "Created belief set '" + bs1 + "' " + Log . formattedDuration ( t0 , t1 ) ) ; t0 = System . currentTimeMillis ( ) ; for ( int j = 0 ; j < numNeighbours ; j ++ ) { bb . addBelief ( i , bs1 , "agent" + j , ( ( j % 2 ) == 0 ) ? "male" : "female" ) ; } t1 = System . currentTimeMillis ( ) ; Log . debug ( "Agent " + i + " added " + numNeighbours + " beliefs to belief set '" + bs1 + "' (" + ( t1 - t0 ) + " ms)" ) ; } long t3 = System . currentTimeMillis ( ) ; Log . info ( "Finished initialising " + numAgents + " agents with " + numNeighbours + " beliefs each for belief set '" + bs1 + "' " + Log . formattedDuration ( t2 , t3 ) ) ; t2 = System . currentTimeMillis ( ) ; for ( int i = 0 ; i < numAgents ; i ++ ) { t0 = System . currentTimeMillis ( ) ; bb . createBeliefSet ( i , bs2 , fields2 ) ; t1 = System . currentTimeMillis ( ) ; Log . debug ( "Created belief set '" + bs2 + "' " + Log . formattedDuration ( t0 , t1 ) ) ; t0 = System . currentTimeMillis ( ) ; for ( int j = 0 ; j < numNeighbours ; j ++ ) { bb . addBelief ( i , bs2 , "agent" + j , ( ( j % 2 ) == 0 ) ? true : false ) ; } t1 = System . currentTimeMillis ( ) ; Log . debug ( "Agent " + i + " added " + numNeighbours + " beliefs to belief set '" + bs2 + "' (" + ( t1 - t0 ) + " ms)" ) ; } t3 = System . currentTimeMillis ( ) ; Log . info ( "Finished initialising " + numAgents + " agents with " + numNeighbours + " beliefs each for belief set '" + bs2 + "' " + Log . formattedDuration ( t2 , t3 ) ) ; final String opstr = ".name=agent" ; int agentId = 0 ; int neighbourId = 0 ; doEval ( bb , agentId , bs1 + opstr + neighbourId ) ; agentId = 0 ; neighbourId = numNeighbours - 1 ; doEval ( bb , agentId , bs1 + opstr + neighbourId ) ; agentId = numAgents - 1 ; neighbourId = numNeighbours - 1 ; doEval ( bb , agentId , bs1 + opstr + neighbourId ) ; agentId = 0 ; neighbourId = 0 ; doEval ( bb , agentId , bs1 + opstr + neighbourId ) ; agentId = 0 ; neighbourId = numNeighbours - 1 ; doEval ( bb , agentId , bs1 + opstr + neighbourId ) ; agentId = numAgents - 1 ; neighbourId = numNeighbours - 1 ; doEval ( bb , agentId , bs1 + opstr + neighbourId ) ;


signature:
public class BeliefBase { /** * Evaluates the given query on the given belief base for the agent .
 * @ param bb the belief base to query
 * @ param agentId the agent for which the query applies
 * @ param query the belief query
 * @ throws BeliefBaseException on query evaluation error
 * @ since 0.3.4 */
public static void doEval ( BeliefBase bb , int agentId , String query ) throws BeliefBaseException { } }

implementation: final long t0 = System . currentTimeMillis ( ) ; bb . eval ( agentId , query ) ; final long t1 = System . currentTimeMillis ( ) ; Log . info ( "Agent " + agentId + " searched for '" + query + "' " + Log . formattedDuration ( t0 , t1 ) ) ;


signature:
public class AObjectCatalog { /** * Gets the object at the given index of the catalog .
 * @ param index the index of the object
 * @ return the object at that index */
public AObject get ( int index ) { } }

implementation: if ( index >= 0 && index < objects . length ) { return objects [ index ] ; } return null ;


signature:
public class AObjectCatalog { /** * Find an object by name . Can be very expensive for large catalogs , since a name comparison is
 * performed in sequence on the objects in the catalog , until a match is found . Search is case
 * sensitive .
 * @ param name the name to find
 * @ return an AObject with a matching name , or null if not found */
public AObject find ( String name ) { } }

implementation: for ( int i = 0 ; i < nextid ; i ++ ) { if ( objects [ i ] . getName ( ) . equals ( name ) ) { return objects [ i ] ; } } return null ;


signature:
public class AObjectCatalog { /** * Pushes a new object to the top of the catalog .
 * @ param obj the object to add */
public void push ( AObject obj ) { } }

implementation:
if ( obj == null || obj . getId ( ) != GlobalConstant . NULLID ) { return ; } // Grow if we are at capacity
if ( nextid == objects . length ) { grow ( ) ; } obj . setId ( nextid ) ; objects [ nextid ++ ] = obj ;


signature:
public class AObjectCatalog { /** * Pops ( removes ) the object at the top of the catalog .
 * @ return the object at the top , or null if the catalog is empty */
public AObject pop ( ) { } }

implementation: if ( nextid > GlobalConstant . NULLID ) { nextid -- ; AObject obj = objects [ nextid ] ; objects [ nextid ] = null ; return obj ; } return null ;


signature:
public class AObjectCatalog { /** * Grows the Catalog by a factor of { @ link # increment } . */
private void grow ( ) { } }

implementation: AObject [ ] temp = new AObject [ objects . length + increment ] ; System . arraycopy ( objects , 0 , temp , 0 , objects . length ) ; objects = temp ;


signature:
public class ReceiveToken3 { /** * { @ inheritDoc } . */
@ Override public boolean context ( ) { } }

implementation: Agent agent = getAgent ( ) ; int myid = agent . getId ( ) ; int goalid = ( ( Token3 ) getGoal ( ) ) . getAgent ( ) ; try { return ( myid == goalid ) && agent . eval ( "neighbour.name = *" ) ; } catch ( BeliefBaseException e ) { Log . error ( e . getMessage ( ) ) ; } return false ;


signature:
public class ReceiveToken3 { /** * { @ inheritDoc } . */
@ Override public void setPlanVariables ( Map < String , Object > vars ) { } }

implementation: for ( String attribute : vars . keySet ( ) ) { if ( "name" . equals ( attribute ) ) { neighbour = ( String ) ( vars . get ( attribute ) ) ; } }


signature:
public class Stack255 { /** * Gets the object at the given index in the catalog .
 * @ param idx the position of the Object
 * @ return the Object , or null if the index is invalid */
public Object get ( int idx ) { } }

implementation:
int index = idx & 0xff ; if ( isEmpty ( ) ) { // System . err . println ( " index " + index + " is invalid as stack is empty " ) ;
return null ; } else if ( index < 0 || index >= size ) { // System . err . println ( " index " + index + " is outside of range [ 0 , " + ( size - 1 ) + " ] " ) ;
return null ; } return objects [ index ] ;


signature:
public class Stack255 { /** * Pushes an object on to the top of the stack .
 * @ param obj the Object to place on the stack
 * @ return true if successfully added , false if the stack was full */
public boolean push ( Object obj ) { } }

implementation:
// Cannot add beyond maximum capacity
if ( isFull ( ) ) { return false ; } // Grow if we are at capacity
if ( size == objects . length ) { grow ( ) ; } objects [ size ++ ] = obj ; return true ;


signature:
public class Stack255 { /** * Pops the Object at the top of the stack .
 * @ return the Object , or null if the stack is empty */
public Object pop ( ) { } }

implementation: if ( isEmpty ( ) ) { return null ; } size -- ; Object obj = objects [ size ] ; objects [ size ] = null ; return obj ;


signature:
public class Stack255 { /** * Grows the stack capacity by { @ link # increment } up to the maximum capacity of 255 ( byte size ) .
 * @ return true if the stack was successfully increased , false otherwise */
private boolean grow ( ) { } }

implementation:
if ( objects . length == MAXIMUM_CAPACITY ) { // Cannot grow beyond the maximum capacity
return false ; } int newsize = objects . length + increment ; if ( newsize > MAXIMUM_CAPACITY ) { newsize = MAXIMUM_CAPACITY ; } Object [ ] temp = new Object [ newsize ] ; System . arraycopy ( objects , 0 , temp , 0 , objects . length ) ; objects = temp ; return true ;


signature:
public class Player { /** * { @ inheritDoc } . */
@ Override public void start ( PrintStream writer , String [ ] params ) { } }

implementation:
out = writer ; // Parse the arguments
parse ( params ) ; // Create the board
board = new Board ( ndiscs ) ; out . println ( "Initialised hanoi board with " + ndiscs + " discs:" ) ; out . println ( board . toString ( ) ) ; // Solve the board
post ( new Solve ( "s" , ndiscs , 0 , 2 , 1 ) ) ;


signature:
public class ABeliefStore { /** * { @ inheritDoc } . */
@ Override public boolean createBeliefSet ( int agentid , String name , BeliefSetField [ ] fields ) throws BeliefBaseException { } }

implementation:
if ( beliefsets . containsKey ( name ) ) { return false ; } // Add the beliefset to the list of beliefsets
BeliefSet bs = new BeliefSet ( beliefsets . size ( ) , name , fields ) ; beliefsets . put ( name , bs ) ; beliefsetsByID . put ( bs . getId ( ) , bs ) ; return true ;


signature:
public class ABeliefStore { /** * { @ inheritDoc } . */
@ Override public boolean addBelief ( int agentid , String beliefsetName , Object ... tuple ) throws BeliefBaseException { } }

implementation:
// Check that the beliefset exists
if ( ! beliefsets . containsKey ( beliefsetName ) ) { throw new BeliefBaseException ( "Belief set '" + beliefsetName + "' does not exist" ) ; } // Create a new Belief
Belief belief = new Belief ( beliefs . size ( ) , beliefsets . get ( beliefsetName ) . getId ( ) , tuple ) ; // Add it to the list of beliefs
int id ; if ( ! beliefs . containsKey ( belief ) ) { id = beliefs . size ( ) ; beliefs . put ( belief , id ) ; beliefsByID . put ( belief . getId ( ) , belief ) ; } else { id = beliefs . get ( belief ) ; } // Add it to the agents beliefs
SparseBitSet bits = agents2beliefs [ agentid ] ; if ( bits == null ) { bits = new SparseBitSet ( ) ; } bits . set ( id ) ; agents2beliefs [ agentid ] = bits ; // Update the cached results
for ( String query : cachedresults . keySet ( ) ) { Set < Belief > results = cachedresults . get ( query ) ; if ( match ( belief , queries . get ( query ) ) ) { results . add ( belief ) ; } } return true ;


signature:
public class ABeliefStore { /** * { @ inheritDoc } . */
@ Override public boolean eval ( int agentid , String key ) throws BeliefBaseException { } }

implementation: return ! query ( agentid , key ) . isEmpty ( ) ;


signature:
public class ABeliefStore { /** * { @ inheritDoc } . */
@ Override public Set < Belief > query ( int agentid , String key ) throws BeliefBaseException { } }

implementation:
// Get the cached query if we have seen it before , else parse it
AQuery query = null ; if ( queries . containsKey ( key ) ) { query = queries . get ( key ) ; } else { // Valid queries have the following syntax
// beliefset . field OP value
// where OP is one of = , ! = , < , or >
if ( key == null ) { throw new BeliefBaseException ( logsuffix ( agentid ) + "'null' query" ) ; } Pattern pattern = Pattern . compile ( "(\\w+)\\.(\\w+)\\s*([=<>(!=)])\\s*(.+)" ) ; Matcher matcher = pattern . matcher ( key ) ; if ( ! matcher . matches ( ) ) { throw new BeliefBaseException ( logsuffix ( agentid ) + "invalid query '" + key + "' : syntax not of the form beliefset.field <op> value" ) ; } String strBeliefset = matcher . group ( 1 ) ; String strField = matcher . group ( 2 ) ; String strOp = matcher . group ( 3 ) ; String strVal = matcher . group ( 4 ) ; try { query = parseQuery ( agentid , strBeliefset , strField , strOp , strVal ) ; queries . put ( key , query ) ; } catch ( BeliefBaseException e ) { throw new BeliefBaseException ( logsuffix ( agentid ) + "could not parse query: " + key , e ) ; } } // Get the cached results if they exist ,
// else perform the query and cache the results
Set < Belief > results = null ; if ( cachedresults . containsKey ( key ) ) { results = cachedresults . get ( key ) ; } else { results = performQuery ( query , beliefs ) ; cachedresults . put ( key , results ) ; } // Finally , filter the results for this agent
Set < Belief > matches = filterResultsForAgent ( agentid , results ) ; Log . debug ( "Agent " + agentid + " found " + matches . size ( ) + " matches for the query" ) ; return matches ;


signature:
public class ABeliefStore { /** * Gets the type of the given object .
 * @ param obj the object whose type is being queried
 * @ return the type of the object , or null if unknown */
public static String getType ( Object obj ) { } }

implementation: if ( obj == null ) { return null ; } String type = null ; if ( obj instanceof String || obj instanceof Integer || obj instanceof Double || obj instanceof Boolean ) { type = obj . getClass ( ) . getName ( ) ; } return type ;


signature:
public class ABeliefStore { /** * Checks if the given query run on the given belief returns a match .
 * @ param belief the belief being queried
 * @ param query the query being performed on the belief
 * @ return true if there is a match , false otherwise */
private static boolean match ( Belief belief , AQuery query ) { } }

implementation:
assert ( belief != null ) ; assert ( query != null ) ; if ( belief . getBeliefset ( ) != query . getBeliefset ( ) ) { return false ; } switch ( query . getOp ( ) ) { case EQ : Object lhs = belief . getTuple ( ) [ query . getField ( ) ] ; Object rhs = query . getValue ( ) ; // Match wildcard or exact string
return "*" . equals ( rhs ) || lhs . equals ( rhs ) ; case GT : // TODO : Handle Operator . GT
case LT : // TODO : Handle Operator . LT
default : break ; } return false ;


signature:
public class ABeliefStore { /** * Sample program to test pattern matching .
 * @ param args command line arguments
 * @ throws BeliefBaseException thrown if something went wrong */
public static void main ( String [ ] args ) throws BeliefBaseException { } }

implementation: BeliefBase bb = new ABeliefStore ( 100 , 4 ) ; bb . eval ( 0 , "neighbour.age < 31" ) ; Console console = System . console ( ) ; if ( console == null ) { System . err . println ( "No console." ) ; System . exit ( 1 ) ; } while ( true ) { Pattern pattern = Pattern . compile ( console . readLine ( "%nEnter your regex: " ) ) ; Matcher matcher = pattern . matcher ( console . readLine ( "Enter input string to search: " ) ) ; boolean found = false ; while ( matcher . find ( ) ) { console . format ( "I found the text" + " \"%s\" starting at " + "index %d and ending at index %d.%n" , matcher . group ( ) , matcher . start ( ) , matcher . end ( ) ) ; found = true ; } if ( ! found ) { console . format ( "No match found.%n" ) ; } }


signature:
public class ABeliefStore { /** * Gets the belief set field name ( see
 * { @ link io . github . agentsoz . jill . core . beliefbase . BeliefSetField } ) for the given belief set
 * for the given agent .
 * @ param agentid the agent in question
 * @ param beliefset the beliefset of that agent
 * @ param index the index of the belief set field in that belief set
 * @ return the name of the belief set field
 * @ throws BeliefBaseException if something went wrong */
public static String getFieldName ( int agentid , int beliefset , int index ) throws BeliefBaseException { } }

implementation: if ( beliefset < 0 || beliefset > beliefsets . size ( ) ) { throw new BeliefBaseException ( "belief set id " + beliefset + " is invalid" ) ; } BeliefSetField [ ] bsf = beliefsetsByID . get ( beliefset ) . getFields ( ) ; if ( index < 0 || index >= bsf . length ) { throw new BeliefBaseException ( "belief set field id " + index + " is invalid" ) ; } return bsf [ index ] . getName ( ) ;


signature:
public class AString { /** * Encodes the String str into a sequence of bytes using the character set specified in CHARSET ,
 * storing the result into a new byte array .
 * @ param str the String to convert from
 * @ return the new byte array , or null if conversion was unsuccessful
 * @ see String # getBytes ( String ) */
public static byte [ ] toBytes ( String str ) { } }

implementation:
if ( str == null ) { return new byte [ 0 ] ; } byte [ ] val = null ; try { val = str . getBytes ( CHARSET ) ; } catch ( UnsupportedEncodingException e ) { // NOPMD - ignore empty catch
// Can never occur since CHARSET is correct and final
} return val ;


signature:
public class Agent { /** * Push the given goal to the given stack .
 * @ param stack the stack to push to new goal to
 * @ param goal the goal to push */
private void post ( Stack255 stack , Goal goal ) { } }

implementation: synchronized ( stack ) { logger . debug ( "{} posting goal {}" , Log . logPrefix ( getId ( ) ) , goal . getClass ( ) . getSimpleName ( ) ) ; stack . push ( goal ) ; Main . setAgentIdle ( getId ( ) , false ) ; } Main . flagMessageTo ( Main . poolid ( getId ( ) ) ) ;


signature:
public class Agent { /** * Send a message to an agent .
 * @ param id the agent to send the message to
 * @ param msg the message to send
 * @ return true if the message was sent successfully , false otherwise */
public boolean send ( int id , Goal msg ) { } }

implementation: AObject obj = agents . get ( id ) ; if ( obj == null ) { logger . warn ( "{} attempted to send a message to unknown agent id '{}'" , Log . logPrefix ( getId ( ) ) , id ) ; return false ; } logger . debug ( "{} is sending message of type {} to agent {}" , Log . logPrefix ( getId ( ) ) , msg . getClass ( ) . getSimpleName ( ) , id ) ; ( ( Agent ) obj ) . post ( msg ) ; return true ;


signature:
public class Agent { /** * Send a message to this agent .
 * @ param name the agent to send the message to
 * @ param msg the message to send
 * @ return true if the message was sent successfully , false otherwise */
public boolean send ( String name , Goal msg ) { } }

implementation: AObject obj = agents . find ( name ) ; if ( obj == null ) { logger . warn ( "{} attempted to send a message to unknown agent '{}'" , Log . logPrefix ( getId ( ) ) , name ) ; return false ; } ( ( Agent ) obj ) . post ( msg ) ; return true ;


signature:
public class Agent { /** * < p > start . < / p >
 * @ param writer a { @ link java . io . PrintStream } object .
 * @ param params an array of { @ link java . lang . String } objects . */
public void start ( PrintStream writer , String [ ] params ) { } }

implementation: logger . debug ( "{} is starting" , Log . logPrefix ( getId ( ) ) ) ;


signature:
public class Agent { /** * Returns this agent ' s top level goals .
 * @ return { @ link io . github . agentsoz . jill . lang . Agent # goals } */
public byte [ ] getGoals ( ) { } }

implementation: byte [ ] arr = new byte [ goals . length ] ; System . arraycopy ( goals , 0 , arr , 0 , arr . length ) ; return arr ;


signature:
public class Agent { /** * Set ' s this agent ' s top level goals , i . e . , { @ link # goals } .
 * @ param bs an array of goal IDs ( must exist in the
 * { @ link io . github . agentsoz . jill . core . GlobalState # goalTypes } catalog . */
public void setGoals ( byte [ ] bs ) { } }

implementation: goals = new byte [ bs . length ] ; System . arraycopy ( bs , 0 , goals , 0 , goals . length ) ;


signature:
public class Agent { /** * Creates a new belief set with the given fields .
 * < p > Example usage :
 * < pre >
 * BeliefSetField [ ] fields = { new BeliefSetField ( " name " , String . class , true ) ,
 * new BeliefSetField ( " gender " , String . class , false ) , } ;
 * createBeliefSet ( " neighbour " , fields ) ;
 * < / pre >
 * @ param name a name for this new belief set
 * @ param fields an array of belief set fields ( see
 * { @ link io . github . agentsoz . jill . core . beliefbase . BeliefSetField } )
 * @ throws io . github . agentsoz . jill . core . beliefbase . BeliefBaseException exception
 * ( see { @ link io . github . agentsoz . jill . core . beliefbase . BeliefSetField } ) */
public void createBeliefSet ( String name , BeliefSetField [ ] fields ) throws BeliefBaseException { } }

implementation: beliefbase . createBeliefSet ( getId ( ) , name , fields ) ;


signature:
public class Agent { /** * Adds a new belief to the specified belief set .
 * @ param beliefsetName the belief set to add the belief to ; must have been created previously
 * using { @ link # createBeliefSet ( String , BeliefSetField [ ] ) }
 * @ param tuple parameter list of field values ; types must match the specification in
 * { @ link # createBeliefSet ( String , BeliefSetField [ ] ) }
 * @ throws io . github . agentsoz . jill . core . beliefbase . BeliefBaseException exception
 * ( see { @ link io . github . agentsoz . jill . core . beliefbase . BeliefBaseException } ) */
public void addBelief ( String beliefsetName , Object ... tuple ) throws BeliefBaseException { } }

implementation: beliefbase . addBelief ( getId ( ) , beliefsetName , tuple ) ;


signature:
public class Agent { /** * Evaluates the given query against this agent ' s belief base .
 * @ param query the query to evaluate
 * @ return true if the query returned results , false otherwise
 * @ throws BeliefBaseException if something went wrong */
public boolean eval ( String query ) throws BeliefBaseException { } }

implementation: boolean result = beliefbase . eval ( getId ( ) , query ) ; lastresult = ( result ) ? beliefbase . query ( getId ( ) , query ) : new HashSet < Belief > ( ) ; return result ;


signature:
public class Agent { /** * Forces this agent to enter an idle state irrespective of whether it has any active intentions
 * or not . The agent will continue to remain in the suspected state until some event forces it to
 * become active again , at which point it will resume operation .
 * @ param val the new idle state of this agent */
public void suspend ( boolean val ) { } }

implementation: Main . setAgentIdle ( getId ( ) , val ) ; Main . flagMessageTo ( Main . poolid ( getId ( ) ) ) ;


signature:
public class GreetNeighbour { /** * { @ inheritDoc } . */
@ Override public boolean context ( ) { } }

implementation: try { return getAgent ( ) . eval ( "neighbour.gender = male" ) ; } catch ( BeliefBaseException e ) { Log . error ( e . getMessage ( ) ) ; } return false ;


signature:
public class BeliefSet { /** * Gets the field of this belief set that has the given name .
 * @ param name the name of the field to retrieve
 * @ return the belief set field matching that name , or null if not found
 * @ since 0.3.4 */
public BeliefSetField getFieldByName ( String name ) { } }

implementation: BeliefSetField field = null ; for ( int i = 0 ; i < fields . length ; i ++ ) { if ( name . equals ( fields [ i ] . getName ( ) ) ) { field = fields [ i ] ; break ; } } return field ;


signature:
public class BeliefSet { /** * Gets the index ( column ) of the given field in this belief set .
 * @ param field the field for which the index is required
 * @ return the index of that field , or - 1 if not found
 * @ since 0.3.4 */
public int getIndex ( BeliefSetField field ) { } }

implementation: int index = - 1 ; for ( int i = 0 ; i < fields . length ; i ++ ) { if ( field . equals ( fields [ i ] ) ) { index = i ; } } return index ;


signature:
public class TokenAgent2 { /** * { @ inheritDoc } . */
@ Override public void start ( PrintStream writer , String [ ] params ) { } }

implementation: parse ( params ) ; out = writer ; if ( getId ( ) == 0 ) { Log . debug ( "round 1" ) ; send ( 1 , new Token2 ( 1 , 1 ) ) ; }


signature:
public class TokenAgent2 { /** * Parses the command line arguments .
 * @ param args the command line arguments */
public static void parse ( String [ ] args ) { } }

implementation: for ( int i = 0 ; i < args . length ; i ++ ) { if ( "-rounds" . equals ( args [ i ] ) && i + 1 < args . length ) { i ++ ; try { rounds = Integer . parseInt ( args [ i ] ) ; } catch ( NumberFormatException e ) { Log . warn ( "Value '" + args [ i ] + "' is not a number" ) ; } } }


signature:
public class Greeter { /** * { @ inheritDoc } . */
@ Override public void start ( PrintStream writer , String [ ] params ) { } }

implementation:
// Parse the arguments
parse ( params ) ; // Create a new belief set about neighbours
BeliefSetField [ ] fields = { new BeliefSetField ( "name" , String . class , true ) , new BeliefSetField ( "gender" , String . class , false ) , } ; try { // Attach this belief set to this agent
this . createBeliefSet ( beliefset , fields ) ; // Add beliefs about neighbours
registerNeighbours ( rand , numNeighbours ) ; Log . debug ( "Agent " + getName ( ) + " is initialising with " + numNeighbours + " neighbours" ) ; // Post the goal to be friendly
post ( new BeFriendly ( "BeFriendly" ) ) ; } catch ( BeliefBaseException e ) { Log . error ( e . getMessage ( ) ) ; }


signature:
public class Greeter { /** * Helper function to add beliefs about neighbours .
 * @ param rand random number generator to use
 * @ param count number of beliefs to add
 * @ throws BeliefBaseException thrown if there is a belief base access error */
private void registerNeighbours ( Random rand , int count ) throws BeliefBaseException { } }

implementation: int size = ( count < 0 ) ? 0 : count ; for ( int i = 0 ; i < size ; i ++ ) { boolean male = ( rand . nextDouble ( ) < 0.5 ) ? true : false ; this . addBelief ( beliefset , buildName ( male ) , male ? "male" : "female" ) ; }


signature:
public class Greeter { /** * Builds a new name .
 * @ param male specifies whether the name should be for a male or female
 * @ return the constructed name */
private static String buildName ( boolean male ) { } }

implementation: StringBuilder name = new StringBuilder ( ) ; name . append ( male ? males [ rand . nextInt ( males . length ) ] : females [ rand . nextInt ( females . length ) ] ) . append ( ' ' ) . append ( middle [ rand . nextInt ( middle . length ) ] ) . append ( ' ' ) . append ( surnames [ rand . nextInt ( surnames . length ) ] ) ; return name . toString ( ) ;


signature:
public class Greeter { /** * Parses the command line arguments .
 * @ param args arguments passed to this program */
public static void parse ( String [ ] args ) { } }

implementation:
for ( int i = 0 ; i < args . length ; i ++ ) { switch ( args [ i ] ) { case "-seed" : if ( i + 1 < args . length ) { i ++ ; int seed = 0 ; try { seed = Integer . parseInt ( args [ i ] ) ; rand = new Random ( seed ) ; } catch ( NumberFormatException e ) { Log . warn ( "Seed value '" + args [ i ] + "' is not a number" ) ; } } break ; case "-neighbourhoodSize" : if ( i + 1 < args . length ) { i ++ ; try { numNeighbours = Integer . parseInt ( args [ i ] ) ; } catch ( NumberFormatException e ) { Log . warn ( "Neighbourhood size value '" + args [ i ] + "' is not a number" ) ; } } break ; default : // Ignore any other arguments
break ; } }


signature:
public class IntentionSelector { /** * Runs this intentions selction thread . */
public void run ( ) { } }

implementation:
Set < Integer > toRemove = new HashSet < Integer > ( ) ; do { boolean idle = true ; // Remove agents that have have become idle due to an external event
removeInactiveAgents ( ) ; // Add agents that have have become active due to an external event
addActiveAgents ( ) ; for ( Integer i : activeAgents ) { Agent agent = ( Agent ) GlobalState . agents . get ( i ) ; Stack255 agentExecutionStack = ( Stack255 ) ( agent ) . getExecutionStack ( ) ; if ( ! isStackValid ( agent , agentExecutionStack ) ) { // Mark this agent for removal
toRemove . add ( i ) ; continue ; } // At least one agent is active
idle = false ; // Get the item at the top of the stack
Object node = ( Object ) agentExecutionStack . get ( ( byte ) ( agentExecutionStack . size ( ) - 1 ) ) ; if ( node instanceof Plan ) { // If it is a plan then execute a plan step ; and if it finished then remove it
managePlan ( i , agentExecutionStack , ( Plan ) node , toRemove ) ; } else if ( node instanceof Goal ) { // If it is a goal then find a plan for it and put it on the stack
manageGoal ( i , agent , agentExecutionStack , ( Goal ) node ) ; } agent . nextActiveStack ( ) ; // select the next active stack for next time
} // remove agents that have finished executing plans and have gone idle in this cycle
removeFinishedAgents ( toRemove ) ; if ( idle ) { waitOnExternalMessage ( ) ; if ( shutdown ) { break ; } } } while ( true ) ; logger . debug ( "Pool {} is exiting" , poolid ) ;


signature:
public class IntentionSelector { /** * Checks if this agent ' s execution stack is valid . The stack is valid if it is not null or empty
 * and has not exceeded the maximum size limit of 255.
 * @ param agent the agent whose stack is to be checked
 * @ param agentExecutionStack that agent ' s execution stack
 * @ return true if stack is valid , false otherwise */
private boolean isStackValid ( Agent agent , Stack255 agentExecutionStack ) { } }

implementation: if ( agentExecutionStack == null ) { return false ; } final int esSize = agentExecutionStack . size ( ) ; logger . trace ( "{} execution stack is {}/255 full" , Log . logPrefix ( agent . getId ( ) ) , esSize ) ; if ( esSize == 0 ) { return false ; } if ( esSize >= 255 ) { logger . error ( "{} execution stack reached size limit of 255. Cannot continue." , Log . logPrefix ( agent . getId ( ) ) ) ; return false ; } return true ;


signature:
public class IntentionSelector { /** * Removes the given list of agents from the list of active agents .
 * @ param toRemove the list of agent IDs to remove */
private void removeFinishedAgents ( Set < Integer > toRemove ) { } }

implementation: if ( ! toRemove . isEmpty ( ) ) { for ( int i : toRemove ) { activeAgents . remove ( i ) ; } toRemove . clear ( ) ; }


signature:
public class IntentionSelector { /** * Manages the goal at the top of the execution stack of an agent . All relevant plans are
 * evaluated to see if their context conditions hold . Plans deemed applicable are then added to
 * the list of bindings from which a plan instane will be eventually selected .
 * @ param agentIndex the agent ' s index
 * @ param agent the agent in question
 * @ param agentExecutionStack the agent ' s execution stack
 * @ param node the goal at the top of the xecution stack
 * @ return false if something went wrong , true otherwise */
private boolean manageGoal ( int agentIndex , Agent agent , Stack255 agentExecutionStack , Goal node ) { } }

implementation:
// Get the goal type for this goal
GoalType gtype = ( GoalType ) GlobalState . goalTypes . find ( node . getClass ( ) . getName ( ) ) ; byte [ ] ptypes = gtype . getChildren ( ) ; assert ( ptypes != null ) ; // Clear any previous plan bindings before adding any new ones
bindings . clear ( ) ; for ( int p = 0 ; p < ptypes . length ; p ++ ) { PlanType ptype = ( PlanType ) GlobalState . planTypes . get ( ptypes [ p ] ) ; try { // Create an object of this Plan type , so we can
// access its context condition
Plan planInstance = ( Plan ) ( ptype . getPlanClass ( ) . getConstructor ( Agent . class , Goal . class , String . class ) . newInstance ( GlobalState . agents . get ( agentIndex ) , node , "p" ) ) ; // Clear previously buffered context results if any
agent . clearLastResults ( ) ; // Evaluate the context condition
if ( planInstance . context ( ) ) { // Get the results of context query just performed
Set < Belief > results = agent . getLastResults ( ) ; // Add the results to the bindings
bindings . add ( planInstance , ( results == null ) ? null : new LinkedHashSet < Belief > ( results ) ) ; } } catch ( NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e ) { logger . error ( "Could not create plan object of type " + ptype . getClass ( ) . getName ( ) , e ) ; } } int numBindings = bindings . size ( ) ; if ( numBindings == 0 ) { // No plan options for this goal at this point in time , so move to the next agent
logger . debug ( Log . logPrefix ( agent . getId ( ) ) + " has no applicable plans for goal " + gtype + " and will continue to wait indefinitely" ) ; return false ; } // Call the meta - level planning prior to plan selection
agent . notifyAgentPrePlanSelection ( bindings ) ; // Pick a plan option using specified policy
Plan planInstance = bindings . selectPlan ( GlobalConstant . PLAN_SELECTION_POLICY ) ; // Now push the plan on to the intention stack
synchronized ( agentExecutionStack ) { logger . debug ( Log . logPrefix ( agent . getId ( ) ) + " choose an instance of plan " + planInstance . getClass ( ) . getSimpleName ( ) + " to handle goal " + node . getClass ( ) . getSimpleName ( ) ) ; agentExecutionStack . push ( planInstance ) ; } return true ;


signature:
public class IntentionSelector { /** * Manages the plan at the top of this agent ' s execution stack . If the plan has finished it is
 * removed , else it is progresses by a single { @ link PlanStep } .
 * @ param agentIndex the agent in question
 * @ param agentExecutionStack this agent ' s execution stack
 * @ param node the plan at the top of the execution stack
 * @ param toRemove the remove list to which this agent should be added if the plan has finished */
private void managePlan ( int agentIndex , Stack255 agentExecutionStack , Plan node , Set < Integer > toRemove ) { } }

implementation:
// If done then pop this plan / goal
if ( node . hasfinished ( ) ) { logger . debug ( Log . logPrefix ( agentIndex ) + " finished executing plan " + node . getClass ( ) . getSimpleName ( ) ) ; synchronized ( agentExecutionStack ) { // Pop the plan off the stack
agentExecutionStack . pop ( ) ; // Pop the goal off the stack
agentExecutionStack . pop ( ) ; if ( agentExecutionStack . isEmpty ( ) ) { // remove empty intention stacks
Agent agent = ( Agent ) GlobalState . agents . get ( agentIndex ) ; int size = agent . cleanupStacks ( ) ; // If we are left with only one stack and that is empty , then agent is idle
if ( size == 1 && agent . getExecutionStack ( ) . isEmpty ( ) ) { // Mark this agent as idle
// Main . setAgentIdle ( i , true ) ;
toRemove . add ( agentIndex ) ; } } } } else { logger . debug ( Log . logPrefix ( agentIndex ) + " is executing a step of plan " + node . getClass ( ) . getSimpleName ( ) ) ; node . step ( ) ; }


signature:
public class IntentionSelector { /** * Removes from { @ link # activeAgents } all agents flagged by external events as having become
 * inactive . */
private void removeInactiveAgents ( ) { } }

implementation: synchronized ( extToRemove ) { if ( ! extToRemove . isEmpty ( ) ) { for ( int i : extToRemove ) { activeAgents . remove ( i ) ; } extToRemove . clear ( ) ; } }


signature:
public class IntentionSelector { /** * Adds to { @ link # activeAgents } all agents flagged by external events as having become active . */
private void addActiveAgents ( ) { } }

implementation: synchronized ( extToAdd ) { if ( ! extToAdd . isEmpty ( ) ) { for ( int i : extToAdd ) { activeAgents . add ( i ) ; } extToAdd . clear ( ) ; } }


signature:
public class IntentionSelector { /** * Waits on { @ link IntentionSelector # lock } until woken up by an external message . */
private void waitOnExternalMessage ( ) { } }

implementation:
synchronized ( lock ) { while ( ! hasMessage ) { try { logger . debug ( "Pool {} is idle; will wait on external message" , poolid ) ; // Main . incrementPoolsIdle ( ) ;
isIdle = true ; Main . flagPoolIdle ( ) ; lock . wait ( ) ; isIdle = false ; // Main . decrementPoolsIdle ( ) ;
logger . debug ( "Pool {} just woke up on external message" , poolid ) ; } catch ( InterruptedException e ) { logger . error ( "Pool " + poolid + " failed to wait on external message: " , e ) ; } } hasMessage = false ; }


signature:
public class IntentionSelector { /** * Terminates this intention selector thread . */
public void shutdown ( ) { } }

implementation:
synchronized ( lock ) { logger . debug ( "Pool {} received shutdown message" , poolid ) ; shutdown = true ; hasMessage = true ; lock . notify ( ) ; // NOPMD - ignore notifyall ( ) warning
}


signature:
public class IntentionSelector { /** * and this thread is still iterating over activeagents */
public void setAgentIdle ( int agentId , boolean idle ) { } }

implementation:
// If agent is becoming active , and not already active
if ( ! idle /* & & ! activeAgents . contains ( agentId ) */
) { synchronized ( extToAdd ) { extToAdd . add ( agentId ) ; } } // If agent is becoming idle , and not already idle
if ( idle /* & & activeAgents . contains ( agentId ) */
) { synchronized ( extToRemove ) { extToRemove . add ( agentId ) ; } }


signature:
public class Board { /** * Move a disc from pin A to pin B .
 * @ param pinA the ID of the source pin
 * @ param pinB the ID of the destination pin
 * @ return true if the move was made , false otherwise */
public boolean move ( int pinA , int pinB ) { } }

implementation:
// Nothing to do if the pin number is invalid
if ( pinA < 0 || pinA >= pins . length || pinB < 0 || pinB >= pins . length ) { Log . warn ( "Invalid board pin specified " + pinA + ". Should be between 0.." + ( pins . length - 1 ) + " (inclusive)." ) ; return false ; } else if ( pins [ pinA ] . isEmpty ( ) ) { Log . warn ( "No disc on pin" + pinA ) ; return false ; } else if ( pinA == pinB ) { Log . info ( "Moving disc from pin" + pinA + " on to itself (means the board will not change)" ) ; return true ; } int discOnA = pins [ pinA ] . get ( pins [ pinA ] . size ( ) - 1 ) ; int discOnB = ( pins [ pinB ] . isEmpty ( ) ) ? Integer . MAX_VALUE : pins [ pinB ] . get ( pins [ pinB ] . size ( ) - 1 ) ; if ( discOnB < discOnA ) { Log . warn ( "Cannot move disc" + discOnA + " (pin" + pinA + ") on to smaller disc" + discOnB + " (pin" + pinB + ")" ) ; return false ; } pins [ pinB ] . add ( pins [ pinA ] . remove ( pins [ pinA ] . size ( ) - 1 ) ) ; return true ;


signature:
public class Main { /** * Program entry
 * @ param args command line arguments . */
public static void main ( String [ ] args ) { } }

implementation:
// Parse the command line options
ArgumentsLoader . parse ( args ) ; // Load the configuration
Config config = ArgumentsLoader . getConfig ( ) ; // Initialise the system with the given arguments
if ( ! init ( config ) ) { return ; } // load all extensions
if ( ! Program . loadExtensions ( config ) ) { return ; } // Start the engine
start ( config ) ; // Wait until the agents become idle
waitUntilIdle ( ) ; // finish up
finish ( ) ;


signature:
public class Main { /** * Initialises the Jill engine .
 * @ param config a valid loaded configuration
 * @ return a boolean . */
public static boolean init ( Config config ) { } }

implementation:
// Pause for key press from user if requested
if ( config . isDoPauseForUserInput ( ) ) { Program . pauseForUserInput ( ) ; } // Configure logging
Log . createLogger ( Main . LOGGER_NAME , config . getLogLevel ( ) , config . getLogFile ( ) ) ; logger = LoggerFactory . getLogger ( Main . LOGGER_NAME ) ; int numAgents = 0 ; for ( Config . AgentTypeData agentType : config . getAgents ( ) ) { numAgents += agentType . getCount ( ) ; } final int increment = 10000 ; GlobalState . reset ( ) ; GlobalState . agents = new AObjectCatalog ( "agents" , numAgents , increment ) ; // Create the central belief base
GlobalState . beliefbase = new ABeliefStore ( numAgents , config . getNumThreads ( ) ) ; long t0 ; // Create the agents
t0 = System . currentTimeMillis ( ) ; for ( Config . AgentTypeData agentType : config . getAgents ( ) ) { if ( ! ProgramLoader . loadAgent ( agentType . getClassname ( ) , agentType . getCount ( ) , GlobalState . agents ) ) { // return unsuccessful
return false ; } } long t1 = System . currentTimeMillis ( ) ; logger . info ( "Created " + GlobalState . agents . size ( ) + agentsIn + Log . formattedDuration ( t0 , t1 ) ) ; // Initialise the thread pools
Program . initIntentionSelectionPools ( numAgents , config . getNumThreads ( ) ) ; // Redirect the agent program output if specified
if ( config . getProgramOutputFile ( ) != null ) { try { writer = new PrintStream ( config . getProgramOutputFile ( ) , "UTF-8" ) ; } catch ( FileNotFoundException | UnsupportedEncodingException e ) { logger . error ( "Could not open program outout file " + config . getProgramOutputFile ( ) , e ) ; } } else { writer = System . out ; } // Initialise the intention selection threads
Program . initIntentionSelectionThreads ( config ) ; // return success
return true ;


signature:
public class Main { /** * Starts the Jill engine . Must have previously been initialised ( see { @ link # init ( Config ) } ) .
 * @ param config a valid config */
public static void start ( Config config ) { } }

implementation:
// Start the agents
long t0 = System . currentTimeMillis ( ) ; int index = 0 ; int subIndex = 0 ; for ( Config . AgentTypeData agentType : config . getAgents ( ) ) { index = subIndex ; String [ ] args = ( agentType . getArgs ( ) == null || agentType . getArgs ( ) . isEmpty ( ) ) ? new String [ 0 ] : agentType . getArgs ( ) . toArray ( new String [ agentType . getArgs ( ) . size ( ) ] ) ; for ( subIndex = index ; subIndex < index + agentType . getCount ( ) ; subIndex ++ ) { // Get the agent
Agent agent = ( Agent ) GlobalState . agents . get ( subIndex ) ; // Start the agent
agent . start ( writer , args ) ; } } long t1 = System . currentTimeMillis ( ) ; logger . info ( "Started " + GlobalState . agents . size ( ) + agentsIn + Log . formattedDuration ( t0 , t1 ) ) ; // Start the intention selection threads
Program . startIntentionSelectionThreads ( ) ;


signature:
public class Main { /** * Blocks until all agents have finished executing plans and have gone idle . */
public static void waitUntilIdle ( ) { } }

implementation:
// Wait till we are all done
long t0 = System . currentTimeMillis ( ) ; synchronized ( poolsIdle ) { while ( ! arePoolsIdle ( ) ) { try { poolsIdle . wait ( ) ; } catch ( InterruptedException e ) { logger . error ( "Failed to wait on termination condition: " + e . getMessage ( ) ) ; } } } long t1 = System . currentTimeMillis ( ) ; logger . info ( "Finished running " + GlobalState . agents . size ( ) + agentsIn + Log . formattedDuration ( t0 , t1 ) ) ;


signature:
public class Main { /** * Termiantes the Jill engine . */
public static void finish ( ) { } }

implementation:
// Terminate the extensions first
for ( JillExtension extension : GlobalState . eventHandlers ) { extension . finish ( ) ; } // Now shut down the threads
Program . shutdownIntentionSelectionThreads ( ) ; // Finish the agents
long t0 = System . currentTimeMillis ( ) ; for ( int i = 0 ; i < GlobalState . agents . size ( ) ; i ++ ) { // Get the agent
Agent agent = ( Agent ) GlobalState . agents . get ( i ) ; // Terminate the agent
agent . finish ( ) ; } // Close the writer
if ( writer != null ) { writer . close ( ) ; } long t1 = System . currentTimeMillis ( ) ; logger . info ( "Terminated " + GlobalState . agents . size ( ) + agentsIn + Log . formattedDuration ( t0 , t1 ) ) ;


signature:
public class Main { /** * Checks if the system is idle , i . e . , all the agents pools are idle
 * @ return true if idle , false otherwise */
public static boolean arePoolsIdle ( ) { } }

implementation: boolean idle = true ; for ( int i = 0 ; i < npools ; i ++ ) { idle &= ( intentionSelectors [ i ] == null ) || intentionSelectors [ i ] . isIdle ( ) ; } return idle ;


signature:
public class Main { /** * Checks if the { @ link io . github . agentsoz . jill . core . IntentionSelector } pools have finished ,
 * i . e . , all agents in the pools are idle .
 * @ return true if pools have finished , false otherwise */
public static boolean arePoolsFinished ( ) { } }

implementation: boolean finished = true ; for ( int i = 0 ; i < intentionSelectors . length ; i ++ ) { finished &= ( intentionSelectors [ i ] == null ) ; } return finished ;


signature:
public class Main { /** * Sets a bit in the agentsIdle cache , to mark if this agent is idle ( or not ) .
 * @ param agentId the agent is question
 * @ param isIdle the new idle status of this agent */
public static void setAgentIdle ( int agentId , boolean isIdle ) { } }

implementation: int poolid = poolid ( agentId ) ; intentionSelectors [ poolid ] . setAgentIdle ( agentId , isIdle ) ;


signature:
public class Main { /** * Gets the ID of the intention selection pool to which the given agent belongs .
 * @ param agentid ID of the agent for which the pool ID is being requested
 * @ return ID of the pool to which this agent belongs */
public static int poolid ( int agentid ) { } }

implementation: int poolid = agentid / poolsize ; if ( poolid + 1 > npools ) { poolid = npools - 1 ; } return poolid ;


signature:
public class JpaTranslationContext { /** * Returns the expression currently active in the building context .
 * @ param < E > the type of the expression .
 * @ return the JPA expression . */
@ SuppressWarnings ( "unchecked" ) public < E > Expression < E > pickExpression ( ) { } }

implementation: Preconditions . checkState ( this . expression != null , "No expression has been set" ) ; Expression < E > result = ( Expression < E > ) this . expression ; expression = null ; return result ;


signature:
public class JpaTranslationContext { /** * Sets the expression currently active in the building context .
 * @ param expression the expression .
 * @ param < E > the type of the expressions . */
public < E > void setExpression ( Expression < E > expression ) { } }

implementation: Preconditions . checkState ( this . expression == null , "An expression is already set" ) ; this . expression = expression ;


signature:
public class JpaUtils { /** * Create a new join or find an existing join on the specified attribute .
 * @ param attribute The attribute to join on .
 * @ param from The entity from .
 * @ return the join expression . */
public static Expression < ? > join ( String attribute , From < ? , ? > from ) { } }

implementation: Expression < ? > path ; try { String [ ] properties = attribute . split ( "\\." ) ; if ( properties . length > 1 ) { path = joinRecursively ( properties , findOrCreateJoin ( properties [ 0 ] , from ) , 1 ) . get ( properties [ properties . length - 1 ] ) ; } else { path = from . get ( properties [ 0 ] ) ; } } catch ( IllegalArgumentException e ) { throw SeedException . wrap ( e , JpaErrorCode . UNABLE_TO_CREATE_JPA_JOIN_FOR_SPECIFICATION ) . put ( "property" , attribute ) ; } return path ;


signature:
public class JpaUtils { /** * Join recursively using the split property path .
 * @ param properties property path .
 * @ param join current join .
 * @ param index index of the current property to be joined .
 * @ return the resulting join . */
private static Join < ? , ? > joinRecursively ( String [ ] properties , Join < ? , ? > join , int index ) { } }

implementation: if ( index < properties . length - 1 ) { return joinRecursively ( properties , findOrCreateJoin ( properties [ index ] , join ) , index + 1 ) ; } else { return join ; }


signature:
public class JpaUtils { /** * Find an existing join for the property or create a new join .
 * @ param property property to be joined
 * @ param from clause letting us keep track of all already existing joins
 * @ return the join */
private static Join < ? , ? > findOrCreateJoin ( String property , From < ? , ? > from ) { } }

implementation: for ( Join < ? , ? > rootJoin : from . getJoins ( ) ) { if ( rootJoin . getAttribute ( ) . getName ( ) . equals ( property ) ) { return rootJoin ; } } return from . join ( property ) ;


signature:
public class LoggerInstanceProcessor { /** * Dump managed instance of { @ link InstanceType # PROXY } type and with { @ link InstanceScope # APPLICATION } scope to container
 * logger . For managed instance of other scope / type combinations this method does nothing .
 * @ param managedClass managed class ,
 * @ param instance instance of managed class . */
@ Override public void postProcessInstance ( ManagedClassSPI managedClass , Object instance ) { } }

implementation: if ( ! managedClass . getInstanceScope ( ) . equals ( InstanceScope . APPLICATION ) ) { return ; } if ( ! managedClass . getInstanceType ( ) . equals ( InstanceType . PROXY ) ) { return ; } Class < ? > [ ] interfaceClasses = managedClass . getInterfaceClasses ( ) ; StringBuilder interfaceNames = new StringBuilder ( interfaceClasses [ 0 ] . getName ( ) ) ; for ( int i = 1 ; i < interfaceClasses . length ; ++ i ) { interfaceNames . append ( ", " ) ; interfaceNames . append ( interfaceClasses [ i ] . getName ( ) ) ; } log . debug ( "Create managed container proxy:\r\n" + "\t- implementation: %s\r\n" + "\t- interface(s): %s\r\n" + "\t- scope: %s\r\n" + "\t- type: %s\r\n" + "\t- transactional: %s\r\n" + "\t- remote: %s" , managedClass . getImplementationClass ( ) , interfaceNames . toString ( ) , managedClass . getInstanceScope ( ) , managedClass . getInstanceType ( ) , managedClass . isTransactional ( ) , managedClass . isRemotelyAccessible ( ) ) ;


signature:
public class PartialResponse { /** * Indicates whether the response reaches the end of the elements available
 * on the server .
 * @ return < code > true < / code > if there are no more elements . */
public boolean isEndReached ( ) { } }

implementation:
if ( to == null || from == null ) { // No range specified , must be complete response
return true ; } if ( length == null ) { // No lenth specified , can ' t be end
return false ; } return to == length - 1 ;


signature:
public class MultipartFormArgumentsReader { /** * Parse multipart form from HTTP request , create object instance of requested type and fill it with form field value ( s ) . If
 * formal type is a stream store it to local thread so that to be able to close it after arguments processed by application
 * code .
 * @ param httpRequest HTTP request ,
 * @ param formalParameters formal parameter types .
 * @ return single item arguments array .
 * @ throws IOException if reading from HTTP request input stream fails .
 * @ throws IllegalArgumentException if formal parameters does not contain exactly one type .
 * @ throws IllegalArgumentException if formal parameter type is parameterized .
 * @ throws IllegalArgumentException if HTTP request does not contain a valid multipart form . */
@ Override public Object [ ] read ( HttpServletRequest httpRequest , Type [ ] formalParameters ) throws IOException , IllegalArgumentException { } }

implementation:
if ( formalParameters . length != 1 ) { throw new IllegalArgumentException ( "Bad parameters count. Should be exactly one but is |%d|." , formalParameters . length ) ; } if ( formalParameters [ 0 ] instanceof ParameterizedType ) { throw new IllegalArgumentException ( "Parameterized type |%s| is not supported." , formalParameters [ 0 ] ) ; } Class < ? > type = ( Class < ? > ) formalParameters [ 0 ] ; Object [ ] arguments = new Object [ 1 ] ; if ( type . equals ( Form . class ) ) { arguments [ 0 ] = new FormImpl ( httpRequest ) ; } else if ( type . equals ( FormIterator . class ) ) { arguments [ 0 ] = new FormIteratorImpl ( httpRequest ) ; } else if ( type . equals ( UploadedFile . class ) ) { Form form = new FormImpl ( httpRequest ) ; // Form # getUploadedFile ( ) throws IlegalArgumentException if form has not a single file upload part
arguments [ 0 ] = form . getUploadedFile ( ) ; } else if ( type . equals ( UploadStream . class ) ) { threadLocal . set ( ( Closeable ) ( arguments [ 0 ] = getUploadStream ( httpRequest , formalParameters ) ) ) ; } else if ( type . equals ( InputStream . class ) ) { threadLocal . set ( ( Closeable ) ( arguments [ 0 ] = getUploadStream ( httpRequest , formalParameters ) . openStream ( ) ) ) ; } else { arguments [ 0 ] = new FormObject ( httpRequest , type ) . getValue ( ) ; } return arguments ;


signature:
public class MultipartFormArgumentsReader { /** * Get upload stream from given HTTP request . This method expects on HTTP request a multipart form with a single part of
 * byte stream type . Returns an upload stream instance wrapping the form stream part .
 * @ param httpRequest HTTP request ,
 * @ param formalParameters used only for exception message .
 * @ return upload stream .
 * @ throws IOException if reading form HTTP request fails .
 * @ throws IllegalArgumentException if there is no valid multipart form on HTTP request . */
private static UploadStream getUploadStream ( HttpServletRequest httpRequest , Type [ ] formalParameters ) throws IOException { } }

implementation: FormIterator form = new FormIteratorImpl ( httpRequest ) ; if ( ! form . hasNext ( ) ) { throw new IllegalArgumentException ( "Empty form." ) ; } Part part = form . next ( ) ; if ( ! ( part instanceof UploadStream ) ) { throw new IllegalArgumentException ( "Illegal form. Expected uploaded stream but got field |%s|." , part . getName ( ) ) ; } return ( UploadStream ) part ;


signature:
public class AliasHelper { /** * Looks up a class in the alias map . If < code > className < / code > exists as
 * an alias , it is resolved and returned . If the alias doesn ' t exist , the
 * original String is returned .
 * @ param className class name to look up
 * @ return resolved name of the alias */
public String getClazz ( final String className ) { } }

implementation: String realName = className ; while ( classMapper . containsKey ( realName ) ) { realName = classMapper . get ( realName ) ; } return realName ;


signature:
public class RestServlet { /** * Performed super - initialization by { @ link AppServlet # init ( ServletConfig ) } and loads REST methods cache . A REST method is a
 * remotely accessible method that does not return a { @ link Resource } . Map storage key is generated by
 * { @ link # key ( ManagedMethodSPI ) } based on managed class and REST method request paths and is paired with retrieval key -
 * { @ link # key ( String ) } , generated from request path info when method invocation occurs .
 * @ param config servlet configuration object .
 * @ throws UnavailableException if tiny container is not properly initialized . */
@ Override public void init ( ServletConfig config ) throws UnavailableException { } }

implementation: super . init ( config ) ; for ( ManagedMethodSPI managedMethod : container . getManagedMethods ( ) ) { if ( ! managedMethod . isRemotelyAccessible ( ) ) { continue ; } if ( ! Types . isKindOf ( managedMethod . getReturnType ( ) , Resource . class ) ) { restMethods . put ( key ( managedMethod ) , managedMethod ) ; } }


signature:
public class RestServlet { /** * Handle request for a REST resource . Locate REST method based on request path info , execute method and serialize back to
 * client returned value , if any . See class description for general behavior .
 * @ param context request context .
 * @ throws IOException if reading from HTTP request or writing to HTTP response fail . */
@ Override protected void handleRequest ( RequestContext context ) throws IOException { } }

implementation:
HttpServletRequest httpRequest = context . getRequest ( ) ; HttpServletResponse httpResponse = context . getResponse ( ) ; ArgumentsReader argumentsReader = null ; Object value = null ; ManagedMethodSPI method = null ; try { method = restMethods . get ( key ( httpRequest . getPathInfo ( ) ) ) ; if ( method == null ) { throw new NoSuchMethodException ( ) ; } Type [ ] formalParameters = method . getParameterTypes ( ) ; argumentsReader = argumentsReaderFactory . getArgumentsReader ( httpRequest , formalParameters ) ; Object [ ] arguments = argumentsReader . read ( httpRequest , formalParameters ) ; Object instance = container . getInstance ( method . getDeclaringClass ( ) ) ; value = method . invoke ( instance , arguments ) ; } catch ( AuthorizationException e ) { sendUnauthorized ( context ) ; return ; } catch ( NoSuchMethodException e ) { sendNotFound ( context , e ) ; return ; } catch ( IllegalArgumentException e ) { // there are opinions that 422 UNPROCESSABLE ENTITY is more appropriate response
// see https : / / httpstatuses . com / 422
sendBadRequest ( context ) ; return ; } catch ( InvocationException e ) { sendError ( context , e ) ; return ; } finally { if ( argumentsReader != null ) { argumentsReader . clean ( ) ; } } httpResponse . setCharacterEncoding ( "UTF-8" ) ; if ( method . isVoid ( ) ) { // expected servlet container behavior :
// since there is nothing written to respond to output stream , container either set content length to zero
// or closes connection signaling end of content
httpResponse . setStatus ( HttpServletResponse . SC_NO_CONTENT ) ; return ; } // expected servlet container behavior :
// if client request connection header is close container uses an internal buffer for serialized JSON , add content
// length response header based on buffer size and closes connection
// if client request connection header is not explicitly set to close , container uses an internal buffer for serialized
// JSON but with limited capacity ; if capacity is not exceeded set response content length ; if capacity is exceeded
// switch to chunked transfer
ContentType contentType = valueWriterFactory . getContentTypeForValue ( value ) ; httpResponse . setStatus ( HttpServletResponse . SC_OK ) ; httpResponse . setContentType ( contentType . getValue ( ) ) ; ValueWriter valueWriter = valueWriterFactory . getValueWriter ( contentType ) ; valueWriter . write ( httpResponse , value ) ;


signature:
public class RestServlet { /** * Generate retrieval key for REST methods cache . This key is used by request routing logic to locate REST method about to
 * invoke . It is based on request path extracted from request URI , see { @ link RequestPreprocessor } and
 * { @ link RequestContext # getRequestPath ( ) } - and should be identical with storage key .
 * Retrieval key syntax is identical with storage key but is based on request path , that on its turn is extracted from
 * request URI . In fact this method just trim query parameters and extension , if any .
 * < pre >
 * request - path = [ " / " resource ] " / " sub - resource [ " ? " query - string ]
 * key = [ " / " resource ] " / " sub - resource
 * resource = managed class request - path
 * sub - resource = managed method request - path
 * < / pre >
 * @ param requestPath request path identify REST resource to retrieve .
 * @ return REST method key . */
private static String key ( String requestPath ) { } }

implementation: int queryParametersIndex = requestPath . lastIndexOf ( '?' ) ; if ( queryParametersIndex == - 1 ) { queryParametersIndex = requestPath . length ( ) ; } int extensionIndex = requestPath . lastIndexOf ( '.' , queryParametersIndex ) ; if ( extensionIndex == - 1 ) { extensionIndex = queryParametersIndex ; } return requestPath . substring ( 0 , extensionIndex ) ;


signature:
public class ContentType { /** * Create a content type instance suitable to represent requested file . It is a trivial a approach using a map of common
 * used file extension . Recognizes only couple , most used types ; if extension is not recognized returns { @ link # TEXT _ HTML } .
 * @ param file source file .
 * @ return content type discovered for requested file .
 * @ throws IllegalArgumentException if file parameter is null . */
public static ContentType forFile ( File file ) { } }

implementation: Params . notNull ( file , "File" ) ; ContentType contentType = FILE_TYPES . get ( Files . getExtension ( file ) ) ; if ( contentType == null ) { log . debug ( "Unknown content type for |%s|. Replace with default |%s|." , file , TEXT_HTML ) ; contentType = TEXT_HTML ; } return contentType ;


signature:
public class ContentType { /** * Parses content type value and returns newly created instance . Given value should obey syntax described by this class .
 * This factory method just delegates { @ link # ContentType ( String ) } . If < code > value < / code > argument is null uses
 * { @ link # APPLICATION _ JSON } as default .
 * @ param value content type string value with syntax described by this class , possible null .
 * @ return content type instance for given value .
 * @ throws SyntaxException if < code > value < / code > does not respect syntax described by this class . */
public static ContentType valueOf ( String value ) { } }

implementation: if ( value == null ) { return ContentType . APPLICATION_JSON ; } return new ContentType ( value ) ;


signature:
public class ContentType { /** * Test if content type has a parameter with requested name and value .
 * @ param name parameter name ,
 * @ param value parameter value .
 * @ return true if content type has a parameter with requested name and value .
 * @ throws IllegalArgumentException if < code > name < / code > argument is null or empty .
 * @ throws IllegalArgumentException if < code > value < / code > argument is null or empty . */
public boolean hasParameter ( String name , String value ) { } }

implementation: Params . notNullOrEmpty ( name , "Parameter name" ) ; Params . notNullOrEmpty ( value , "Parameter value" ) ; return value . equals ( parameters . get ( name ) ) ;


signature:
public class ContentType { /** * Get parameter value or null if parameter does not exist .
 * @ param name parameter name .
 * @ return parameter value , possible null .
 * @ throws IllegalArgumentException if < code > name < / code > argument is null or empty . */
public String getParameter ( String name ) { } }

implementation: Params . notNullOrEmpty ( name , "Parameter name" ) ; return parameters . get ( name ) ;


signature:
public class ContentType { /** * Parse content type parameters . Given parameters expression should be valid accordingly grammar from class description ; it
 * should not start with parameters separator , that is , semicolon .
 * @ param expression content type parameters expression .
 * @ return non empty parameters map .
 * @ throws SyntaxException if parameters expression is not valid . */
private static Map < String , String > parseParameters ( String expression ) { } }

implementation:
// charset = UTF - 8
Map < String , String > parameters = new HashMap < > ( ) ; int parametersSeparatorIndex = 0 ; for ( ; ; ) { int valueSeparatorIndex = expression . indexOf ( '=' , parametersSeparatorIndex ) ; if ( valueSeparatorIndex == - 1 ) { break ; } String name = expression . substring ( parametersSeparatorIndex , valueSeparatorIndex ) . trim ( ) ; ++ valueSeparatorIndex ; parametersSeparatorIndex = expression . indexOf ( ';' , valueSeparatorIndex ) ; if ( parametersSeparatorIndex == - 1 ) { parametersSeparatorIndex = expression . length ( ) ; } if ( valueSeparatorIndex == parametersSeparatorIndex ) { throw new SyntaxException ( "Invalid content type parameters |%s|. Value is empty." , expression ) ; } if ( parameters . put ( name , expression . substring ( valueSeparatorIndex , parametersSeparatorIndex ) . trim ( ) ) != null ) { throw new SyntaxException ( "Invalid content type parameters |%s|. Name override |%s|." , expression , name ) ; } ++ parametersSeparatorIndex ; } if ( parameters . isEmpty ( ) ) { throw new SyntaxException ( "Invalid content type parameters |%s|. Missing name/value separator." , expression ) ; } return parameters ;


signature:
public class TransactionalResourceImpl { /** * Configure underlying transaction manager .
 * @ param config configuration object .
 * @ throws ConfigException if given configuration object is not valid , as requested by transaction manager implementation .
 * @ throws Exception if configuration of the transaction manager implementation fails . */
@ Override public void config ( Config config ) throws Exception { } }

implementation: log . trace ( "config(Config.Element)" ) ; log . debug ( "Configure transaction manager |%s|." , transactionManager . getClass ( ) ) ; transactionManager . config ( config ) ;


signature:
public class AbstractGenerator { /** * Returns the target file for a given artifact type and filename . This method takes care about eventually creating non existing
 * directories or protect existing files to be overridden .
 * @ param artifactName
 * Type of the artifact to create - This has to refer to an existing entry in the configuration ( Like ' & lt ; artifact
 * name = " < i > artifactName < / i > " . . & gt ; ' ) .
 * @ param filename
 * Name of the target file ( without a path ) .
 * @ param logInfo
 * Addition information to log .
 * @ return File to write to or NULL if nothing should be written . */
protected final GeneratedFile getTargetFile ( final String artifactName , final String filename , final String logInfo ) { } }

implementation:
final Folder folder = getGeneratorConfig ( ) . findTargetFolder ( artifactName ) ; final File dir = folder . getCanonicalDir ( ) ; final File file = new File ( dir , filename ) ; // Make sure the folder exists
if ( ! dir . exists ( ) ) { if ( folder . isCreate ( ) ) { dir . mkdirs ( ) ; } else { throw new IllegalStateException ( "Directory '" + dir + "' does not exist, but configuration does not allow creation: " + "<folder name=\"" + folder . getName ( ) + "\" create=\"false\" ... />" ) ; } } // Make sure the parent directory for the file exists
if ( ! file . getParentFile ( ) . exists ( ) ) { file . getParentFile ( ) . mkdirs ( ) ; } if ( file . exists ( ) && ! folder . overrideAllowed ( file ) ) { // Skip file because override is not allowed
return new GeneratedFile ( file , logInfo , true ) ; } return new GeneratedFile ( file , logInfo ) ;


signature:
public class AbstractGenerator { /** * Writes a generated artifact to a file .
 * @ param artifact
 * Artifact to persist .
 * @ throws GenerateException
 * Error writing the artifact . */
protected final void write ( @ NotNull final GeneratedArtifact artifact ) throws GenerateException { } }

implementation: Contract . requireArgNotNull ( "artifact" , artifact ) ; final GeneratedFile genFile = getTargetFile ( artifact . getName ( ) , artifact . getPathAndName ( ) , null ) ; if ( genFile . isSkip ( ) ) { LOG . debug ( "Omitted already existing file: {} [{}]" , genFile , artifact ) ; } else { LOG . debug ( "Writing file:  {} [{}]" , genFile , artifact ) ; try { final OutputStream out = new BufferedOutputStream ( new FileOutputStream ( genFile . getTmpFile ( ) ) ) ; try { out . write ( artifact . getData ( ) ) ; } finally { out . close ( ) ; } genFile . persist ( ) ; } catch ( final IOException ex ) { throw new GenerateException ( "Error writing artifact '" + artifact + "' to '" + artifact . getPathAndName ( ) + "'!" , ex ) ; } }


signature:
public class InstanceFieldsInitializationProcessor { /** * Initialize instance fields from managed class configuration object .
 * @ param managedClass managed class ,
 * @ param instance instance of managed class .
 * @ throws ConverterException if configured value cannot be converted to field type .
 * @ throws BugError if attempt to assign instance field to not POJO type . */
@ Override public void postProcessInstance ( ManagedClassSPI managedClass , Object instance ) { } }

implementation: Config config = managedClass . getConfig ( ) ; if ( config == null ) { return ; } List < Config > fields = config . findChildren ( "instance-field" ) ; if ( ! fields . isEmpty ( ) && ! InstanceType . POJO . equals ( managedClass . getInstanceType ( ) ) ) { throw new BugError ( "Cannot assign instance field on non %s type." , InstanceType . POJO ) ; } for ( Config field : fields ) { Classes . setFieldValue ( instance , field . getAttribute ( "name" ) , field . getAttribute ( "value" ) ) ; }


signature:
public class ManagedClass { /** * Scan annotations for managed classes that requires implementation . Annotations are processed only for managed classes
 * that have { @ link # implementationClass } that is primary source scanned for annotation . If an annotation is not present
 * into implementation class try to find it on interface ( s ) . See < a href = " # annotations " > Annotations < / a > section from class
 * description .
 * @ throws BugError for insane conditions . */
private void scanAnnotations ( ) { } }

implementation:
// set remote type and request URI path from @ Remote , @ Controller or @ Service
boolean remoteType = false ; Controller controllerAnnotation = getAnnotation ( implementationClass , Controller . class ) ; if ( controllerAnnotation != null ) { remoteType = true ; requestPath = controllerAnnotation . value ( ) ; } Service serviceAnnotation = getAnnotation ( implementationClass , Service . class ) ; if ( serviceAnnotation != null ) { remoteType = true ; requestPath = serviceAnnotation . value ( ) ; } Remote remoteAnnotation = getAnnotation ( implementationClass , Remote . class ) ; if ( remoteAnnotation != null ) { remoteType = true ; } RequestPath requestPathAnnotation = getAnnotation ( implementationClass , RequestPath . class ) ; if ( requestPathAnnotation != null ) { requestPath = requestPathAnnotation . value ( ) ; } if ( requestPath != null && requestPath . isEmpty ( ) ) { requestPath = null ; } if ( remoteType ) { remotelyAccessible = true ; } // set transactional and immutable type
boolean transactionalType = hasAnnotation ( implementationClass , Transactional . class ) ; boolean immutableType = hasAnnotation ( implementationClass , Immutable . class ) ; if ( ! transactionalType && immutableType ) { throw new BugError ( "@Immutable annotation without @Transactional on class |%s|." , implementationClass . getName ( ) ) ; } if ( transactionalType && ! instanceType . isPROXY ( ) ) { throw new BugError ( "@Transactional requires |%s| type but found |%s| on |%s|." , InstanceType . PROXY , instanceType , implementationClass ) ; } Class < ? extends Interceptor > classInterceptor = getInterceptorClass ( implementationClass ) ; boolean publicType = hasAnnotation ( implementationClass , Public . class ) ; // managed classes does not support public inheritance
for ( Method method : implementationClass . getDeclaredMethods ( ) ) { final int modifiers = method . getModifiers ( ) ; if ( Modifier . isStatic ( modifiers ) || ! Modifier . isPublic ( modifiers ) ) { // scans only public and non - static methods
continue ; } Method interfaceMethod = getInterfaceMethod ( method ) ; ManagedMethod managedMethod = null ; boolean remoteMethod = hasAnnotation ( method , Remote . class ) ; if ( ! remoteMethod ) { remoteMethod = remoteType ; } if ( hasAnnotation ( method , Local . class ) ) { if ( ! remoteMethod ) { throw new BugError ( "@Local annotation on not remote method |%s|." , method ) ; } remoteMethod = false ; } if ( remoteMethod ) { // if at least one owned managed method is remote this managed class become remote too
remotelyAccessible = true ; } // load method interceptor annotation and if missing uses class annotation ; is legal for both to be null
Class < ? extends Interceptor > methodInterceptor = getInterceptorClass ( method ) ; if ( methodInterceptor == null ) { methodInterceptor = classInterceptor ; } // if method is intercepted , either by method or class annotation , create intercepted managed method
if ( methodInterceptor != null ) { if ( ! instanceType . isPROXY ( ) && ! remotelyAccessible ) { throw new BugError ( "@Intercepted method |%s| supported only on PROXY type or remote accessible classes." , method ) ; } managedMethod = new ManagedMethod ( this , methodInterceptor , interfaceMethod ) ; } // handle remote accessible methods
boolean publicMethod = hasAnnotation ( method , Public . class ) ; if ( publicMethod && ! remotelyAccessible ) { throw new BugError ( "@Public annotation on not remote method |%s|." , method ) ; } if ( ! publicMethod ) { publicMethod = publicType ; } if ( hasAnnotation ( method , Private . class ) ) { if ( ! remotelyAccessible ) { throw new BugError ( "@Private annotation on not remote method |%s|." , method ) ; } publicMethod = false ; } RequestPath methodPath = getAnnotation ( method , RequestPath . class ) ; if ( ! remotelyAccessible && methodPath != null ) { throw new BugError ( "@MethodPath annotation on not remote method |%s|." , method ) ; } if ( remoteMethod ) { if ( managedMethod == null ) { managedMethod = new ManagedMethod ( this , interfaceMethod ) ; } managedMethod . setRequestPath ( methodPath != null ? methodPath . value ( ) : null ) ; managedMethod . setRemotelyAccessible ( remoteMethod ) ; managedMethod . setAccess ( publicMethod ? Access . PUBLIC : Access . PRIVATE ) ; } // handle declarative transaction
// 1 . allow transactional only on PROXY
// 2 . do not allow immutable on method if not transactional
// 3 . do not allow mutable on method if not transactional
// 4 . if PROXY create managed method if not already created from above remote method logic
if ( ! transactionalType ) { transactionalType = hasAnnotation ( method , Transactional . class ) ; } if ( transactionalType ) { transactional = true ; if ( ! instanceType . isPROXY ( ) ) { throw new BugError ( "@Transactional requires |%s| type but found |%s|." , InstanceType . PROXY , instanceType ) ; } } boolean immutable = hasAnnotation ( method , Immutable . class ) ; if ( immutable && ! transactional ) { log . debug ( "@Immutable annotation without @Transactional on method |%s|." , method ) ; } if ( ! immutable ) { immutable = immutableType ; } if ( hasAnnotation ( method , Mutable . class ) ) { if ( ! transactional ) { log . debug ( "@Mutable annotation without @Transactional on method |%s|." , method ) ; } immutable = false ; } if ( instanceType . isPROXY ( ) && managedMethod == null ) { managedMethod = new ManagedMethod ( this , interfaceMethod ) ; } if ( transactional ) { managedMethod . setTransactional ( true ) ; managedMethod . setImmutable ( immutable ) ; } // handle asynchronous mode
// 1 . instance type should be PROXY or managed class should be flagged for remote access
// 2 . transactional method cannot be executed asynchronously
// 3 . asynchronous method should be void
boolean asynchronousMethod = hasAnnotation ( method , Asynchronous . class ) ; if ( asynchronousMethod ) { if ( ! instanceType . isPROXY ( ) && ! remotelyAccessible ) { throw new BugError ( "Not supported instance type |%s| for asynchronous method |%s|." , instanceType , method ) ; } if ( transactional ) { throw new BugError ( "Transactional method |%s| cannot be executed asynchronous." , method ) ; } if ( ! Types . isVoid ( method . getReturnType ( ) ) ) { throw new BugError ( "Asynchronous method |%s| must be void." , method ) ; } // at this point either instance type is PROXY or remote flag is true ; checked by above bug error
// both conditions has been already processed with managed method creation
// so managed method must be already created
managedMethod . setAsynchronous ( asynchronousMethod ) ; } Cron cronMethod = getAnnotation ( method , Cron . class ) ; if ( cronMethod != null ) { // if ( ! instanceType . isPROXY ( ) ) {
// throw new BugError ( " Not supported instance type | % s | for cron method | % s | . " , instanceType , method ) ;
if ( remotelyAccessible ) { throw new BugError ( "Remote accessible method |%s| cannot be executed by cron." , method ) ; } if ( transactional ) { throw new BugError ( "Transactional method |%s| cannot be executed by cron." , method ) ; } if ( ! Types . isVoid ( method . getReturnType ( ) ) ) { throw new BugError ( "Cron method |%s| must be void." , method ) ; } if ( managedMethod == null ) { managedMethod = new ManagedMethod ( this , interfaceMethod ) ; } managedMethod . setCronExpression ( cronMethod . value ( ) ) ; cronMethodsPool . add ( managedMethod ) ; autoInstanceCreation = true ; } // store managed method , if created , to managed methods pool
if ( managedMethod != null ) { methodsPool . put ( interfaceMethod , managedMethod ) ; if ( managedMethod . isRemotelyAccessible ( ) && netMethodsPool . put ( method . getName ( ) , managedMethod ) != null ) { throw new BugError ( "Overloading is not supported for net method |%s|." , managedMethod ) ; } } } for ( Field field : implementationClass . getDeclaredFields ( ) ) { ContextParam contextParam = field . getAnnotation ( ContextParam . class ) ; if ( contextParam != null ) { field . setAccessible ( true ) ; contextParamFields . put ( contextParam . value ( ) , field ) ; } }