public AObject find(String name) {
    for (int i = 0; i < nextid; i++) {
      if (objects[i].getName().equals(name)) {
        return objects[i];
      }
    }
    return null;
  }

public AObject find ( String name ) { for ( int i = 0 ; i < nextid ; i ++ ) { if ( objects [ i ] . getName ( ) . equals ( name ) ) { return objects [ i ] ; } } return null ; }

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

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 .


public void push(AObject obj) {
    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;
  }

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

Pushes a new object to the top of the catalog.

@param obj the object to add

Pushes a new object to the top of the catalog .


public Object get(int idx) {
    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];
  }

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

Gets the object at the given index in the catalog .


public boolean push(Object obj) {
    // 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;
  }

public
boolean
push
(
Object
obj
)
{
// 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
;
}

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

Pushes an object on to the top of the stack .


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

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

Pops the Object at the top of the stack.

@return the Object, or null if the stack is empty

Pops the Object at the top of the stack .


public static String getType(Object obj) {
    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;
  }

public static String getType ( Object obj ) { 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 ; }

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


private static boolean match(Belief belief, AQuery query) {
    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;
  }

private
static
boolean
match
(
Belief
belief
,
AQuery
query
)
{
assert
(
belief
!=
)
;
assert
(
query
!=
)
;
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
;
}

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

Checks if the given query run on the given belief returns a match .


public static void main(String[] args) throws BeliefBaseException {
    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");
      }
    }
  }

public
static
void
main
(
String
[
]
args
)
throws
BeliefBaseException
{
BeliefBase
bb
=
new
ABeliefStore
(
100
,
4
)
;
bb
.
eval
(
0
,
"neighbour.age < 31"
)
;
Console
console
=
System
.
console
(
)
;
if
(
console
==
)
{
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"
)
;
}
}
}

Sample program to test pattern matching.

@param args command line arguments
@throws BeliefBaseException thrown if something went wrong

Sample program to test pattern matching .


public static byte[] toBytes(String str) {
    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;
  }

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)

Encodes the String str into a sequence of bytes using the character set specified in CHARSET storing the result into a new byte array .


private void post(Stack255 stack, Goal goal) {
    synchronized (stack) {
      logger.debug("{} posting goal {}", Log.logPrefix(getId()), goal.getClass().getSimpleName());
      stack.push(goal);
      Main.setAgentIdle(getId(), false);
    }
    Main.flagMessageTo(Main.poolid(getId()));
  }

private
void
post
(
Stack255
stack
,
Goal
goal
)
{
synchronized
(
stack
)
{
logger
.
debug
(
"{} posting goal {}"
,
Log
.
logPrefix
(
getId
(
)
)
,
goal
.
getClass
(
)
.
getSimpleName
(
)
)
;
stack
.
push
(
goal
)
;
Main
.
setAgentIdle
(
getId
(
)
,
false
)
;
}
Main
.
flagMessageTo
(
Main
.
poolid
(
getId
(
)
)
)
;
}

Push the given goal to the given stack.
@param stack the stack to push to new goal to
@param goal the goal to push

Push the given goal to the given stack .


public boolean send(int id, Goal msg) {
    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;
  }

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(String name, Goal msg) {
    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;
  }

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 byte[] getGoals() {
    byte[] arr = new byte[goals.length];
    System.arraycopy(goals, 0, arr, 0, arr.length);
    return arr;
  }

public byte [ ] getGoals ( ) { byte [ ] arr = new byte [ goals . length ] ; System . arraycopy ( goals , 0 , arr , 0 , arr . length ) ; return arr ; }

Returns this agent's top level goals.

@return {@link io.github.agentsoz.jill.lang.Agent#goals}


public void createBeliefSet(String name, BeliefSetField[] fields) throws BeliefBaseException {
    beliefbase.createBeliefSet(getId(), name, fields);
  }

public void createBeliefSet ( String name , BeliefSetField [ ] fields ) throws BeliefBaseException { beliefbase . createBeliefSet ( getId ( ) , name , fields ) ; }

Creates a new belief set with the given fields.

Example usage:

BeliefSetField[] fields = {new BeliefSetField("name", String.class, true),
new BeliefSetField("gender", String.class, false),};
createBeliefSet("neighbour", fields);

@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})

Creates a new belief set with the given fields .


public void addBelief(String beliefsetName, Object... tuple) throws BeliefBaseException {
    beliefbase.addBelief(getId(), beliefsetName, tuple);
  }

public void addBelief ( String beliefsetName , Object ... tuple ) throws BeliefBaseException { beliefbase . addBelief ( getId ( ) , beliefsetName , tuple ) ; }

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})

Adds a new belief to the specified belief set .


public boolean eval(String query) throws BeliefBaseException {
    boolean result = beliefbase.eval(getId(), query);
    lastresult = (result) ? beliefbase.query(getId(), query) : new HashSet<Belief>();
    return result;
  }

public boolean eval ( String query ) throws BeliefBaseException { boolean result = beliefbase . eval ( getId ( ) , query ) ; lastresult = ( result ) ? beliefbase . query ( getId ( ) , query ) : new HashSet < Belief > ( ) ; return result ; }

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

Evaluates the given query against this agent s belief base .


public void suspend(boolean val) {
    Main.setAgentIdle(getId(), val);
    Main.flagMessageTo(Main.poolid(getId()));
  }

public void suspend ( boolean val ) { Main . setAgentIdle ( getId ( ) , val ) ; Main . flagMessageTo ( Main . poolid ( getId ( ) ) ) ; }

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

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 .


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

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

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

Gets the field of this belief set that has the given name .


private void registerNeighbours(Random rand, int count) throws BeliefBaseException {
    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");
    }
  }

private void registerNeighbours ( Random rand , int count ) throws BeliefBaseException { 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" ) ; } }

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

Helper function to add beliefs about neighbours .


private static String buildName(boolean male) {
    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();
  }

private static String buildName ( boolean male ) { 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 ( ) ; }

Builds a new name.

@param male specifies whether the name should be for a male or female
@return the constructed name


public void run() {
    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);
  }


private boolean isStackValid(Agent agent, Stack255 agentExecutionStack) {
    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;
  }

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

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 .


private void removeFinishedAgents(Set<Integer> toRemove) {
    if (!toRemove.isEmpty()) {
      for (int i : toRemove) {
        activeAgents.remove(i);
      }
      toRemove.clear();
    }
  }

private void removeFinishedAgents ( Set < Integer > toRemove ) { if ( ! toRemove . isEmpty ( ) ) { for ( int i : toRemove ) { activeAgents . remove ( i ) ; } toRemove . clear ( ) ; } }

Removes the given list of agents from the list of active agents.

@param toRemove the list of agent IDs to remove

Removes the given list of agents from the list of active agents .


private boolean manageGoal(int agentIndex, Agent agent, Stack255 agentExecutionStack, Goal node) {
    // 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;
  }

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

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 .


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

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

Terminates this intention selector thread.

Terminates this intention selector thread .


public void setAgentIdle(int agentId, boolean idle) {
    // 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);
      }
    }
  }

and this thread is still iterating over activeagents


public boolean move(int pinA, int pinB) {
    // 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;
  }

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 static boolean init(Config config) {

    // 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;
  }

Initialises the Jill engine.

@param config a valid loaded configuration
@return a boolean.


public static void waitUntilIdle() {
    // 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));
  }

Blocks until all agents have finished executing plans and have gone idle.

Blocks until all agents have finished executing plans and have gone idle .


public static void finish() {
    // 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));
  }

public
static
void
finish
(
)
{
// 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
!=
)
{
writer
.
close
(
)
;
}
long
t1
=
System
.
currentTimeMillis
(
)
;
logger
.
info
(
"Terminated "
+
GlobalState
.
agents
.
size
(
)
+
agentsIn
+
Log
.
formattedDuration
(
t0
,
t1
)
)
;
}


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

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

Checks if the system is idle, i.e., all the agents pools are idle

@return true if idle, false otherwise

Checks if the system is idle i . e . all the agents pools are idle


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

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

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

Gets the ID of the intention selection pool to which the given agent belongs .


@SuppressWarnings("unchecked")
    public <E> Expression<E> pickExpression() {
        Preconditions.checkState(this.expression != null, "No expression has been set");
        Expression<E> result = (Expression<E>) this.expression;
        expression = null;
        return result;
    }

@
SuppressWarnings
(
"unchecked"
)
public
<
E
>
Expression
<
E
>
pickExpression
(
)
{
Preconditions
.
checkState
(
this
.
expression
!=
,
"No expression has been set"
)
;
Expression
<
E
>
result
=
(
Expression
<
E
>
)
this
.
expression
;
expression
=
;
return
result
;
}

Returns the expression currently active in the building context.

@param <E> the type of the expression.
@return the JPA expression.

Returns the expression currently active in the building context .


public <E> void setExpression(Expression<E> expression) {
        Preconditions.checkState(this.expression == null, "An expression is already set");
        this.expression = expression;
    }

public
<
E
>
void
setExpression
(
Expression
<
E
>
expression
)
{
Preconditions
.
checkState
(
this
.
expression
==
,
"An expression is already set"
)
;
this
.
expression
=
expression
;
}

Sets the expression currently active in the building context.

@param expression the expression.
@param <E>        the type of the expressions.

Sets the expression currently active in the building context .


public static Expression<?> join(String attribute, From<?, ?> from) {
        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;
    }

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.

Create a new join or find an existing join on the specified attribute .


private static Join<?, ?> joinRecursively(String[] properties, Join<?, ?> join, int index) {
        if (index < properties.length - 1) {
            return joinRecursively(properties, findOrCreateJoin(properties[index], join), index + 1);
        } else {
            return join;
        }
    }

private static Join < ? , ? > joinRecursively ( String [ ] properties , Join < ? , ? > join , int index ) { if ( index < properties . length - 1 ) { return joinRecursively ( properties , findOrCreateJoin ( properties [ index ] , join ) , index + 1 ) ; } else { return join ; } }

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.

Join recursively using the split property path .


private static Join<?, ?> findOrCreateJoin(String property, From<?, ?> from) {
        for (Join<?, ?> rootJoin : from.getJoins()) {
            if (rootJoin.getAttribute().getName().equals(property)) {
                return rootJoin;
            }
        }
        return from.join(property);
    }

private static Join < ? , ? > findOrCreateJoin ( String property , From < ? , ? > from ) { for ( Join < ? , ? > rootJoin : from . getJoins ( ) ) { if ( rootJoin . getAttribute ( ) . getName ( ) . equals ( property ) ) { return rootJoin ; } } return from . join ( property ) ; }

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

Find an existing join for the property or create a new join .


public boolean isEndReached() {
        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;
    }

Indicates whether the response reaches the end of the elements available
on the server.

@return true if there are no more elements.

Indicates whether the response reaches the end of the elements available on the server .


private static UploadStream getUploadStream(HttpServletRequest httpRequest, Type[] formalParameters) throws IOException {
		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;
	}

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.

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 .


@Override
	protected void handleRequest(RequestContext context) throws IOException {
		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);
	}

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.

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 .


public boolean hasParameter(String name, String value) {
		Params.notNullOrEmpty(name, "Parameter name");
		Params.notNullOrEmpty(value, "Parameter value");
		return value.equals(parameters.get(name));
	}

public
boolean
hasParameter
(
String
name
,
String
value
)
{
Params
.
notNullOrEmpty
(
name
,
"Parameter name"
)
;
Params
.
notNullOrEmpty
(
value
,
"Parameter value"
)
;
return
value
.
equals
(
parameters
.
get
(
name
)
)
;
}

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 name argument is null or empty.
@throws IllegalArgumentException if value argument is null or empty.

Test if content type has a parameter with requested name and value .


public String getParameter(String name) {
		Params.notNullOrEmpty(name, "Parameter name");
		return parameters.get(name);
	}

public
String
getParameter
(
String
name
)
{
Params
.
notNullOrEmpty
(
name
,
"Parameter name"
)
;
return
parameters
.
get
(
name
)
;
}

Get parameter value or null if parameter does not exist.

@param name parameter name.
@return parameter value, possible null.
@throws IllegalArgumentException if name argument is null or empty.

Get parameter value or null if parameter does not exist .


private static Map<String, String> parseParameters(String expression) {
		// 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;
	}

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.

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 .


@Override
	public void config(Config config) throws Exception {
		log.trace("config(Config.Element)");
		log.debug("Configure transaction manager |%s|.", transactionManager.getClass());
		transactionManager.config(config);
	}

@
Override
public
void
config
(
Config
config
)
throws
Exception
{
log
.
trace
(
"config(Config.Element)"
)
;
log
.
debug
(
"Configure transaction manager |%s|."
,
transactionManager
.
getClass
(
)
)
;
transactionManager
.
config
(
config
)
;
}

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.

Configure underlying transaction manager .


protected final GeneratedFile getTargetFile(final String artifactName, final String filename, final String logInfo) {

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

    }

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 '<artifact
name="<i>artifactName</i>" ..>').
@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.

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 .


protected final void write(@NotNull final GeneratedArtifact artifact) throws GenerateException {

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

Writes a generated artifact to a file.

@param artifact
Artifact to persist.

@throws GenerateException
Error writing the artifact.


@Override
	public void postProcessInstance(ManagedClassSPI managedClass, Object instance) {
		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"));
		}
	}

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.

Initialize instance fields from managed class configuration object .


private static Constructor<?> getDeclaredConstructor(Class<?> implementationClass) {
		if (implementationClass == null) {
			return null;
		}
		Constructor<?>[] declaredConstructors = (Constructor<?>[]) implementationClass.getDeclaredConstructors();
		if (declaredConstructors.length == 0) {
			throw new BugError("Invalid implementation class |%s|. Missing constructor.", implementationClass);
		}
		Constructor<?> constructor = null;

		for (Constructor<?> declaredConstructor : declaredConstructors) {
			// synthetic constructors are created by compiler to circumvent JVM limitations, JVM that is not evolving with
			// the same speed as the language; for example, to allow outer class to access private members on a nested class
			// compiler creates a constructor with a single argument of very nested class type
			if (declaredConstructor.isSynthetic()) {
				continue;
			}
			if (declaredConstructor.getParameterTypes().length == 0) {
				continue;
			}
			if (declaredConstructor.getAnnotation(Test.class) != null) {
				continue;
			}
			if (constructor != null) {
				throw new BugError("Implementation class |%s| has not a single constructor with parameters.", implementationClass);
			}
			constructor = declaredConstructor;
		}

		if (constructor == null) {
			constructor = declaredConstructors[0];
		}
		constructor.setAccessible(true);
		return constructor;
	}

Get implementation class constructor. Managed class mandates a single constructor with parameters, no matter if private
or formal parameters count. If both default constructor and constructor with parameters are defined this method returns
constructor with parameters. Returns null if implementation class is missing.

@param implementationClass implementation class, possible null.
@return implementation class constructor or null if given implementation class is null.
@throws BugError if implementation class is an interface, primitive or array and has no constructor at all.
@throws BugError if implementation class has more constructors with parameters.

Get implementation class constructor . Managed class mandates a single constructor with parameters no matter if private or formal parameters count . If both default constructor and constructor with parameters are defined this method returns constructor with parameters . Returns null if implementation class is missing .


private String buildStringRepresentation(Config descriptor) {
		StringBuilder builder = new StringBuilder();
		builder.append(descriptor.getName());
		builder.append(':');
		if (implementationClass != null) {
			builder.append(implementationClass.getName());
			builder.append(':');
		}
		for (Class<?> interfaceClass : interfaceClasses) {
			builder.append(interfaceClass.getName());
			builder.append(':');
		}
		builder.append(instanceType);
		builder.append(':');
		builder.append(instanceScope);
		builder.append(':');
		builder.append(remotelyAccessible ? "NET" : "LOCAL");
		if (implementationURL != null) {
			builder.append(':');
			builder.append(implementationURL);
		}
		return builder.toString();
	}

private String buildStringRepresentation ( Config descriptor ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( descriptor . getName ( ) ) ; builder . append ( ' ' ) ; if ( implementationClass != null ) { builder . append ( implementationClass . getName ( ) ) ; builder . append ( ' ' ) ; } for ( Class < ? > interfaceClass : interfaceClasses ) { builder . append ( interfaceClass . getName ( ) ) ; builder . append ( ' ' ) ; } builder . append ( instanceType ) ; builder . append ( ' ' ) ; builder . append ( instanceScope ) ; builder . append ( ' ' ) ; builder . append ( remotelyAccessible ? "NET" : "LOCAL" ) ; if ( implementationURL != null ) { builder . append ( ' ' ) ; builder . append ( implementationURL ) ; } return builder . toString ( ) ; }

Build and return this managed class string representation.

@param descriptor managed class descriptor.
@return this managed class string representation.

Build and return this managed class string representation .


private static Method getInterfaceMethod(Method method) {
		for (Class<?> interfaceClass : method.getDeclaringClass().getInterfaces()) {
			try {
				return interfaceClass.getMethod(method.getName(), method.getParameterTypes());
			} catch (NoSuchMethodException unused) {
			}
		}
		return method;
	}

private static Method getInterfaceMethod ( Method method ) { for ( Class < ? > interfaceClass : method . getDeclaringClass ( ) . getInterfaces ( ) ) { try { return interfaceClass . getMethod ( method . getName ( ) , method . getParameterTypes ( ) ) ; } catch ( NoSuchMethodException unused ) { } } return method ; }

Get Java reflective method from interface. This getter attempt to locate a method with the same signature as requested
base class method in any interface the declaring class may have. If no method found in interfaces or no interface present
return given base class method. If requested base class method is declared in multiple interfaces this getter returns the
first found but there is no guarantee for order.

@param method base class method, not null.
@return interface method or given base class method if no interface method found.

Get Java reflective method from interface . This getter attempt to locate a method with the same signature as requested base class method in any interface the declaring class may have . If no method found in interfaces or no interface present return given base class method . If requested base class method is declared in multiple interfaces this getter returns the first found but there is no guarantee for order .


private static Class<?> type(Field field) {
		if (Types.isKindOf(field.getType(), List.class)) {
			// for the purpose of this implementation only first parameterized
			// type matters, as result from list declaration List<E>
			return (Class<?>) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0];
		}
		return field.getType();
	}

Return field class or actual type argument if given field is a list.

@param field Java reflective class field.
@return field type.

Return field class or actual type argument if given field is a list .


@SuppressWarnings("unchecked")
	protected static Object getDependencyValue(ManagedClassSPI hostManagedClass, Class<?> type) {
		Stack<Class<?>> stackTrace = dependenciesStack.get();
		if (stackTrace == null) {
			stackTrace = new Stack<>();
			dependenciesStack.set(stackTrace);
		}
		ContainerSPI container = hostManagedClass.getContainer();

		if (stackTrace.contains(type)) {
			try {
				// add current dependency class to reveal what dependency from stack is circular
				stackTrace.add(type);

				StringBuilder builder = new StringBuilder();
				builder.append("Circular dependency. Dependencies trace follows:\r\n");
				for (Class<?> stackTraceClass : stackTrace) {
					builder.append("\t- ");
					builder.append(stackTraceClass.getName());
					builder.append("\r\n");
				}

				log.error(builder.toString());
				throw new BugError("Circular dependency for |%s|.", type.getName());
			} finally {
				// takes care to current thread stack trace is removed
				dependenciesStack.remove();
			}
		}

		stackTrace.push(type);
		try {

			ManagedClassSPI dependencyManagedClass = container.getManagedClass(type);
			if (isProxyRequired(hostManagedClass, dependencyManagedClass)) {
				// if scope proxy is required returns a Java Proxy handled by ScopeProxyHandler
				ScopeProxyHandler<?> handler = new ScopeProxyHandler<>(container, type);
				return Proxy.newProxyInstance(dependencyManagedClass.getImplementationClass().getClassLoader(), dependencyManagedClass.getInterfaceClasses(), handler);
			}

			Object value = container.getOptionalInstance((Class<? super Object>) type);
			if (value != null) {
				// if dependency type is a managed class returns it value from factory
				return value;
			}

			if (Types.isKindOf(type, AppFactory.class)) {
				// handle ApFactory and its hierarchy since it is a special case
				return container;
			}

			if (Classes.isInstantiable(type)) {
				// if requested type is instantiable POJO create a new empty instance of requested type
				return Classes.newInstance(type);
			}

			// TODO: test value instance of
			// if FactoryBean consider it as factory and substitute value
			// e.g. value = ((FactoryBean)value).getInstance(value.getClass())

			// all attempts to create dependency value has fallen
			throw new BugError("Dependency |%s| not resolved for |%s|.", type.getName(), hostManagedClass);

		} finally {
			stackTrace.pop();
			// do not remove stack trace after outermost call finished, i.e. when stack trace is empty
			// leave it on thread local for reuse, in order to avoid unnecessary object creation
		}
	}

Get dependency value of requested type. See class description for a discussion about supported types and circular
dependencies.

@param hostManagedClass managed class defining the context on which dependency is resolved,
@param type dependency type.
@return dependency instance, reused from container caches or fresh created.
@throws BugError if dependency value cannot be created or circular dependency is detected.

Get dependency value of requested type . See class description for a discussion about supported types and circular dependencies .


public final void persist() {

        if (persisted) {
            // Do nothing if already done
            return;
        }

        try {

            // Compare new and old file
            if (FileUtils.contentEquals(tmpFile, file)) {
                LOG.debug("Omitted: {} {}", getPath(), logInfo);
                if (!tmpFile.delete()) {
                    tmpFile.deleteOnExit();
                }
            } else {
                if (file.exists() && !file.delete()) {
                    throw new IOException("Wasn't able to delete file " + file);
                }
                if (!tmpFile.renameTo(file)) {
                    throw new IOException("Wasn't able to rename temporary file " + tmpFile + " to " + file);
                }
                LOG.info("Generated: {} {}", getPath(), logInfo);
            }

            persisted = true;

        } catch (final IOException ex) {
            throw new RuntimeException("Error comparing content: tmp=" + tmpFile + ", target=" + file + logInfo, ex);
        }

    }

public
final
void
persist
(
)
{
if
(
persisted
)
{
// Do nothing if already done
return
;
}
try
{
// Compare new and old file
if
(
FileUtils
.
contentEquals
(
tmpFile
,
file
)
)
{
LOG
.
debug
(
"Omitted: {} {}"
,
getPath
(
)
,
logInfo
)
;
if
(
!
tmpFile
.
delete
(
)
)
{
tmpFile
.
deleteOnExit
(
)
;
}
}
else
{
if
(
file
.
exists
(
)
&&
!
file
.
delete
(
)
)
{
throw
new
IOException
(
"Wasn't able to delete file "
+
file
)
;
}
if
(
!
tmpFile
.
renameTo
(
file
)
)
{
throw
new
IOException
(
"Wasn't able to rename temporary file "
+
tmpFile
+
" to "
+
file
)
;
}
LOG
.
info
(
"Generated: {} {}"
,
getPath
(
)
,
logInfo
)
;
}
persisted
=
true
;
}
catch
(
final
IOException
ex
)
{
throw
new
RuntimeException
(
"Error comparing content: tmp="
+
tmpFile
+
", target="
+
file
+
logInfo
,
ex
)
;
}
}

Compares the content of the temporary file with the possibly existing target file. If both are equal the temporary file is deleted.
Otherwise the old target file is deleted and the new generated file is renamed. This prevents time stamp changes for the target file
if nothing changed since the last generation.

Compares the content of the temporary file with the possibly existing target file . If both are equal the temporary file is deleted . Otherwise the old target file is deleted and the new generated file is renamed . This prevents time stamp changes for the target file if nothing changed since the last generation .


public final void setDefaultLink(String rel, String... hrefs) {
        if (hrefs == null || hrefs.length == 0) {
            defaultLinks.remove(rel);
        } else {
            defaultLinks.put(rel,
                    stream(hrefs).map(uri::resolve).collect(toSet()));
        }
    }

public final void setDefaultLink ( String rel , String ... hrefs ) { if ( hrefs == null || hrefs . length == 0 ) { defaultLinks . remove ( rel ) ; } else { defaultLinks . put ( rel , stream ( hrefs ) . map ( uri :: resolve ) . collect ( toSet ( ) ) ) ; } }

Registers one or more default links for a specific relation type. These
links are used when no links with this relation type are provided by the
server.

This method is not thread-safe! Call this before performing any requests.

@param rel The relation type of the links to add.
@param hrefs The hrefs of links relative to this endpoint's URI. Use
null or an empty list to remove all previous entries for the
relation type.

@see Endpoint#getLinks(java.lang.String)
@see Endpoint#getLinksWithTitles(java.lang.String)
@see Endpoint#link(java.lang.String)

Registers one or more default links for a specific relation type . These links are used when no links with this relation type are provided by the server .


public final void setDefaultLinkTemplate(String rel, String href) {
        if (href == null) {
            defaultLinkTemplates.remove(rel);
        } else {
            defaultLinkTemplates.put(rel, href);
        }
    }

public final void setDefaultLinkTemplate ( String rel , String href ) { if ( href == null ) { defaultLinkTemplates . remove ( rel ) ; } else { defaultLinkTemplates . put ( rel , href ) ; } }

Registers a default link template for a specific relation type. This
template is used when no template with this relation type is provided by
the server.

This method is not thread-safe! Call this before performing any requests.

@param rel The relation type of the link template to add.
@param href The href of the link template relative to this endpoint's
URI. Use null to remove any previous entry for the relation
type.

@see Endpoint#linkTemplate(java.lang.String)

Registers a default link template for a specific relation type . This template is used when no template with this relation type is provided by the server .


@SuppressWarnings("LocalVariableHidesMemberVariable")
    private void handleLinks(HttpResponse response) {
        Map<String, Map<URI, String>> links = new HashMap<>();
        Map<String, String> linkTemplates = new HashMap<>();

        handleHeaderLinks(response, links, linkTemplates);

        HttpEntity entity = response.getEntity();
        if (entity != null) {
            Header contentType = entity.getContentType();
            if ((contentType != null) && contentType.getValue().startsWith("application/json")) {
                try {
                    handleBodyLinks(serializer.readTree(entity.getContent()), links, linkTemplates);
                } catch (IOException ex) {
                    throw new RuntimeException();
                    // Body error handling is done elsewhere
                }
            }
        }

        this.links = unmodifiableMap(links);
        this.linkTemplates = unmodifiableMap(linkTemplates);
    }

Handles links embedded in an HTTP response.

@param response The response to check for links.

Handles links embedded in an HTTP response .


protected void handleHeaderLinks(HttpResponse response, Map<String, Map<URI, String>> links, Map<String, String> linkTemplates) {
        getLinkHeaders(response).forEach(header -> {
            if (header.getRel() == null) {
                return;
            }
            if (header.isTemplated()) {
                linkTemplates.put(header.getRel(), header.getHref());
            } else {
                getOrAdd(links, header.getRel())
                        .put(uri.resolve(header.getHref()), header.getTitle());
            }
        });
    }

protected void handleHeaderLinks ( HttpResponse response , Map < String , Map < URI , String > > links , Map < String , String > linkTemplates ) { getLinkHeaders ( response ) . forEach ( header -> { if ( header . getRel ( ) == null ) { return ; } if ( header . isTemplated ( ) ) { linkTemplates . put ( header . getRel ( ) , header . getHref ( ) ) ; } else { getOrAdd ( links , header . getRel ( ) ) . put ( uri . resolve ( header . getHref ( ) ) , header . getTitle ( ) ) ; } } ) ; }

Handles links embedded in HTTP response headers.

@param response The response to check for links.
@param links A dictionary to add found links to.
@param linkTemplates A dictionary to add found link templates to.

Handles links embedded in HTTP response headers .


protected void handleBodyLinks(JsonNode jsonBody, Map<String, Map<URI, String>> links, Map<String, String> linkTemplates) {
        if (jsonBody.getNodeType() != JsonNodeType.OBJECT) {
            return;
        }

        JsonNode linksNode = jsonBody.get("_links");
        if (linksNode == null) {
            linksNode = jsonBody.get("links");
        }
        if (linksNode == null) {
            return;
        }

        linksNode.fields().forEachRemaining(x -> {
            String rel = x.getKey();
            Map<URI, String> linksForRel = getOrAdd(links, rel);

            switch (x.getValue().getNodeType()) {
                case ARRAY:
                    x.getValue().forEach(subobj -> {
                        if (subobj.getNodeType() == JsonNodeType.OBJECT) {
                            parseLinkObject(rel, (ObjectNode) subobj, linksForRel, linkTemplates);
                        }
                    });
                    break;
                case OBJECT:
                    parseLinkObject(rel, (ObjectNode) x.getValue(), linksForRel, linkTemplates);
                    break;
            }
        });
    }

protected void handleBodyLinks ( JsonNode jsonBody , Map < String , Map < URI , String > > links , Map < String , String > linkTemplates ) { if ( jsonBody . getNodeType ( ) != JsonNodeType . OBJECT ) { return ; } JsonNode linksNode = jsonBody . get ( "_links" ) ; if ( linksNode == null ) { linksNode = jsonBody . get ( "links" ) ; } if ( linksNode == null ) { return ; } linksNode . fields ( ) . forEachRemaining ( x -> { String rel = x . getKey ( ) ; Map < URI , String > linksForRel = getOrAdd ( links , rel ) ; switch ( x . getValue ( ) . getNodeType ( ) ) { case ARRAY : x . getValue ( ) . forEach ( subobj -> { if ( subobj . getNodeType ( ) == JsonNodeType . OBJECT ) { parseLinkObject ( rel , ( ObjectNode ) subobj , linksForRel , linkTemplates ) ; } } ) ; break ; case OBJECT : parseLinkObject ( rel , ( ObjectNode ) x . getValue ( ) , linksForRel , linkTemplates ) ; break ; } } ) ; }

Handles links embedded in JSON response bodies.

@param jsonBody The body to check for links.
@param links A dictionary to add found links to.
@param linkTemplates A dictionary to add found link templates to.

Handles links embedded in JSON response bodies .


private void parseLinkObject(String rel, ObjectNode obj, Map<URI, String> linksForRel, Map<String, String> linkTemplates) {
        JsonNode href = obj.findValue("href");
        if (href == null) {
            return;
        }

        JsonNode templated = obj.findValue("templated");
        if (templated != null && templated.isBoolean() && templated.asBoolean()) {
            linkTemplates.put(rel, href.asText());
        } else {
            JsonNode title = obj.findValue("title");
            linksForRel.put(
                    uri.resolve(href.asText()),
                    (title != null && title.getNodeType() == JsonNodeType.STRING) ? title.asText() : null);
        }
    }

private void parseLinkObject ( String rel , ObjectNode obj , Map < URI , String > linksForRel , Map < String , String > linkTemplates ) { JsonNode href = obj . findValue ( "href" ) ; if ( href == null ) { return ; } JsonNode templated = obj . findValue ( "templated" ) ; if ( templated != null && templated . isBoolean ( ) && templated . asBoolean ( ) ) { linkTemplates . put ( rel , href . asText ( ) ) ; } else { JsonNode title = obj . findValue ( "title" ) ; linksForRel . put ( uri . resolve ( href . asText ( ) ) , ( title != null && title . getNodeType ( ) == JsonNodeType . STRING ) ? title . asText ( ) : null ) ; } }

Parses a JSON object for link information.

@param rel The relation type of the link.
@param obj The JSON object to parse for link information.
@param linksForRel A dictionary to add found links to. Maps hrefs to
titles.
@param linkTemplates A dictionary to add found link templates to. Maps
rels to templated hrefs.

Parses a JSON object for link information .


private static Map<URI, String> getOrAdd(Map<String, Map<URI, String>> map, String key) {
        Map<URI, String> value = map.get(key);
        if (value == null) {
            map.put(key, value = new HashMap<>());
        }
        return value;
    }

private static Map < URI , String > getOrAdd ( Map < String , Map < URI , String > > map , String key ) { Map < URI , String > value = map . get ( key ) ; if ( value == null ) { map . put ( key , value = new HashMap <> ( ) ) ; } return value ; }

Returns the element with the specified key from the map. Creates, adds
and returns a new element if no match was found.

@param map The map to look in.
@param key The key to look for.
@return The existing or new element.

Returns the element with the specified key from the map . Creates adds and returns a new element if no match was found .


protected void handleCapabilities(HttpResponse response) {
        allowedMethods = unmodifiableSet(stream(response.getHeaders("Allow"))
                .filter(x -> x.getName().equals("Allow"))
                .flatMap(x -> stream(x.getElements())).map(x -> x.getName())
                .collect(toSet()));
    }

protected void handleCapabilities ( HttpResponse response ) { allowedMethods = unmodifiableSet ( stream ( response . getHeaders ( "Allow" ) ) . filter ( x -> x . getName ( ) . equals ( "Allow" ) ) . flatMap ( x -> stream ( x . getElements ( ) ) ) . map ( x -> x . getName ( ) ) . collect ( toSet ( ) ) ) ; }

Handles allowed HTTP methods and other capabilities reported by the
server.

@param response The response to check for the "Allow" header.

Handles allowed HTTP methods and other capabilities reported by the server .


protected Optional<Boolean> isMethodAllowed(String method) {
        if (allowedMethods.isEmpty()) {
            return Optional.empty();
        }
        return Optional.of(allowedMethods.contains(method));
    }

protected Optional < Boolean > isMethodAllowed ( String method ) { if ( allowedMethods . isEmpty ( ) ) { return Optional . empty ( ) ; } return Optional . of ( allowedMethods . contains ( method ) ) ; }

Shows whether the server has indicated that a specific HTTP method is
currently allowed.

Uses cached data from last response.

@param method The HTTP method (e.g. GET, POST, ...) to check.
@return An indicator whether the method is allowed. If no request has been
sent yet or the server did not specify allowed methods
{@link Optional#empty()} is returned.

Shows whether the server has indicated that a specific HTTP method is currently allowed .


protected void registerInstanceProcessor() {
		registerInstanceProcessor(new InstanceFieldsInjectionProcessor());
		registerInstanceProcessor(new InstanceFieldsInitializationProcessor());
		registerInstanceProcessor(new ConfigurableInstanceProcessor());
		registerInstanceProcessor(new PostConstructInstanceProcessor());
		registerInstanceProcessor(new CronMethodsProcessor(cronManager));
		registerInstanceProcessor(new LoggerInstanceProcessor());
	}

protected void registerInstanceProcessor ( ) { registerInstanceProcessor ( new InstanceFieldsInjectionProcessor ( ) ) ; registerInstanceProcessor ( new InstanceFieldsInitializationProcessor ( ) ) ; registerInstanceProcessor ( new ConfigurableInstanceProcessor ( ) ) ; registerInstanceProcessor ( new PostConstructInstanceProcessor ( ) ) ; registerInstanceProcessor ( new CronMethodsProcessor ( cronManager ) ) ; registerInstanceProcessor ( new LoggerInstanceProcessor ( ) ) ; }

Register all instance post - processors .


protected void registerInstanceFactory(InstanceType instanceType, InstanceFactory instanceFactory) {
		log.debug("Register instance factory |%s| to |%s|.", instanceFactory.getClass(), instanceType);
		if (instanceFactories.put(instanceType, instanceFactory) != null) {
			throw new BugError("Attempt to override instance type |%s|.", instanceType);
		}
	}

Register instance factory to requested instance type.

@param instanceType instance type used as key for instance factory,
@param instanceFactory instance factory.
@throws BugError if instance type is already registered.

Register instance factory to requested instance type .


protected void registerInstanceProcessor(InstanceProcessor instanceProcessor) {
		for (InstanceProcessor existingInstanceProcessoor : instanceProcessors) {
			if (existingInstanceProcessoor.getClass().equals(instanceProcessor.getClass())) {
				throw new BugError("Attempt to override instance processor |%s|.", instanceProcessor.getClass());
			}
		}
		log.debug("Register instance processor |%s|.", instanceProcessor.getClass());
		instanceProcessors.add(instanceProcessor);
	}

Register instance processor. Only a single instance per processor class is allowed.

@param instanceProcessor instance processor.
@throws BugError if instance processor class is already registered.
@see #instanceProcessors

Register instance processor . Only a single instance per processor class is allowed .


protected void registerClassProcessor(ClassProcessor classProcessor) {
		for (ClassProcessor existingClassProcessoor : classProcessors) {
			if (existingClassProcessoor.getClass().equals(classProcessor.getClass())) {
				throw new BugError("Attempt to override class processor |%s|.", classProcessor.getClass());
			}
		}
		log.debug("Register class processor |%s|.", classProcessor.getClass());
		classProcessors.add(classProcessor);
	}

Register global processors for managed classes. Post-processors are singletons and only one post-processor instance of a
type is allowed.

@param classProcessor managed class post-processor.
@throws BugError if class processor class is already registered.
@see #classProcessors

Register global processors for managed classes . Post - processors are singletons and only one post - processor instance of a type is allowed .


@Override
	public <T> T getInstance(Class<? super T> interfaceClass, Object... args) {
		Params.notNull(interfaceClass, "Interface class");

		ManagedClassSPI managedClass = classesPool.get(interfaceClass);
		if (managedClass == null) {
			throw new BugError("No managed class associated with interface class |%s|.", interfaceClass);
		}

		InstanceKey instanceKey = new InstanceKey(managedClass.getKey());
		return getInstance(managedClass, instanceKey, args);
	}


public final void addArgument(@NotNull final Argument argument) {
        if (arguments == null) {
            arguments = new ArrayList<Argument>();
        }
        arguments.add(argument);
    }

public final void addArgument ( @ NotNull final Argument argument ) { if ( arguments == null ) { arguments = new ArrayList < Argument > ( ) ; } arguments . add ( argument ) ; }

Adds an argument to the template. If the list of arguments does not exist, it will be created.

@param argument
Arguments to add.

Adds an argument to the template . If the list of arguments does not exist it will be created .


public final List<TargetFile> createTargetFileList() {
        if (tflProducerConfig == null) {
            LOG.info("Using target file list: {} elements", targetFiles.size());
            return targetFiles;
        }
        final TargetFileListProducer producer = tflProducerConfig.getTargetFileListProducer();
        LOG.info("Using target file list producer: {}", producer.getClass().getName());
        return producer.createTargetFiles();
    }

public
final
List
<
TargetFile
>
createTargetFileList
(
)
{
if
(
tflProducerConfig
==
)
{
LOG
.
info
(
"Using target file list: {} elements"
,
targetFiles
.
size
(
)
)
;
return
targetFiles
;
}
final
TargetFileListProducer
producer
=
tflProducerConfig
.
getTargetFileListProducer
(
)
;
LOG
.
info
(
"Using target file list producer: {}"
,
producer
.
getClass
(
)
.
getName
(
)
)
;
return
producer
.
createTargetFiles
(
)
;
}

Returns the list of target files. Either by using the producer or by simply returning the internal list.

@return Target files - Never NULL and has at least one entry.

Returns the list of target files . Either by using the producer or by simply returning the internal list .


public final String toXml() {
        try {
            final JaxbHelper helper = new JaxbHelper();
            return helper.write(this, createJaxbContext());
        } catch (final MarshalObjectException ex) {
            throw new RuntimeException(ex);
        }
    }

public final String toXml ( ) { try { final JaxbHelper helper = new JaxbHelper ( ) ; return helper . write ( this , createJaxbContext ( ) ) ; } catch ( final MarshalObjectException ex ) { throw new RuntimeException ( ex ) ; } }

Marshals the object to an XML String.

@return XML String.


public final void init(final SrcGen4JContext context, final Map<String, String> vars) {

        if (template != null) {
            template = Utils4J.replaceVars(template, vars);
        }
        if (arguments != null) {
            for (final Argument argument : arguments) {
                argument.init(vars);
            }
        }
        if (targetFiles != null) {
            for (final TargetFile targetFile : targetFiles) {
                targetFile.init(vars);
            }
        }
        if (tflProducerConfig != null) {
            tflProducerConfig.init(context, this, vars);
        }
    }

public final void init ( final SrcGen4JContext context , final Map < String , String > vars ) { if ( template != null ) { template = Utils4J . replaceVars ( template , vars ) ; } if ( arguments != null ) { for ( final Argument argument : arguments ) { argument . init ( vars ) ; } } if ( targetFiles != null ) { for ( final TargetFile targetFile : targetFiles ) { targetFile . init ( vars ) ; } } if ( tflProducerConfig != null ) { tflProducerConfig . init ( context , this , vars ) ; } }

Initializes the model.

@param context
Current context.
@param vars
Variables to use.


public final boolean hasReferenceTo(final File templateDir, final File templateFile) {
        final String p1 = Utils4J.getCanonicalPath(new File(templateDir, template));
        final String p2 = Utils4J.getCanonicalPath(templateFile);
        return p1.equals(p2);
    }

public final boolean hasReferenceTo ( final File templateDir , final File templateFile ) { final String p1 = Utils4J . getCanonicalPath ( new File ( templateDir , template ) ) ; final String p2 = Utils4J . getCanonicalPath ( templateFile ) ; return p1 . equals ( p2 ) ; }

Checks if this model has a reference to the given template file.

@param templateDir
Directory where all template files are located - Cannot be NULL.
@param templateFile
Template file to check - Cannot be NULL.

@return If the template is referenced TRUE else FALSE.

Checks if this model has a reference to the given template file .


public static ParameterizedTemplateModel create(final Reader reader) {
        try {
            final JaxbHelper helper = new JaxbHelper();
            final ParameterizedTemplateModel pc = helper.create(reader, createJaxbContext());
            Contract.requireValid(pc);
            return pc;
        } catch (final UnmarshalObjectException ex) {
            throw new RuntimeException(ex);
        }
    }

public static ParameterizedTemplateModel create ( final Reader reader ) { try { final JaxbHelper helper = new JaxbHelper ( ) ; final ParameterizedTemplateModel pc = helper . create ( reader , createJaxbContext ( ) ) ; Contract . requireValid ( pc ) ; return pc ; } catch ( final UnmarshalObjectException ex ) { throw new RuntimeException ( ex ) ; } }

Creates an instance by reading the XML from a reader.

@param reader
Reader to use.

@return New instance.

Creates an instance by reading the XML from a reader .


public static ParameterizedTemplateModel create(final File file) {
        try {
            final JaxbHelper helper = new JaxbHelper();
            final ParameterizedTemplateModel pc = helper.create(file, createJaxbContext());
            pc.setFile(file);
            Contract.requireValid(pc);
            return pc;
        } catch (final UnmarshalObjectException ex) {
            throw new RuntimeException(ex);
        }
    }

public static ParameterizedTemplateModel create ( final File file ) { try { final JaxbHelper helper = new JaxbHelper ( ) ; final ParameterizedTemplateModel pc = helper . create ( file , createJaxbContext ( ) ) ; pc . setFile ( file ) ; Contract . requireValid ( pc ) ; return pc ; } catch ( final UnmarshalObjectException ex ) { throw new RuntimeException ( ex ) ; } }

Creates an instance by reading the XML from a file.

@param file
File to read.

@return New instance.

Creates an instance by reading the XML from a file .


void setRequestPath(String requestPath) {
		this.requestPath = requestPath != null ? requestPath : Strings.toDashCase(method.getName());
	}

void setRequestPath ( String requestPath ) { this . requestPath = requestPath != null ? requestPath : Strings . toDashCase ( method . getName ( ) ) ; }

Set this method request URI path, that is, the path component by which this method is referred into request URI. If given
request URI path is null uses method name converted to dashed case.

@param requestPath request URI path for this method, possible null.

Set this method request URI path that is the path component by which this method is referred into request URI . If given request URI path is null uses method name converted to dashed case .


StoppableObservable<TEntity> getObservable(final long startIndex, Scheduler scheduler) {
        return runAsync(scheduler, (rx.Observer<? super TEntity> observer, Subscription subscription) -> {
            long currentStartIndex = startIndex;
            while (!subscription.isUnsubscribed()) {
                PartialResponse<TEntity> response;
                try {
                    response = (currentStartIndex >= 0)
                            ? readRange(currentStartIndex, null)
                            : readRange(null, -currentStartIndex);
                } catch (IllegalStateException ex) {
                    // No new data available yet, keep polling
                    continue;
                } catch (IOException | IllegalArgumentException | IllegalAccessException error) {
                    observer.onError(error);
                    return;
                }

                response.getElements().stream().forEach(observer::onNext);

                if (response.isEndReached()) {
                    observer.onCompleted();
                    return;
                }

                // Continue polling for more data
                currentStartIndex = response.getTo() + 1;
            }
        });
    }

Provides an observable stream of elements.

@param startIndex The index of the first element to return in the stream.
Use negative values to start counting from the end of the stream.
@param scheduler The scheduler used to run the background thread.
@return An observable stream of elements.

Provides an observable stream of elements .


@SuppressWarnings("unchecked")
	@Override
	public <T> T asObject(String string, Class<T> valueType) {
		return (T) new InstanceScope(string);
	}

@ SuppressWarnings ( "unchecked" ) @ Override public < T > T asObject ( String string , Class < T > valueType ) { return ( T ) new InstanceScope ( string ) ; }

Create a scope instance from its string value.

Create a scope instance from its string value .


private void setField(Field field, String parameterName, Object instance) {
		final Object value = context.getProperty(parameterName, field.getType());
		try {
			field.set(instance, value);
		} catch (Exception e) {
			throw new BugError(e);
		}
	}

private void setField ( Field field , String parameterName , Object instance ) { final Object value = context . getProperty ( parameterName , field . getType ( ) ) ; try { field . set ( instance , value ) ; } catch ( Exception e ) { throw new BugError ( e ) ; } }

Initialize field from named context parameter.

@param field field to be initialized, both class and instance fields accepted,
@param parameterName name for context parameter,
@param instance optional instance, null for class fields.

Initialize field from named context parameter .


public void addCaptureToLogger(final AppenderAttachable logger,
	                               final String appenderName) {
		Appender currentAppender = logger.getAppender(appenderName);
		Appender captureAppender = CaptureAppender.newAppenderFrom(currentAppender);
		logger.addAppender(captureAppender);
	}

public void addCaptureToLogger ( final AppenderAttachable logger , final String appenderName ) { Appender currentAppender = logger . getAppender ( appenderName ) ; Appender captureAppender = CaptureAppender . newAppenderFrom ( currentAppender ) ; logger . addAppender ( captureAppender ) ; }

Adds a new CaptureAppender to an existing logger.

@param logger       logger to use
@param appenderName name of an existing appender which will be captured

Adds a new CaptureAppender to an existing logger .


public void remove(final AppenderAttachable logger, final String appenderName) {
		logger.removeAppender(CaptureAppender.getAppenderNameFor(appenderName));
	}

public void remove ( final AppenderAttachable logger , final String appenderName ) { logger . removeAppender ( CaptureAppender . getAppenderNameFor ( appenderName ) ) ; }

Removes a CaptureAppender from a logger.

@param logger       logger to use
@param appenderName name of the appender which is captured

Removes a CaptureAppender from a logger .


public void clear(final AppenderAttachable logger, final String appenderName) {
		((CaptureAppender) logger.getAppender(CaptureAppender.getAppenderNameFor(
				appenderName))).clear();
	}

public void clear ( final AppenderAttachable logger , final String appenderName ) { ( ( CaptureAppender ) logger . getAppender ( CaptureAppender . getAppenderNameFor ( appenderName ) ) ) . clear ( ) ; }

Deletes all cached log entries.

@param logger       logger to use
@param appenderName name of the appender which will be cleared


@Override
	public Object[] read(HttpServletRequest httpRequest, Type[] formalParameters) throws IOException, IllegalArgumentException {
		try {
			Object[] arguments = new Object[formalParameters.length];
			int argumentIndex = 0;

			ServletFileUpload multipart = new ServletFileUpload();
			FileItemIterator iterator = multipart.getItemIterator(httpRequest);

			FileItemStream fileItemStream = null;
			while (iterator.hasNext()) {
				fileItemStream = iterator.next();
				String contentType = fileItemStream.getContentType();
				Type parameterType = formalParameters[argumentIndex];

				ArgumentPartReader reader = argumentsReaderFactory.getArgumentPartReader(contentType, parameterType);
				boolean streamArgument = StreamFactory.isStream(parameterType);

				ArgumentPartReader argumentPartReader = (ArgumentPartReader) reader;
				InputStream inputStream = streamArgument ? new LazyFileItemStream(fileItemStream) : fileItemStream.openStream();

				arguments[argumentIndex] = argumentPartReader.read(inputStream, parameterType);
				++argumentIndex;

				// stream argument should be last on mixed arguments list
				// save it to local thread storage for clean-up after arguments processed by application
				if (streamArgument) {
					threadLocal.set(inputStream);
					break;
				}
				inputStream.close();
			}

			if (argumentIndex != formalParameters.length) {
				throw new IllegalArgumentException("Not all parameters processed due to stream argument that is not the last on arguments list.");
			}
			return arguments;
		} catch (FileUploadException e) {
			throw new IOException(e.getMessage());
		}
	}

Read mixed body entities from HTTP request, creating and initializing arguments accordingly given formal parameters. The
number and order of arguments from multipart mixed message should respect formal parameter types. Also stream argument,
if present, should be a single one and the last on arguments list.

@param httpRequest HTTP request,
@param formalParameters formal parameter types.
@return arguments array.
@throws IOException if reading from request input stream fails.
@throws IllegalArgumentException if arguments from HTTP request cannot be parsed.
@throws IllegalArgumentException if content type for a mixed entity body is not supported.
@throws IllegalArgumentException if there is a stream argument but is not the last on arguments list.

Read mixed body entities from HTTP request creating and initializing arguments accordingly given formal parameters . The number and order of arguments from multipart mixed message should respect formal parameter types . Also stream argument if present should be a single one and the last on arguments list .


protected final void parseModel() {

        if ((fileExtensions == null) || (fileExtensions.size() == 0)) {
            throw new IllegalStateException("No file extensions for EMF model files set!");
        }

        // Drop previous resource set
        resourceSet = new ResourceSetImpl();
        error = false;

        parseDirs();
        parseResources();

    }

Parses all model files in the directories and all resources. y

Parses all model files in the directories and all resources . y


protected final void resolveProxies() {
        final List<String> unresolved = new ArrayList<String>();
        if (!resolvedAllProxies(unresolved, 0)) {
            LOG.warn("Could not resolve the following proxies ({}):", unresolved.size());
            for (final String ref : unresolved) {
                LOG.warn("Not found: {}", ref);
            }
            final Iterator<Notifier> it = resourceSet.getAllContents();
            while (it.hasNext()) {
                final Notifier next = it.next();
                if (next instanceof EObject) {
                    final EObject obj = (EObject) next;
                    if (obj.eIsProxy()) {
                        try {
                            it.remove();
                        } catch (final UnsupportedOperationException ex) {
                            LOG.error("Could not remove proxy: " + obj, ex);
                        }
                    }
                }
            }
        }
    }


private File[] getFiles(final File dir) {
        final File[] files = dir.listFiles(new FileFilter() {
            @Override
            public boolean accept(final File file) {
                final boolean pointFile = file.getName().startsWith(".");
                final String extension = FilenameUtils.getExtension(file.getName());
                return (!pointFile && fileExtensions.contains(extension)) || file.isDirectory();
            }
        });
        return files;
    }

private File [ ] getFiles ( final File dir ) { final File [ ] files = dir . listFiles ( new FileFilter ( ) { @ Override public boolean accept ( final File file ) { final boolean pointFile = file . getName ( ) . startsWith ( "." ) ; final String extension = FilenameUtils . getExtension ( file . getName ( ) ) ; return ( ! pointFile && fileExtensions . contains ( extension ) ) || file . isDirectory ( ) ; } } ) ; return files ; }

Returns files that end with java and all directories. Files and directories started with a "." are excluded.

@param dir
Directory to scan.

@return List of files in the directory.

Returns files that end with java and all directories . Files and directories started with a . are excluded .


private void parseDir(final File dir) {
        LOG.debug("Parse: {}", dir);
        final File[] files = getFiles(dir);
        if ((files == null) || (files.length == 0)) {
            LOG.debug("No files found in directory: {}", dir);
        } else {
            for (final File file : files) {
                if (file.isFile()) {
                    final Resource resource = resourceSet.getResource(URI.createFileURI(Utils4J.getCanonicalPath(file)), true);
                    final EList<Diagnostic> diagnostics = resource.getErrors();
                    if (diagnostics.size() == 0) {
                        LOG.debug("Parsed {}", file);
                    } else {
                        error = true;
                        LOG.error("Parsed {} with errors: {}", file, diagnostics);
                    }
                } else {
                    parseDir(file);
                }
            }
        }
    }

private
void
parseDir
(
final
File
dir
)
{
LOG
.
debug
(
"Parse: {}"
,
dir
)
;
final
File
[
]
files
=
getFiles
(
dir
)
;
if
(
(
files
==
)
||
(
files
.
length
==
0
)
)
{
LOG
.
debug
(
"No files found in directory: {}"
,
dir
)
;
}
else
{
for
(
final
File
file
:
files
)
{
if
(
file
.
isFile
(
)
)
{
final
Resource
resource
=
resourceSet
.
getResource
(
URI
.
createFileURI
(
Utils4J
.
getCanonicalPath
(
file
)
)
,
true
)
;
final
EList
<
Diagnostic
>
diagnostics
=
resource
.
getErrors
(
)
;
if
(
diagnostics
.
size
(
)
==
0
)
{
LOG
.
debug
(
"Parsed {}"
,
file
)
;
}
else
{
error
=
true
;
LOG
.
error
(
"Parsed {} with errors: {}"
,
file
,
diagnostics
)
;
}
}
else
{
parseDir
(
file
)
;
}
}
}
}

Parse the directory and it's sub directory.

@param dir
Directory to parse.

Parse the directory and it s sub directory .


public boolean isModelFullyResolved() {

        boolean resolved = true;
        final Set<EObject> eObjects = findAllEObjects(resourceSet);
        final Iterator<EObject> it = eObjects.iterator();
        while (it.hasNext()) {
            final EObject eObj = it.next();
            if (eObj instanceof InternalEObject) {
                final InternalEObject iObj = (InternalEObject) eObj;
                for (final EObject crossRef : iObj.eCrossReferences()) {
                    if (crossRef.eIsProxy()) {
                        LOG.error("Unresolved: {}", crossRef);
                        resolved = false;
                    }
                }
            }
        }
        return resolved;

    }

public
boolean
isModelFullyResolved
(
)
{
boolean
resolved
=
true
;
final
Set
<
EObject
>
eObjects
=
findAllEObjects
(
resourceSet
)
;
final
Iterator
<
EObject
>
it
=
eObjects
.
iterator
(
)
;
while
(
it
.
hasNext
(
)
)
{
final
EObject
eObj
=
it
.
next
(
)
;
if
(
eObj
instanceof
InternalEObject
)
{
final
InternalEObject
iObj
=
(
InternalEObject
)
eObj
;
for
(
final
EObject
crossRef
:
iObj
.
eCrossReferences
(
)
)
{
if
(
crossRef
.
eIsProxy
(
)
)
{
LOG
.
error
(
"Unresolved: {}"
,
crossRef
)
;
resolved
=
false
;
}
}
}
}
return
resolved
;
}

Determines if all proxies in the model are resolved.

@return {@code true} if there are no more proxies in the model.

Determines if all proxies in the model are resolved .


private static Set<EObject> findAllEObjects(final ResourceSet resourceSet) {
        final Set<EObject> list = new HashSet<EObject>();
        for (final Iterator<Notifier> i = resourceSet.getAllContents(); i.hasNext();) {
            final Notifier next = i.next();
            if (next instanceof EObject) {
                list.add((EObject) next);
            }
        }
        return list;
    }

private static Set < EObject > findAllEObjects ( final ResourceSet resourceSet ) { final Set < EObject > list = new HashSet < EObject > ( ) ; for ( final Iterator < Notifier > i = resourceSet . getAllContents ( ) ; i . hasNext ( ) ; ) { final Notifier next = i . next ( ) ; if ( next instanceof EObject ) { list . add ( ( EObject ) next ) ; } } return list ; }

Returns a list of all objects.

@return List.


protected final void setModelDirs(final File... modelDirs) {
        if (modelDirs == null) {
            this.modelDirs = null;
        } else {
            this.modelDirs = new ArrayList<File>();
            this.modelDirs.addAll(Arrays.asList(modelDirs));
        }
    }

protected final void setModelDirs ( final File ... modelDirs ) { if ( modelDirs == null ) { this . modelDirs = null ; } else { this . modelDirs = new ArrayList < File > ( ) ; this . modelDirs . addAll ( Arrays . asList ( modelDirs ) ) ; } }

Sets the model directories to parse. If no list exists internally, it will be created if necessary.

@param modelDirs
Array of model directories or NULL.

Sets the model directories to parse . If no list exists internally it will be created if necessary .


protected final void setFileExtensions(final String... fileExtensions) {
        if (fileExtensions == null) {
            this.fileExtensions = null;
        } else {
            this.fileExtensions = new ArrayList<String>();
            this.fileExtensions.addAll(Arrays.asList(fileExtensions));
        }
    }

protected final void setFileExtensions ( final String ... fileExtensions ) { if ( fileExtensions == null ) { this . fileExtensions = null ; } else { this . fileExtensions = new ArrayList < String > ( ) ; this . fileExtensions . addAll ( Arrays . asList ( fileExtensions ) ) ; } }

Sets the list of file extensions. If no list exists internally, it will be created if necessary.

@param fileExtensions
Array of extensions for files to find ("mymodel", "java", "class", ...)

Sets the list of file extensions . If no list exists internally it will be created if necessary .


protected final void setModelResources(final URI... modelResources) {
        if (modelResources == null) {
            this.modelResources = null;
        } else {
            this.modelResources = new ArrayList<URI>();
            this.modelResources.addAll(Arrays.asList(modelResources));
        }
    }

protected final void setModelResources ( final URI ... modelResources ) { if ( modelResources == null ) { this . modelResources = null ; } else { this . modelResources = new ArrayList < URI > ( ) ; this . modelResources . addAll ( Arrays . asList ( modelResources ) ) ; } }

Sets the model resources to parse. If no list exists internally, it will be created if necessary.

@param modelResources
Array of model resources or NULL.

Sets the model resources to parse . If no list exists internally it will be created if necessary .


@Override
	public final boolean nextRecord() throws IOException {
		final String line = reader.readLine();
		if (line == null) {
			parts = null;
			return false;
		}

		final List<String> newParts = splitLine(line);
		parts = newParts.toArray(new String[newParts.size()]);
		partIndex = 0;
		return true;
	}

@ Override public final boolean nextRecord ( ) throws IOException { final String line = reader . readLine ( ) ; if ( line == null ) { parts = null ; return false ; } final List < String > newParts = splitLine ( line ) ; parts = newParts . toArray ( new String [ newParts . size ( ) ] ) ; partIndex = 0 ; return true ; }

Reads the next row.

@return {@code true} if a record set could been read,
{@code false} on end of file.
@throws IOException when the underlying Stream reports an error


public void setStringArray(String parameterName, String... values) throws java.sql.SQLException {
		int arrayLen = this.getSql().getArrayLen(parameterName);
		AssertUtils.assertTrue(values.length <= arrayLen);

		for (int i = 0; i < arrayLen; i++) {
			setString2(Sql.toParamName(parameterName, i), (i < values.length) ? values[i] : null);
		}
	}

public void setStringArray ( String parameterName , String ... values ) throws java . sql . SQLException { int arrayLen = this . getSql ( ) . getArrayLen ( parameterName ) ; AssertUtils . assertTrue ( values . length <= arrayLen ) ; for ( int i = 0 ; i < arrayLen ; i ++ ) { setString2 ( Sql . toParamName ( parameterName , i ) , ( i < values . length ) ? values [ i ] : null ) ; } }


public void setBoolean2(String parameterName, Boolean value) throws java.sql.SQLException {
		if (value == null) {
			setNull(parameterName, Types.BIT);
		} else {
			setBoolean(parameterName, value);
		}
	}

public void setBoolean2 ( String parameterName , Boolean value ) throws java . sql . SQLException { if ( value == null ) { setNull ( parameterName , Types . BIT ) ; } else { setBoolean ( parameterName , value ) ; } }


@Override
	public long executeLargeUpdate(java.lang.String sql, int[] columnIndexes) throws java.sql.SQLException {
		return this.stat.executeLargeUpdate(sql, columnIndexes);
	}

@ Override public long executeLargeUpdate ( java . lang . String sql , int [ ] columnIndexes ) throws java . sql . SQLException { return this . stat . executeLargeUpdate ( sql , columnIndexes ) ; }


@SuppressWarnings("unchecked")
	@Override
	public <T> T asObject(String string, Class<T> valueType) throws IllegalArgumentException, ConverterException {
		return (T) new InstanceType(string);
	}

@ SuppressWarnings ( "unchecked" ) @ Override public < T > T asObject ( String string , Class < T > valueType ) throws IllegalArgumentException , ConverterException { return ( T ) new InstanceType ( string ) ; }

Create an instance type from its string value.

Create an instance type from its string value .