public String getStringValue()
    {
        // Check if the attribute class has been finalized yet.
        if (attributeClass.finalized)
        {
            // Fetch the string value from the attribute class.
            return attributeClass.lookupValue[value].label;
        }
        else
        {
            return attributeClass.lookupValueList.get(value).label;
        }
    }

Gets the string value of a string attribute.

@return The underlying string value of this attribute.

Gets the string value of a string attribute .


public void setStringValue(String value) throws IllegalArgumentException
    {
        Byte b = attributeClass.lookupByte.get(value);

        // Check if the value is not already a memeber of the attribute class.
        if (b == null)
        {
            // Check if the attribute class has been finalized yet.
            if (attributeClass.finalized)
            {
                throw new IllegalArgumentException("The value to set, " + value +
                    ", is not already a member of the finalized EnumeratedStringType, " +
                    attributeClass.attributeClassName + ".");
            }
            else
            {
                // Add the new value to the attribute class. Delegate to the factory to do this so that strings are
                // interned and so on.
                EnumeratedStringAttribute newAttribute = attributeClass.createStringAttribute(value);
                b = newAttribute.value;
            }
        }

        // Set the new value as the value of this attribute.
        this.value = b;
    }

Sets the specified string as the value of this attribute. The value to set must be a legitimate member of this
attributes type, when the type has been finalized. If the type has yet to be finalized then the new value is
added to the set of possible values for the type.

@param  value The new value to set.

@throws IllegalArgumentException If the type has been finalized and the new value is not a member of the type.

Sets the specified string as the value of this attribute . The value to set must be a legitimate member of this attributes type when the type has been finalized . If the type has yet to be finalized then the new value is added to the set of possible values for the type .


private void read(Term term)
    {
        if (term.isNumber())
        {
            NumericType numericType = (NumericType) term;

            if (numericType.isInteger())
            {
                IntLiteral jplInteger = (IntLiteral) term;
                getContentHandler().startIntegerTerm(jplInteger.longValue());
            }
            else if (numericType.isFloat())
            {
                FloatLiteral jplFloat = (FloatLiteral) term;
                getContentHandler().startFloatTerm(jplFloat.doubleValue());
            }
        }
        else if (term.isVar())
        {
            Variable var = (Variable) term;
            getContentHandler().startVariable(interner.getVariableName(var.getName()));
        }
        else if (term.isAtom())
        {
            Functor atom = (Functor) term;
            getContentHandler().startAtom(interner.getFunctorName(atom.getName()));
        }
        else if (term.isCompound())
        {
            Functor functor = (Functor) term;
            getContentHandler().startCompound();
            getContentHandler().startAtom(interner.getFunctorName(functor.getName()));

            for (com.thesett.aima.logic.fol.Term child : functor.getArguments())
            {
                read(child);
            }

            getContentHandler().endCompound();
        }
        else
        {
            throw new IllegalStateException("Unrecognized Lojix term: " + term);
        }
    }

private
void
read
(
Term
term
)
{
if
(
term
.
isNumber
(
)
)
{
NumericType
numericType
=
(
NumericType
)
term
;
if
(
numericType
.
isInteger
(
)
)
{
IntLiteral
jplInteger
=
(
IntLiteral
)
term
;
getContentHandler
(
)
.
startIntegerTerm
(
jplInteger
.
longValue
(
)
)
;
}
else
if
(
numericType
.
isFloat
(
)
)
{
FloatLiteral
jplFloat
=
(
FloatLiteral
)
term
;
getContentHandler
(
)
.
startFloatTerm
(
jplFloat
.
doubleValue
(
)
)
;
}
}
else
if
(
term
.
isVar
(
)
)
{
Variable
var
=
(
Variable
)
term
;
getContentHandler
(
)
.
startVariable
(
interner
.
getVariableName
(
var
.
getName
(
)
)
)
;
}
else
if
(
term
.
isAtom
(
)
)
{
Functor
atom
=
(
Functor
)
term
;
getContentHandler
(
)
.
startAtom
(
interner
.
getFunctorName
(
atom
.
getName
(
)
)
)
;
}
else
if
(
term
.
isCompound
(
)
)
{
Functor
functor
=
(
Functor
)
term
;
getContentHandler
(
)
.
startCompound
(
)
;
getContentHandler
(
)
.
startAtom
(
interner
.
getFunctorName
(
functor
.
getName
(
)
)
)
;
for
(
com
.
thesett
.
aima
.
logic
.
fol
.
Term
child
:
functor
.
getArguments
(
)
)
{
read
(
child
)
;
}
getContentHandler
(
)
.
endCompound
(
)
;
}
else
{
throw
new
IllegalStateException
(
"Unrecognized Lojix term: "
+
term
)
;
}
}

Reads a Lojix term and invoked appropriate methods on the content handler to describe its structure and contents
to it.

@param term The Lojix term to read.

Reads a Lojix term and invoked appropriate methods on the content handler to describe its structure and contents to it .


public static boolean classExistsAndIsLoadable(String className)
    {
        try
        {
            Class.forName(className);

            return true;
        }
        catch (ClassNotFoundException e)
        {
            // Exception noted and ignored.
            e = null;

            return false;
        }
    }

public
static
boolean
classExistsAndIsLoadable
(
String
className
)
{
try
{
Class
.
forName
(
className
)
;
return
true
;
}
catch
(
ClassNotFoundException
e
)
{
// Exception noted and ignored.
e
=
;
return
false
;
}
}

Checks if the named class exists and is loadable.

@param  className The class to check for.

@return <tt>true</tt> if the named class exists and is loadable.

Checks if the named class exists and is loadable .


public static boolean isSubTypeOf(Class parent, String className)
    {
        try
        {
            Class cls = Class.forName(className);

            return parent.isAssignableFrom(cls);
        }
        catch (ClassNotFoundException e)
        {
            // Exception noted and ignored.
            e = null;

            return false;
        }
    }

public
static
boolean
isSubTypeOf
(
Class
parent
,
String
className
)
{
try
{
Class
cls
=
Class
.
forName
(
className
)
;
return
parent
.
isAssignableFrom
(
cls
)
;
}
catch
(
ClassNotFoundException
e
)
{
// Exception noted and ignored.
e
=
;
return
false
;
}
}

Checks if the named class exists and is loadable and is a sub-type of the specified class.

@param  parent    The class to check that the named class is a sub-type of.
@param  className The class to check for.

@return <tt>true</tt> if the named class exists and is loadable and is a sub-type of the specified class.

Checks if the named class exists and is loadable and is a sub - type of the specified class .


public static boolean isSubTypeOf(String parent, String child)
    {
        try
        {
            return isSubTypeOf(Class.forName(parent), Class.forName(child));
        }
        catch (ClassNotFoundException e)
        {
            // Exception noted so can be ignored.
            e = null;

            return false;
        }
    }

public
static
boolean
isSubTypeOf
(
String
parent
,
String
child
)
{
try
{
return
isSubTypeOf
(
Class
.
forName
(
parent
)
,
Class
.
forName
(
child
)
)
;
}
catch
(
ClassNotFoundException
e
)
{
// Exception noted so can be ignored.
e
=
;
return
false
;
}
}

Checks that the named child class is the same type or a sub-type of the named parent class.

@param  parent The parent class name.
@param  child  The child class name.

@return <tt>true</tt> if the named child class is the same type or a sub-type of the named parent class, <tt>
false</tt> otherwise.

Checks that the named child class is the same type or a sub - type of the named parent class .


public static boolean isSubTypeOf(Class parentClass, Class childClass)
    {
        try
        {
            // Check that the child class can be cast as a sub-type of the parent.
            childClass.asSubclass(parentClass);

            return true;
        }
        catch (ClassCastException e)
        {
            // Exception noted so can be ignored.
            e = null;

            return false;
        }
    }

Checks that the child class is the same type or a sub-type of the parent class.

@param  parentClass The parent class.
@param  childClass  The child class.

@return <tt>true</tt> if the child class is the same type or a sub-type of the parent class, <tt>false</tt>
otherwise.

Checks that the child class is the same type or a sub - type of the parent class .


public static Class<?> forName(String className)
    {
        try
        {
            return Class.forName(className);
        }
        catch (ClassNotFoundException e)
        {
            throw new ReflectionUtilsException("ClassNotFoundException whilst finding class: " + className + ".", e);
        }
    }

Gets the Class object for a named class.

@param  className The class to get the Class object for.

@return The Class object for the named class.

Gets the Class object for a named class .


public static <T> T newInstance(Class<T> cls)
    {
        try
        {
            return cls.newInstance();
        }
        catch (InstantiationException e)
        {
            throw new ReflectionUtilsException("InstantiationException whilst instantiating class.", e);
        }
        catch (IllegalAccessException e)
        {
            throw new ReflectionUtilsException("IllegalAccessException whilst instantiating class.", e);
        }
    }

Creates an instance of a Class, instantiated through its no-args constructor.

@param  cls The Class to instantiate.
@param  <T> The Class type.

@return An instance of the class.

Creates an instance of a Class instantiated through its no - args constructor .


public static <T> T newInstance(Constructor<T> constructor, Object[] args)
    {
        try
        {
            return constructor.newInstance(args);
        }
        catch (InstantiationException e)
        {
            throw new IllegalStateException(e);
        }
        catch (IllegalAccessException e)
        {
            throw new IllegalStateException(e);
        }
        catch (InvocationTargetException e)
        {
            throw new IllegalStateException(e);
        }
    }

public static < T > T newInstance ( Constructor < T > constructor , Object [ ] args ) { try { return constructor . newInstance ( args ) ; } catch ( InstantiationException e ) { throw new IllegalStateException ( e ) ; } catch ( IllegalAccessException e ) { throw new IllegalStateException ( e ) ; } catch ( InvocationTargetException e ) { throw new IllegalStateException ( e ) ; } }

Calls a constuctor with the specified arguments.

@param  constructor The constructor.
@param  args        The arguments.
@param  <T>         The Class type.

@return An instance of the class that the constructor is for.

Calls a constuctor with the specified arguments .


public static Object callMethodOverridingIllegalAccess(Object o, String method, Object[] params,
        Class[] paramClasses)
    {
        // Get the objects class.
        Class cls = o.getClass();

        // Get the classes of the parameters.
        /*Class[] paramClasses = new Class[params.length];

        for (int i = 0; i < params.length; i++)
        {
            paramClasses[i] = params[i].getClass();
        }*/

        try
        {
            // Try to find the matching method on the class.

            Method m = cls.getDeclaredMethod(method, paramClasses);

            // Make it accessible.
            m.setAccessible(true);

            // Invoke it with the parameters.
            return m.invoke(o, params);
        }
        catch (NoSuchMethodException e)
        {
            throw new IllegalStateException(e);
        }
        catch (IllegalAccessException e)
        {
            throw new IllegalStateException(e);
        }
        catch (InvocationTargetException e)
        {
            throw new IllegalStateException(e);
        }
    }

Calls a named method on an object with a specified set of parameters, any Java access modifier are overridden.

@param  o            The object to call.
@param  method       The method name to call.
@param  params       The parameters to pass.
@param  paramClasses The argument types.

@return The return value from the method call.

Calls a named method on an object with a specified set of parameters any Java access modifier are overridden .


public static Object callMethod(Object o, String method, Object[] params)
    {
        // Get the objects class.
        Class cls = o.getClass();

        // Get the classes of the parameters.
        Class[] paramClasses = new Class[params.length];

        for (int i = 0; i < params.length; i++)
        {
            paramClasses[i] = params[i].getClass();
        }

        try
        {
            // Try to find the matching method on the class.
            Method m = cls.getMethod(method, paramClasses);

            // Invoke it with the parameters.
            return m.invoke(o, params);
        }
        catch (NoSuchMethodException e)
        {
            throw new IllegalStateException(e);
        }
        catch (IllegalAccessException e)
        {
            throw new IllegalStateException(e);
        }
        catch (InvocationTargetException e)
        {
            throw new IllegalStateException(e);
        }
    }

Calls a named method on an object with a specified set of parameters.

@param  o      The object to call.
@param  method The method name to call.
@param  params The parameters to pass.

@return The return value from the method call.

Calls a named method on an object with a specified set of parameters .


public static Object callStaticMethod(Method method, Object[] params)
    {
        try
        {
            return method.invoke(null, params);
        }
        catch (IllegalAccessException e)
        {
            throw new IllegalStateException(e);
        }
        catch (InvocationTargetException e)
        {
            throw new IllegalStateException(e);
        }
    }

public static Object callStaticMethod ( Method method , Object [ ] params ) { try { return method . invoke ( null , params ) ; } catch ( IllegalAccessException e ) { throw new IllegalStateException ( e ) ; } catch ( InvocationTargetException e ) { throw new IllegalStateException ( e ) ; } }

Calls a named static method on a class with a specified set of parameters.

@param  method The method name to call.
@param  params The parameters to pass.

@return The return value from the method call.

Calls a named static method on a class with a specified set of parameters .


public static <T> Constructor<T> getConstructor(Class<T> cls, Class[] args)
    {
        try
        {
            return cls.getConstructor(args);
        }
        catch (NoSuchMethodException e)
        {
            throw new IllegalStateException(e);
        }
    }

public static < T > Constructor < T > getConstructor ( Class < T > cls , Class [ ] args ) { try { return cls . getConstructor ( args ) ; } catch ( NoSuchMethodException e ) { throw new IllegalStateException ( e ) ; } }

Gets the constructor of a class that takes the specified set of arguments if any matches. If no matching
constructor is found then a runtime exception is raised.

@param  cls  The class to get a constructor from.
@param  args The arguments to match.
@param  <T>  The class type.

@return The constructor.

Gets the constructor of a class that takes the specified set of arguments if any matches . If no matching constructor is found then a runtime exception is raised .


public static Set<Class> findMatchingSetters(Class obClass, String propertyName)
    {
        /*log.fine("private Set<Class> findMatchingSetters(Object ob, String propertyName): called");*/
        Set<Class> types = new HashSet<Class>();

        // Convert the first letter of the property name to upper case to match against the upper case version of
        // it that will be in the setter method name. For example the property test will have a setter method called
        // setTest.
        String upperPropertyName = Character.toUpperCase(propertyName.charAt(0)) + propertyName.substring(1);

        // Scan through all the objects methods.
        Method[] methods = obClass.getMethods();

        for (Method nextMethod : methods)
        {
            // Get the next method.
            /*log.fine("nextMethod = " + nextMethod.getName());*/
            // Check if a method has the correct name, accessibility and the correct number of arguments to be a setter
            // method for the property.
            String methodName = nextMethod.getName();

            if (methodName.equals("set" + upperPropertyName) && Modifier.isPublic(nextMethod.getModifiers()) &&
                    (nextMethod.getParameterTypes().length == 1))
            {
                /*log.fine(methodName + " is a valid setter method for the property " + propertyName +
                        " with argument of type " + nextMethod.getParameterTypes()[0]);*/

                // Add its argument type to the array of setter types.
                types.add(nextMethod.getParameterTypes()[0]);
            }
        }

        return types;
    }

Finds the argument types of all setter methods on a bean for a given property name. For a method to be a setter
method it must have a void return type, be public and accept only a single argument. Its name must be 'set'
followed by the property name.

@param  obClass      The class to find all setter methods matching a given property for.
@param  propertyName The property name to find all matching setter methods for.

@return An array of the types (as classes) of all the possible types that the setter method can be called with.

Finds the argument types of all setter methods on a bean for a given property name . For a method to be a setter method it must have a void return type be public and accept only a single argument . Its name must be set followed by the property name .


public static <E> Queue<E> getTransactionalQueue(java.util.Queue<E> queue)
    {
        return new WrapperQueue<E>(queue, new LinkedList<E>(), true, false, false);
    }

public static < E > Queue < E > getTransactionalQueue ( java . util . Queue < E > queue ) { return new WrapperQueue < E > ( queue , new LinkedList < E > ( ) , true , false , false ) ; }

Provides a transactional queue, that delays all queue manipulation operations until the transaction is committed,
or erases them if it is rolled back.

@param  queue The queue to make transactional.
@param  <E>   The type of queue element.

@return A transactional queue.

Provides a transactional queue that delays all queue manipulation operations until the transaction is committed or erases them if it is rolled back .


public static <E> Queue<E> getTransactionalReQueue(java.util.Queue<E> queue, Collection<E> requeue)
    {
        return new WrapperQueue<E>(queue, requeue, true, false, false);
    }

public static < E > Queue < E > getTransactionalReQueue ( java . util . Queue < E > queue , Collection < E > requeue ) { return new WrapperQueue < E > ( queue , requeue , true , false , false ) ; }

Provides a transactional requeue, that delays all queue manipulation operations until the transaction is
committed, or erases them if it is rolled back. As this is a requeue, the requeue buffer may be examined directly
and the queue fully supports browsing with iterators.

@param  queue   The queue to use as the underlying queue implementation for the requeue.
@param  requeue The collection to use for the requeue buffer.
@param  <E>     The type of queue element.

@return A transactional requeue.

Provides a transactional requeue that delays all queue manipulation operations until the transaction is committed or erases them if it is rolled back . As this is a requeue the requeue buffer may be examined directly and the queue fully supports browsing with iterators .


public static Type getTypeFromObject(Object o)
    {
        // Check if the object is null, in which case its type cannot be derived.
        if (o == null)
        {
            return new UnknownType();
        }

        // Check if the object is an attribute a and get its type that way if possible.
        if (o instanceof Attribute)
        {
            return ((Attribute) o).getType();
        }

        // Return an approproate Type for the java primitive, wrapper or class type of the argument.
        return new JavaType(o);
    }

Gets the type of a specified object.

@param  o The object to get the type of.

@return The type of the object.


public void reset()
    {
        // Clear out the start states.
        startStates.clear();
        enqueuedOnce = false;

        // Reset the queue to a fresh empty queue.
        queue = createQueue();

        // Clear the goal predicate.
        goalPredicate = null;

        // Reset the maximum steps limit
        maxSteps = 0;

        // Reset the number of steps taken
        searchSteps = 0;

        // Reset the repeated state filter if there is one.
        if (repeatedStateFilter != null)
        {
            repeatedStateFilter.reset();
        }

        // Reset the search alogorithm if it requires resettting.
        searchAlgorithm.reset();
    }

Resets the search, clearing out the queue and setting it to contain just the start state node.

Resets the search clearing out the queue and setting it to contain just the start state node .


public T search() throws SearchNotExhaustiveException
    {
        SearchNode<O, T> path = findGoalPath();

        if (path != null)
        {
            return path.getState();
        }
        else
        {
            return null;
        }
    }

public T search ( ) throws SearchNotExhaustiveException { SearchNode < O , T > path = findGoalPath ( ) ; if ( path != null ) { return path . getState ( ) ; } else { return null ; } }

Perform the search. This can be called multiple times to get successive results where more than one goal can be
found, if the algorithm supports this. In this case it should return null once no more goals can be found.

@return The first state corresponding to a goal state that is found or null if none can be found after exhaustive
searching. A return value of null should really mean that exhaustive searching has been completed rather
than some premature termination condition being reached. See the comment below about the
SearchNotExhaustiveException.

@throws SearchNotExhaustiveException If the search stops before finding a solution or exhausting the search
space. Different search algorithms may fail for different reasons but in
particular it it is worth noting that if the maximum number of steps is
reached without exhausting the search space this will cause an exception to
be thrown rather than for this method to return null.

Perform the search . This can be called multiple times to get successive results where more than one goal can be found if the algorithm supports this . In this case it should return null once no more goals can be found .


public static Type createInstance(String name, int min, int max)
    {
        // Ensure that min is less than or equal to max.
        if (min > max)
        {
            throw new IllegalArgumentException("'min' must be less than or equal to 'max'.");
        }

        synchronized (INT_RANGE_TYPES)
        {
            // Add the newly created type to the map of all types.
            IntRangeType newType = new IntRangeType(name, min, max);

            // Ensure that the named type does not already exist, unless it has an identical definition already, in which
            // case the old definition can be re-used and the new one discarded.
            IntRangeType oldType = INT_RANGE_TYPES.get(name);

            if ((oldType != null) && !oldType.equals(newType))
            {
                throw new IllegalArgumentException("The type '" + name + "' already exists and cannot be redefined.");
            }
            else if ((oldType != null) && oldType.equals(newType))
            {
                return oldType;
            }
            else
            {
                INT_RANGE_TYPES.put(name, newType);

                return newType;
            }
        }
    }

Creates a new int range type with the specified name, if it does not already exist.

@param  name The name of the int range type to create.
@param  min  The minimum value that an instance of the type can take.
@param  max  The maximum value that an instance of teh type can take.

@return A new int range type.

@throws IllegalArgumentException If min is not less than or equal to max, or the named type already exists.

Creates a new int range type with the specified name if it does not already exist .


public void addSupportedTZ(String tzName) {
        if (!StringUtils.isBlank(tzName) && !tzNamesAliases.containsKey(tzName.trim())) {
            tzNamesAliases.put(tzName.trim(), tzName.trim());
            if (LOG.isInfoEnabled()) {
                LOG.info("Endpoint " + this.getEndPointName() + " - add support of TZ: " + tzName);
            }
        }
    }

public
void
addSupportedTZ
(
String
tzName
)
{
if
(
!
StringUtils
.
isBlank
(
tzName
)
&&
!
tzNamesAliases
.
containsKey
(
tzName
.
trim
(
)
)
)
{
tzNamesAliases
.
put
(
tzName
.
trim
(
)
,
tzName
.
trim
(
)
)
;
if
(
LOG
.
isInfoEnabled
(
)
)
{
LOG
.
info
(
"Endpoint "
+
this
.
getEndPointName
(
)
+
" - add support of TZ: "
+
tzName
)
;
}
}
}

Add a new supported tz. Add one aliase with the same name

@param tzName

Add a new supported tz . Add one aliase with the same name


public void addTZAlternateDimension(String orignalDimensionName, DimensionTable alternateDimension, String tzName) {
        addSupportedTZ(tzName);
        if (tzNamesAliases.containsValue(tzName)) {
            sqlTables.put(alternateDimension.getTableName(), alternateDimension);
            alternateDimensions.put(Pair.of(orignalDimensionName.toUpperCase(), tzName), alternateDimension);
        } else {
            LOG.error("Unsuported timezone: " + tzName);
        }
    }

public
void
addTZAlternateDimension
(
String
orignalDimensionName
,
DimensionTable
alternateDimension
,
String
tzName
)
{
addSupportedTZ
(
tzName
)
;
if
(
tzNamesAliases
.
containsValue
(
tzName
)
)
{
sqlTables
.
put
(
alternateDimension
.
getTableName
(
)
,
alternateDimension
)
;
alternateDimensions
.
put
(
Pair
.
of
(
orignalDimensionName
.
toUpperCase
(
)
,
tzName
)
,
alternateDimension
)
;
}
else
{
LOG
.
error
(
"Unsuported timezone: "
+
tzName
)
;
}
}


public void addDimension(DimensionTable table, boolean mandatory) {
        sqlTables.put(table.getTableName(), table);
        dimensions.put(table.getDimensionName().toUpperCase(), table);
        if (mandatory) {
            mandatoryDimensionNames.add(table.getDimensionName().toUpperCase(Locale.ENGLISH));
        }
    }

public void addDimension ( DimensionTable table , boolean mandatory ) { sqlTables . put ( table . getTableName ( ) , table ) ; dimensions . put ( table . getDimensionName ( ) . toUpperCase ( ) , table ) ; if ( mandatory ) { mandatoryDimensionNames . add ( table . getDimensionName ( ) . toUpperCase ( Locale . ENGLISH ) ) ; } }

Add a dimension as mandatory.
Mandatory dimension names are stored in upper case.

@param table     The dimension table
@param mandatory Add if true, remove otherwise

Add a dimension as mandatory . Mandatory dimension names are stored in upper case .


public static Set<Variable> findFreeVariables(Term query)
    {
        QueueBasedSearchMethod<Term, Term> freeVarSearch = new DepthFirstSearch<Term, Term>();
        freeVarSearch.reset();
        freeVarSearch.addStartState(query);
        freeVarSearch.setGoalPredicate(new FreeVariablePredicate());

        return (Set<Variable>) (Set) Searches.setOf(freeVarSearch);
    }

public static Set < Variable > findFreeVariables ( Term query ) { QueueBasedSearchMethod < Term , Term > freeVarSearch = new DepthFirstSearch < Term , Term > ( ) ; freeVarSearch . reset ( ) ; freeVarSearch . addStartState ( query ) ; freeVarSearch . setGoalPredicate ( new FreeVariablePredicate ( ) ) ; return ( Set < Variable > ) ( Set ) Searches . setOf ( freeVarSearch ) ; }

Calculates the set of free variables in a term.

@param  query The term to calculate the free non-anonymous variable set from.

@return A set of variables that are free and non-anonymous in the term.

Calculates the set of free variables in a term .


public static Set<Variable> findFreeNonAnonymousVariables(Term query)
    {
        QueueBasedSearchMethod<Term, Term> freeVarSearch = new DepthFirstSearch<Term, Term>();
        freeVarSearch.reset();
        freeVarSearch.addStartState(query);
        freeVarSearch.setGoalPredicate(new FreeNonAnonymousVariablePredicate());

        return (Set<Variable>) (Set) Searches.setOf(freeVarSearch);
    }

public static Set < Variable > findFreeNonAnonymousVariables ( Term query ) { QueueBasedSearchMethod < Term , Term > freeVarSearch = new DepthFirstSearch < Term , Term > ( ) ; freeVarSearch . reset ( ) ; freeVarSearch . addStartState ( query ) ; freeVarSearch . setGoalPredicate ( new FreeNonAnonymousVariablePredicate ( ) ) ; return ( Set < Variable > ) ( Set ) Searches . setOf ( freeVarSearch ) ; }

Calculates the set of free and non-anonymous variables in a term. This is the set of variables that a user query
usually wants to be made aware of.

@param  query The term to calculate the free non-anonymous variable set from.

@return A set of variables that are free and non-anonymous in the term.

Calculates the set of free and non - anonymous variables in a term . This is the set of variables that a user query usually wants to be made aware of .


public int compare(SearchNode object1, SearchNode object2)
    {
        float h1 = ((HeuristicSearchNode) object1).getH();
        float h2 = ((HeuristicSearchNode) object2).getH();

        return (h1 > h2) ? 1 : ((h1 < h2) ? -1 : 0);
    }

public int compare ( SearchNode object1 , SearchNode object2 ) { float h1 = ( ( HeuristicSearchNode ) object1 ) . getH ( ) ; float h2 = ( ( HeuristicSearchNode ) object2 ) . getH ( ) ; return ( h1 > h2 ) ? 1 : ( ( h1 < h2 ) ? - 1 : 0 ) ; }

Compares two heuristic search nodes by their heuristic values.

@param  object1 The first search node to compare.
@param  object2 The second search node to compare.

@return 1 if the first search node has a larger heuristic value than the second, -1 if it has a smaller heuristic
value and 0 if they are the same.

Compares two heuristic search nodes by their heuristic values .


public static void writeObjectToFile(String outputFileName, Object toWrite, boolean append)
    {
        // Open the output file.
        Writer resultWriter;

        try
        {
            resultWriter = new FileWriter(outputFileName, append);
        }
        catch (IOException e)
        {
            throw new IllegalStateException("Unable to open the output file '" + outputFileName + "' for writing.", e);
        }

        // Write the object into the output file.
        try
        {
            resultWriter.write(toWrite.toString());
            resultWriter.flush();
            resultWriter.close();
        }
        catch (IOException e)
        {
            throw new IllegalStateException("There was an error whilst writing to the output file '" + outputFileName + "'.",
                e);
        }
    }

Writes an object, using its 'toString' method, to the named file. The object may optionally be appended to the
file, or may overwrite it.

@param outputFileName The name of the file to write the output to.
@param toWrite        The object to write to the file.
@param append         <tt>true</tt> to append to the file, <tt>false</tt> to overwrite.

Writes an object using its toString method to the named file . The object may optionally be appended to the file or may overwrite it .


private static String readStreamAsString(BufferedInputStream is)
    {
        try
        {
            byte[] data = new byte[4096];

            StringBuffer inBuffer = new StringBuffer();

            int read;

            while ((read = is.read(data)) != -1)
            {
                String s = new String(data, 0, read);
                inBuffer.append(s);
            }

            return inBuffer.toString();
        }
        catch (IOException e)
        {
            throw new IllegalStateException(e);
        }
    }

private static String readStreamAsString ( BufferedInputStream is ) { try { byte [ ] data = new byte [ 4096 ] ; StringBuffer inBuffer = new StringBuffer ( ) ; int read ; while ( ( read = is . read ( data ) ) != - 1 ) { String s = new String ( data , 0 , read ) ; inBuffer . append ( s ) ; } return inBuffer . toString ( ) ; } catch ( IOException e ) { throw new IllegalStateException ( e ) ; } }

Reads the contents of a reader, one line at a time until the end of stream is encountered, and returns all
together as a string.

@param  is The reader.

@return The contents of the reader.

Reads the contents of a reader one line at a time until the end of stream is encountered and returns all together as a string .


public SearchNode<O, T> createSearchNode(T state)
    {
        return new HeuristicSearchNode<O, T>(state, heuristic);
    }

public SearchNode < O , T > createSearchNode ( T state ) { return new HeuristicSearchNode < O , T > ( state , heuristic ) ; }

Creates the correct type of search nodes for this search. This search uses heuristic search nodes.

@param  state The search space state to create a search node for.

@return The state encapsulated in a heuristic search node.

Creates the correct type of search nodes for this search . This search uses heuristic search nodes .


public String generateTraceIndent(int delta)
    {
        if (!useIndent)
        {
            return "";
        }
        else
        {
            if (delta >= 1)
            {
                indentStack.push(delta);
            }
            else if (delta < 0)
            {
                indentStack.pop();
            }

            StringBuffer result = new StringBuffer();

            traceIndent += (delta < 0) ? delta : 0;

            for (int i = 0; i < traceIndent; i++)
            {
                result.append(" ");
            }

            traceIndent += (delta > 0) ? delta : 0;

            return result.toString();
        }
    }

public
String
generateTraceIndent
(
int
delta
)
{
if
(
!
useIndent
)
{
return
""
;
}
else
{
if
(
delta
>=
1
)
{
indentStack
.
push
(
delta
)
;
}
else
if
(
delta
<
0
)
{
indentStack
.
pop
(
)
;
}
StringBuffer
result
=
new
StringBuffer
(
)
;
traceIndent
+=
(
delta
<
0
)
delta
:
0
;
for
(
int
i
=
0
;
i
<
traceIndent
;
i
++
)
{
result
.
append
(
" "
)
;
}
traceIndent
+=
(
delta
>
0
)
delta
:
0
;
return
result
.
toString
(
)
;
}
}

Generates a sequence of spaces to indent debugging output with.

@param  delta The amount to change the current trace indent by. If this is negative it is subtracted before the
sequence of spaces is generated, if it is positive it is added after.

@return A sequence of spaces to use for nesting call traces in debug output with.

Generates a sequence of spaces to indent debugging output with .


protected void allocateArgumentRegisters(Functor expression)
    {
        // Assign argument registers to functors appearing directly in the argument of the outermost functor.
        // Variables are never assigned directly to argument registers.
        int reg = 0;

        for (; reg < expression.getArity(); reg++)
        {
            Term term = expression.getArgument(reg);

            if (term instanceof Functor)
            {
                /*log.fine("X" + lastAllocatedTempReg + " = " + interner.getFunctorFunctorName((Functor) term));*/

                int allocation = (reg & 0xff) | (REG_ADDR << 8);
                symbolTable.put(term.getSymbolKey(), SymbolTableKeys.SYMKEY_ALLOCATION, allocation);
            }
        }
    }

For a predicate of arity n, the first n registers are used to receive its arguments in.

Non-variable arguments appearing directly within a functor are allocated to argument registers. This means
that they are directly referenced from the argument registers that pass them to predicate calls, or directly
referenced from the argument registers that are used to read them as call arguments.

Variables appearing as functor arguments are not allocated in this way, but are kept in registers with
positions higher than the number of arguments. The reason for this, is that a variable can appear multiple times
in an expression; it may not always be the same argument. Variables are assigned to other registers, then copied
into the argument registers as needed.

Argument registers are allocated by argument position within the functor. This means that gaps will be left
in the numbering for variables to be copied in as needed.

@param expression The clause head functor to allocate argument registers to.

For a predicate of arity n the first n registers are used to receive its arguments in .


private boolean isLastBodyTermInArgPositionOnly(Term var, Functor body)
    {
        return body == symbolTable.get(var.getSymbolKey(), SymbolTableKeys.SYMKEY_VAR_LAST_ARG_FUNCTOR);
    }

private boolean isLastBodyTermInArgPositionOnly ( Term var , Functor body ) { return body == symbolTable . get ( var . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VAR_LAST_ARG_FUNCTOR ) ; }

Checks if a variable is appearing within the last body functor in which it occurs, and only does so within
argument position.

@param  var  The variable to check.
@param  body The current body functor being processed.

@return <tt>true</tt> iff this is the last body functor that the variable appears in and does so only in argument
position.

Checks if a variable is appearing within the last body functor in which it occurs and only does so within argument position .


private OrdinalAttribute getMajorityClassification(String property, Iterable<State> examples)
        throws LearningFailureException
    {
        /*log.fine("private OrdinalAttribute getMajorityClassification(String property, Collection<State> examples): called");*/
        /*log.fine("property = " + property);*/

        // Flag used to indicate that the map to hold the value counts in has been initialized.
        Map<OrdinalAttribute, Integer> countMap = null;

        // Used to hold the biggest count found so far.
        int biggestCount = 0;

        // Used to hold the value with the biggest count found so far.
        OrdinalAttribute biggestAttribute = null;

        // Loop over all the examples counting the number of occurences of each possible classification by the
        // named property.
        for (State example : examples)
        {
            OrdinalAttribute nextAttribute = (OrdinalAttribute) example.getProperty(property);
            /*log.fine("nextAttribute = " + nextAttribute);*/

            // If this is the first attribute then find out how many possible values it can take on.
            if (countMap == null)
            {
                // A check has already been performed at the start of the learning method to ensure that the output
                // property only takes on a finite number of values.
                countMap = new HashMap<OrdinalAttribute, Integer>();
            }

            int count;

            // Increment the count for the number of occurences of this classification.
            if (!countMap.containsKey(nextAttribute))
            {
                count = 1;
                countMap.put(nextAttribute, count);
            }
            else
            {
                count = countMap.get(nextAttribute);
                countMap.put(nextAttribute, count++);
            }

            // Compare it to the biggest score found so far to see if it is bigger.
            if (count > biggestCount)
            {
                // Update the biggest score.
                biggestCount = count;

                // Update the value of the majority classification.
                biggestAttribute = nextAttribute;
            }
        }

        // Return the majority classification found.
        return biggestAttribute;
    }

This helper method works out how the majority of the specified examples are classified by the named property. The
property should always be the goal property that the algorithm is learning and must always take on a finite
number of different values.

@param  property The name of the property to find the majority classification for.
@param  examples A collection of state objects to count over in order to find the majority classification for the
named property.

@return The value of the majority classification for the named property or null if the example collection was
empty so no majority could be found.

@throws LearningFailureException If the number of possible value that the specified property can take on is not
finite.

This helper method works out how the majority of the specified examples are classified by the named property . The property should always be the goal property that the algorithm is learning and must always take on a finite number of different values .


private boolean allHaveSameClassification(String property, Iterable<State> examples)
    {
        // Used to hold the value of the first attribute seen.
        OrdinalAttribute firstAttribute = null;

        // Flag used to indicate that the test passed successfully.
        boolean success = true;

        // Loop over all the examples.
        for (State example : examples)
        {
            OrdinalAttribute nextAttribute = (OrdinalAttribute) example.getProperty(property);

            // If this is the first example just store its attribute value.
            if (firstAttribute == null)
            {
                firstAttribute = nextAttribute;
            }

            // Otherwise check if the attribute value does not match the first one in which case the test fails.
            else if (!nextAttribute.equals(firstAttribute))
            {
                success = false;

                break;
            }
        }

        // If the test passed then store the matching classification that all the examples have in a memeber variable
        // from where it can be accessed.
        if (success)
        {
            allClassification = firstAttribute;
        }

        return success;
    }

Tests if a property of a set of examples has the same value for all the examples. This algorithm works by
iterating through the examples until two different values are found or the end of the collection is reached
having found only one value.

<p>As a side effect this method leaves the value of the classification in the member variable
{@link #allClassification} when all the examples do match.

@param  property The name of the property to test.
@param  examples A collection of state objects to iterate over in order to test if they all have the same value
for the named property.

@return true if they all have the same value; false otherwise.

Tests if a property of a set of examples has the same value for all the examples . This algorithm works by iterating through the examples until two different values are found or the end of the collection is reached having found only one value .


private String chooseBestPropertyToDecideOn(String outputProperty, Iterable<State> examples,
        Iterable<String> inputProperties)
    {
        /*log.fine("private String chooseBestPropertyToDecideOn(String outputProperty, Collection<State> examples, " +
         "Collection<String> inputProperties): called");*/

        // for (State e : examples) /*log.fine(e);*/

        // Determine how many possible values (symbols) the output property can have.
        int numOutputValues =
            examples.iterator().next().getComponentType().getPropertyType(outputProperty).getNumPossibleValues();

        // Used to hold the largest information gain found so far.
        double largestGain = 0.0d;

        // Used to hold the input property that gives the largest gain found so far.
        String largestGainProperty = null;

        // Loop over all the input properties.
        for (String inputProperty : inputProperties)
        {
            // let G = the set of goal property values.
            // let A = the set of property values that the input property can have.

            // Determine how many possible values (symbols) the input property can have.
            int numInputValues =
                examples.iterator().next().getComponentType().getPropertyType(inputProperty).getNumPossibleValues();

            // Create an array to hold the counts of the output symbols.
            int[] outputCounts = new int[numOutputValues];

            // Create arrays to hold the counts of the input symbols and the joint input/output counts.
            int[] inputCounts = new int[numInputValues];
            int[][] jointCounts = new int[numInputValues][numOutputValues];

            // Loop over all the examples.
            for (State example : examples)
            {
                // Extract the output property attribute value.
                OrdinalAttribute outputAttribute = (OrdinalAttribute) example.getProperty(outputProperty);

                // Extract the input property attribute value.
                OrdinalAttribute inputAttribute = (OrdinalAttribute) example.getProperty(inputProperty);

                // Increment the count for the occurence of this value of the output property.
                outputCounts[outputAttribute.ordinal()]++;

                // Increment the count for the occurence of this value of the input property.
                inputCounts[inputAttribute.ordinal()]++;

                // Increment the count for the joint occurrence of this input/output value pair.
                jointCounts[inputAttribute.ordinal()][outputAttribute.ordinal()]++;
            }

            // Calculate the estimated probability distribution of G from the occurrence counts over the examples.
            double[] pForG = InformationTheory.pForDistribution(outputCounts);

            // Calculate the estimated probability distribution of A from the occurrence counts over the examples.
            double[] pForA = InformationTheory.pForDistribution(inputCounts);

            // Calculate the estimated probability distribution p(g|a) from the joint occurrence counts over the
            // examples.
            double[][] pForGGivenA = InformationTheory.pForJointDistribution(jointCounts);

            // Calculate the information gain on G by knowing A.
            double gain = InformationTheory.gain(pForG, pForA, pForGGivenA);

            // Check if the gain is larger than the best found so far and update the best if so.
            if (gain > largestGain)
            {
                largestGain = gain;
                largestGainProperty = inputProperty;
            }
        }

        return largestGainProperty;
    }

For a given set of examples, input properties and an output property this method chooses the input property that
provides the largest information gain on the value of the output property.

@param  outputProperty  The name of the property to compare the information gain of the input properties against.
@param  examples        A collection of state objects to count over in order to find the highest information gain
input property.
@param  inputProperties A collection of input properties to find the best one amongst.

@return The name of the input property with the highest information gain.

For a given set of examples input properties and an output property this method chooses the input property that provides the largest information gain on the value of the output property .


public Functor functor(String name, Term... args)
    {
        int internedName = interner.internFunctorName(name, args.length);

        return new Functor(internedName, args);
    }

public Functor functor ( String name , Term ... args ) { int internedName = interner . internFunctorName ( name , args . length ) ; return new Functor ( internedName , args ) ; }

Creates a functor.

@param  name The name of the functor.
@param  args The functors arguments.

@return A functor.


public Variable var(String name)
    {
        boolean isAnonymous = name.startsWith("_");
        int internedName = interner.internVariableName(name);

        return new Variable(internedName, null, isAnonymous);
    }

public Variable var ( String name ) { boolean isAnonymous = name . startsWith ( "_" ) ; int internedName = interner . internVariableName ( name ) ; return new Variable ( internedName , null , isAnonymous ) ; }

Creates a variable. If the variable name begins with an underscore "_", it will be anonymous, otherwise it will
be named.

@param  name The name of the variable.

@return A variable.

Creates a variable . If the variable name begins with an underscore _ it will be anonymous otherwise it will be named .


public ActionForward executeWithErrorHandling(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response, ActionErrors errors)
    {
        log.fine("public ActionForward performWithErrorHandling(ActionMapping mapping, ActionForm form," +
            "HttpServletRequest request, HttpServletResponse response, " + "ActionErrors errors): called");

        HttpSession session = request.getSession();
        DynaBean dynaForm = (DynaActionForm) form;

        // Redirect to the specified location
        String redirect = (String) dynaForm.get(REDIRECT);

        log.fine("redirect = " + redirect);

        return new ActionForward(redirect, true);
    }

Handles an HTTP request sent to this action by struts. This simply forwards to the location specified by the
"redirect" request parameter.

@param  mapping  The Struts action mapping.
@param  form     The Struts form associated with this action.
@param  request  The HTTP request.
@param  response The HTTP response.
@param  errors   The Struts action errors object to place any errors in.

@return A forward to the "redirect" location.

Handles an HTTP request sent to this action by struts . This simply forwards to the location specified by the redirect request parameter .


public List<E> get(int index)
    {
        /*log.fine("public List<E> get(int index): called");*/

        // Check that the index is not to large.
        int originalSize = original.size();
        int size = (originalSize / pageSize) + (((originalSize % pageSize) == 0) ? 0 : 1);

        /*log.fine("originalSize = " + originalSize);*/
        /*log.fine("size = " + size);*/

        // Check if the size of the underlying list is zero, in which case return an empty list, so long as page zero
        // was requested.
        if ((index == 0) && (originalSize == 0))
        {
            return new ArrayList<E>();
        }

        // Check if the requested index exceeds the number of pages, or is an illegal negative value.
        if ((index >= size) || (index < 0))
        {
            /*log.fine("(index >= size) || (index < 0), throwing out of bounds exception.");*/
            throw new IndexOutOfBoundsException("Index " + index +
                " is less than zero or more than the number of pages: " + size);
        }

        // Extract the appropriate sub-list.
        // Note that if this is the last page it may not be a full page. Just up to the last page will be returned.
        /*log.fine("Requesting sublist from, " + (pageSize * index) + ", to ," +
            (((pageSize * (index + 1)) >= originalSize) ? originalSize : (pageSize * (index + 1))) + ".");*/

        List<E> result =
            original.subList(pageSize * index,
                ((pageSize * (index + 1)) >= originalSize) ? originalSize : (pageSize * (index + 1)));

        return result;
    }

Extracts the sub-list at the specified page index. The returned list will have size equal to the page size unless
it is the last page in which case it may not be a full page.

@param  index The sub-list index to extract.

@return The sub-list as a {@link java.util.List}.

@throws IndexOutOfBoundsException If the index is < 0 or larger that the number of pages (list size / page size +
(list size % page size == 0 ? 0 : 1)).

Extracts the sub - list at the specified page index . The returned list will have size equal to the page size unless it is the last page in which case it may not be a full page .


public void setTexture(Paint obj)
    {
        if (obj instanceof GradientPaint)
        {
            texture = new GradientPaint(0, 0, Color.white, getSize().width * 2, 0, Color.green);
        }
        else
        {
            texture = obj;
        }
    }

public void setTexture ( Paint obj ) { if ( obj instanceof GradientPaint ) { texture = new GradientPaint ( 0 , 0 , Color . white , getSize ( ) . width * 2 , 0 , Color . green ) ; } else { texture = obj ; } }

Sets the kind of paint to use. For the image background?

@param obj The paint to use.

Sets the kind of paint to use . For the image background?


public void paintImmediately(int x, int y, int w, int h)
    {
        RepaintManager repaintManager = null;
        boolean save = true;

        if (!isDoubleBuffered())
        {
            repaintManager = RepaintManager.currentManager(this);
            save = repaintManager.isDoubleBufferingEnabled();
            repaintManager.setDoubleBufferingEnabled(false);
        }

        super.paintImmediately(x, y, w, h);

        if (repaintManager != null)
        {
            repaintManager.setDoubleBufferingEnabled(save);
        }
    }

public void paintImmediately ( int x , int y , int w , int h ) { RepaintManager repaintManager = null ; boolean save = true ; if ( ! isDoubleBuffered ( ) ) { repaintManager = RepaintManager . currentManager ( this ) ; save = repaintManager . isDoubleBufferingEnabled ( ) ; repaintManager . setDoubleBufferingEnabled ( false ) ; } super . paintImmediately ( x , y , w , h ) ; if ( repaintManager != null ) { repaintManager . setDoubleBufferingEnabled ( save ) ; } }

Immediately repaints the surface.

<p/>It's possible to turn off double-buffering for just the repaint calls invoked directly on the non double
buffered component. This can be done by overriding paintImmediately() (which is called as a result of repaint)
and getting the current RepaintManager and turning off double buffering in the RepaintManager before calling
super.paintImmediately(g).

@param x The X coord to start painting at.
@param y The Y coord to start painting at.
@param w The width of the region to paint.
@param h The height of the region to paint.


protected BufferedImage createBufferedImage(int w, int h, int imgType)
    {
        BufferedImage bi = null;

        if (imgType == 0)
        {
            bi = (BufferedImage) createImage(w, h);
        }
        else if ((imgType > 0) && (imgType < 14))
        {
            bi = new BufferedImage(w, h, imgType);
        }
        else if (imgType == 14)
        {
            bi = createBinaryImage(w, h, 2);
        }
        else if (imgType == 15)
        {
            bi = createBinaryImage(w, h, 4);
        }
        else if (imgType == 16)
        {
            bi = createSGISurface(w, h, 32);
        }
        else if (imgType == 17)
        {
            bi = createSGISurface(w, h, 16);
        }

        // Store the buffered image size
        biw = w;
        bih = h;

        return bi;
    }

protected
BufferedImage
createBufferedImage
(
int
w
,
int
h
,
int
imgType
)
{
BufferedImage
bi
=
;
if
(
imgType
==
0
)
{
bi
=
(
BufferedImage
)
createImage
(
w
,
h
)
;
}
else
if
(
(
imgType
>
0
)
&&
(
imgType
<
14
)
)
{
bi
=
new
BufferedImage
(
w
,
h
,
imgType
)
;
}
else
if
(
imgType
==
14
)
{
bi
=
createBinaryImage
(
w
,
h
,
2
)
;
}
else
if
(
imgType
==
15
)
{
bi
=
createBinaryImage
(
w
,
h
,
4
)
;
}
else
if
(
imgType
==
16
)
{
bi
=
createSGISurface
(
w
,
h
,
32
)
;
}
else
if
(
imgType
==
17
)
{
bi
=
createSGISurface
(
w
,
h
,
16
)
;
}
// Store the buffered image size
biw
=
w
;
bih
=
h
;
return
bi
;
}

Generates a fresh buffered image of the appropriate type.

@param  w       The image width.
@param  h       The image height.
@param  imgType The image type. Note that this should be two less than the image types defined as constants in
this class to correspond with the image type constants defined in BufferedImage. This class uses
0 for auto image type selection and 1 for direct to screen.

@return A buffered image of the specifed size and type.

Generates a fresh buffered image of the appropriate type .


protected Graphics2D createGraphics2D(int width, int height, BufferedImage bi, Graphics g)
    {
        Graphics2D g2 = null;

        // Check if the buffered image is null
        if (bi != null)
        {
            // Create Graphics2D context for the buffered image
            g2 = bi.createGraphics();
        }
        else
        {
            // The buffered image is null so create Graphics2D context for the Graphics context
            g2 = (Graphics2D) g;
        }

        // @todo what is this for?
        g2.setBackground(getBackground());

        // Set the rendering properties of the graphics context
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, antiAlias);
        g2.setRenderingHint(RenderingHints.KEY_RENDERING, rendering);

        // Check the clear flags to see if the graphics context should be cleared
        if (clearSurface || clearOnce)
        {
            // Clear the image
            g2.clearRect(0, 0, width, height);

            // Reset the clear once flag to show that clearing has been done
            clearOnce = false;
        }

        // Check if a background fill texture is to be used
        if (texture != null)
        {
            // set composite to opaque for texture fills
            g2.setComposite(AlphaComposite.SrcOver);
            g2.setPaint(texture);
            g2.fillRect(0, 0, width, height);
        }

        // Check if alpha compositing is to be used
        if (composite != null)
        {
            // Set the alpha compositing algorithm
            g2.setComposite(composite);
        }

        return g2;
    }

Creates a Graphics2D drawing context from a BufferedImage or Graphics context. The graphics context is built
using the properties defined for the surface. This method is used to generate the Graphics2D context that
subclasses will render in. IF the buffered image is null then the passed in Graphics context will be used to
generate the Graphics2D context. This is the case when no buffered image is used and the subclass renders
straight to the screen.

@param  width  The width of the buffered image.
@param  height The height of the buffered image.
@param  bi     The buffered image to generate a Graphics2D context for, or null if the next param is to be used.
@param  g      The Graphics context to generate a Graphics2D context for, only used if bi is null.

@return A Graphics2D drawing context of the specified size and type.

Creates a Graphics2D drawing context from a BufferedImage or Graphics context . The graphics context is built using the properties defined for the surface . This method is used to generate the Graphics2D context that subclasses will render in . IF the buffered image is null then the passed in Graphics context will be used to generate the Graphics2D context . This is the case when no buffered image is used and the subclass renders straight to the screen .


private BufferedImage createBinaryImage(int w, int h, int pixelBits)
    {
        int bytesPerRow = w * pixelBits / 8;

        if ((w * pixelBits % 8) != 0)
        {
            bytesPerRow++;
        }

        byte[] imageData = new byte[h * bytesPerRow];
        IndexColorModel cm = null;

        switch (pixelBits)
        {
        case 1:
        {
            cm = new IndexColorModel(pixelBits, lut1Arr.length, lut1Arr, lut1Arr, lut1Arr);
            break;
        }

        case 2:
        {
            cm = new IndexColorModel(pixelBits, lut2Arr.length, lut2Arr, lut2Arr, lut2Arr);
            break;
        }

        case 4:
        {
            cm = new IndexColorModel(pixelBits, lut4Arr.length, lut4Arr, lut4Arr, lut4Arr);
            break;
        }

        default:
        {
            new Exception("Invalid # of bit per pixel").printStackTrace();
        }
        }

        DataBuffer db = new DataBufferByte(imageData, imageData.length);
        WritableRaster r = Raster.createPackedRaster(db, w, h, pixelBits, null);

        return new BufferedImage(cm, r, false, null);
    }

private
BufferedImage
createBinaryImage
(
int
w
,
int
h
,
int
pixelBits
)
{
int
bytesPerRow
=
w
*
pixelBits
/
8
;
if
(
(
w
*
pixelBits
%
8
)
!=
0
)
{
bytesPerRow
++
;
}
byte
[
]
imageData
=
new
byte
[
h
*
bytesPerRow
]
;
IndexColorModel
cm
=
;
switch
(
pixelBits
)
{
case
1
:
{
cm
=
new
IndexColorModel
(
pixelBits
,
lut1Arr
.
length
,
lut1Arr
,
lut1Arr
,
lut1Arr
)
;
break
;
}
case
2
:
{
cm
=
new
IndexColorModel
(
pixelBits
,
lut2Arr
.
length
,
lut2Arr
,
lut2Arr
,
lut2Arr
)
;
break
;
}
case
4
:
{
cm
=
new
IndexColorModel
(
pixelBits
,
lut4Arr
.
length
,
lut4Arr
,
lut4Arr
,
lut4Arr
)
;
break
;
}
default
:
{
new
Exception
(
"Invalid # of bit per pixel"
)
.
printStackTrace
(
)
;
}
}
DataBuffer
db
=
new
DataBufferByte
(
imageData
,
imageData
.
length
)
;
WritableRaster
r
=
Raster
.
createPackedRaster
(
db
,
w
,
h
,
pixelBits
,
)
;
return
new
BufferedImage
(
cm
,
r
,
false
,
)
;
}

Creates a custom grey-scale binary image format.

@param  w         The image width.
@param  h         The image height.
@param  pixelBits The number of grey-scale bits to use. Must be 1, 2 or 4.

@return A buffered image of the specifed size and type.

Creates a custom grey - scale binary image format .


private BufferedImage createSGISurface(int w, int h, int pixelBits)
    {
        int rMask32 = 0xFF000000;
        int rMask16 = 0xF800;
        int gMask32 = 0x00FF0000;
        int gMask16 = 0x07C0;
        int bMask32 = 0x0000FF00;
        int bMask16 = 0x003E;
        DirectColorModel dcm = null;
        DataBuffer db = null;
        WritableRaster wr = null;

        switch (pixelBits)
        {
        case 16:
        {
            short[] imageDataUShort = new short[w * h];
            dcm = new DirectColorModel(16, rMask16, gMask16, bMask16);
            db = new DataBufferUShort(imageDataUShort, imageDataUShort.length);
            wr = Raster.createPackedRaster(db, w, h, w, new int[] { rMask16, gMask16, bMask16 }, null);

            break;
        }

        case 32:
        {
            int[] imageDataInt = new int[w * h];
            dcm = new DirectColorModel(32, rMask32, gMask32, bMask32);
            db = new DataBufferInt(imageDataInt, imageDataInt.length);
            wr = Raster.createPackedRaster(db, w, h, w, new int[] { rMask32, gMask32, bMask32 }, null);

            break;
        }

        default:
        {
            new Exception("Invalid # of bit per pixel").printStackTrace();
        }

        }

        return new BufferedImage(dcm, wr, false, null);
    }

private
BufferedImage
createSGISurface
(
int
w
,
int
h
,
int
pixelBits
)
{
int
rMask32
=
0xFF000000
;
int
rMask16
=
0xF800
;
int
gMask32
=
0x00FF0000
;
int
gMask16
=
0x07C0
;
int
bMask32
=
0x0000FF00
;
int
bMask16
=
0x003E
;
DirectColorModel
dcm
=
;
DataBuffer
db
=
;
WritableRaster
wr
=
;
switch
(
pixelBits
)
{
case
16
:
{
short
[
]
imageDataUShort
=
new
short
[
w
*
h
]
;
dcm
=
new
DirectColorModel
(
16
,
rMask16
,
gMask16
,
bMask16
)
;
db
=
new
DataBufferUShort
(
imageDataUShort
,
imageDataUShort
.
length
)
;
wr
=
Raster
.
createPackedRaster
(
db
,
w
,
h
,
w
,
new
int
[
]
{
rMask16
,
gMask16
,
bMask16
}
,
)
;
break
;
}
case
32
:
{
int
[
]
imageDataInt
=
new
int
[
w
*
h
]
;
dcm
=
new
DirectColorModel
(
32
,
rMask32
,
gMask32
,
bMask32
)
;
db
=
new
DataBufferInt
(
imageDataInt
,
imageDataInt
.
length
)
;
wr
=
Raster
.
createPackedRaster
(
db
,
w
,
h
,
w
,
new
int
[
]
{
rMask32
,
gMask32
,
bMask32
}
,
)
;
break
;
}
default
:
{
new
Exception
(
"Invalid # of bit per pixel"
)
.
printStackTrace
(
)
;
}
}
return
new
BufferedImage
(
dcm
,
wr
,
false
,
)
;
}

Creates a custom colour image format.

@param  w         The image width.
@param  h         The image height.
@param  pixelBits The number of bits-per-pixel to use. Must be 16 or 32.

@return A buffered image of the specifed size and type.


protected void setQueueSearchAlgorithm(QueueSearchAlgorithm<O, T> algorithm)
    {
        algorithm.setPeekAtHead(true);
        algorithm.setReverseEnqueueOrder(true);
        super.setQueueSearchAlgorithm(algorithm);
    }

protected void setQueueSearchAlgorithm ( QueueSearchAlgorithm < O , T > algorithm ) { algorithm . setPeekAtHead ( true ) ; algorithm . setReverseEnqueueOrder ( true ) ; super . setQueueSearchAlgorithm ( algorithm ) ; }

Allows different queue search algorithms to replace the default one. This overidden method ensures that the peek
at head flag is always set on the search algorithm and that it expands it successor nodes in reverse, as for
depth first searches.

@param algorithm The search algorithm to use.

Allows different queue search algorithms to replace the default one . This overidden method ensures that the peek at head flag is always set on the search algorithm and that it expands it successor nodes in reverse as for depth first searches .


public SearchNode search(QueueSearchState<O, T> initSearch, Collection<T> startStates, int maxSteps,
        int searchSteps) throws SearchNotExhaustiveException
    {
        // Iteratively increase the bound until a search succeeds.
        for (float bound = startBound;;)
        {
            // Set up the maximum bound for this iteration.
            maxBound = bound;

            // Use a try block as the depth bounded search will throw a MaxBoundException if it fails but there
            // are successors states known to exist beyond the current max depth fringe.
            try
            {
                // Get the number of search steps taken so far and pass this into the underlying depth bounded search
                // so that the step count limit carries over between successive iterations.
                int numStepsSoFar = initSearch.getStepsTaken();

                // Call the super class search method to perform a depth bounded search on this maximum bound starting
                // from the initial search state.
                initSearch.resetEnqueuedOnceFlag();

                SearchNode node = super.search(initSearch, startStates, maxSteps, numStepsSoFar);

                // Check if the current depth found a goal node
                if (node != null)
                {
                    return node;
                }

                // The depth bounded search returned null, so it has exhausted the search space. Return with null.
                else
                {
                    return null;
                }
            }

            // The depth bounded search failed but it knows that there are more successor states at deeper levels.
            catch (MaxBoundException e)
            {
                // Do nothing, no node found at this depth so continue at the next depth level
                e = null;
            }

            // Check if the bound should be increased by epsilon or to the next smallest bound property value
            // beyond the fringe and update the bound for the next iteration.
            if (useEpsilon)
            {
                bound = bound + epsilon;
            }
            else
            {
                bound = getMinBeyondBound();
            }
        }
    }

Search iteratively on increasing maximum bound limits until the search space is exhausted or a goal state is
found.

@param  initSearch  The algorithm to turn the start states into the intial set of search nodes, of the correct
type to begin the search with.
@param  startStates The set of start states to begin the search with.
@param  maxSteps    The maximum number of steps to search for before giving up. If this is 0 or less then no
maximum number is enforced.
@param  searchSteps The number of steps taken so far. This may be greater than 0 if this search is run
iteratively and previous iterations of it have already been run.

@return The first {@link SearchNode} corresponding to a goal state that is found or null if none can be found
after exhaustive searching.

@throws SearchNotExhaustiveException SearchNotExhaustiveException If the search terminates prematurely because
the maximum number of steps is reached.

Search iteratively on increasing maximum bound limits until the search space is exhausted or a goal state is found .


public SearchNode search(QueueSearchState<O, T> initSearch, Collection<T> startStates, int maxSteps,
        int searchSteps) throws SearchNotExhaustiveException
    {
        // Initialize the queue with the start states set up in search nodes if this has not already been done.
        // This will only be done on the first call to this method, as enqueueStartStates sets a flag when it is
        // done. Subsequent searches continue from where the previous search left off. Have to call reset on
        // the search method to really start the search again from the start states.
        Queue<SearchNode<O, T>> queue = initSearch.enqueueStartStates(startStates);

        // Get the goal predicate configured as part of the enqueueing start states process.
        UnaryPredicate<T> goalPredicate = initSearch.getGoalPredicate();

        // Keep running until the queue becomes empty or a goal state is found.
        while (!queue.isEmpty())
        {
            // Extract or peek at the head element from the queue.
            SearchNode<O, T> headNode = peekAtHead ? queue.peek() : queue.remove();

            // Expand the successors into the queue whether the current node is a goal state or not.
            // This prepares the queue for subsequent searches, ensuring that goal states do not block
            // subsequent goal states that exist beyond them.
            if (!headNode.isExpanded())
            {
                headNode.expandSuccessors(queue, reverseEnqueue);
            }

            // Get the node to be goal checked, either the head node or the new top of queue, depending on the
            // peek at head flag. Again this is only a peek, the node is only to be removed if it is to be
            // goal checked.
            SearchNode<O, T> currentNode = peekAtHead ? queue.peek() : headNode;

            // Only goal check leaves, or nodes already expanded. (The expanded flag will be set on leaves anyway).
            if (currentNode.isExpanded())
            {
                // If required, remove the node to goal check from the queue.
                currentNode = peekAtHead ? queue.remove() : headNode;

                // Check if the current node is a goal state.
                if (goalPredicate.evaluate(currentNode.getState()))
                {
                    return currentNode;
                }
            }

            // Check if there is a maximum number of steps limit and increase the step count and check the limit if so.
            if (maxSteps > 0)
            {
                searchSteps++;

                // Update the search state with the number of steps taken so far.
                initSearch.setStepsTaken(searchSteps);

                if (searchSteps >= maxSteps)
                {
                    // The maximum number of steps has been reached, however if the queue is now empty then the search
                    // has just completed within the maximum. Check if the queue is empty and return null if so.
                    if (queue.isEmpty())
                    {
                        return null;
                    }

                    // Quit without a solution as the max number of steps has been reached but because there are still
                    // more states in the queue then raise a search failure exception.
                    else
                    {
                        throw new SearchNotExhaustiveException("Maximum number of steps reached.", null);
                    }
                }
            }
        }

        // No goal state was found so return null
        return null;
    }

Search until a goal state is found or the maximum allowed number of steps is reached.

@param  initSearch  The algorithm to turn the start states into the intial set of search nodes, of the correct
type to begin the search with.
@param  startStates The set of start states to begin the search with.
@param  maxSteps    The maximum number of steps to search for before giving up. If this is 0 or less then no
maximum number is enforced.
@param  searchSteps The number of steps taken so far. This may be greater than 0 if this search is run
iteratively and previous iterations of it have already been run.

@return The first {@link SearchNode} corresponding to a goal state that is found or null if none can be found
after exhaustive searching.

@throws SearchNotExhaustiveException SearchNotExhaustiveException If the search terminates prematurely because
the maximum number of steps is reached.

Search until a goal state is found or the maximum allowed number of steps is reached .


public static void main(String[] args)
    {
        try
        {
            SimpleCharStream inputStream = new SimpleCharStream(System.in, null, 1, 1);
            PrologParserTokenManager tokenManager = new PrologParserTokenManager(inputStream);
            Source<Token> tokenSource = new TokenSource(tokenManager);

            PrologParser parser =
                new PrologParser(tokenSource,
                    new VariableAndFunctorInternerImpl("Prolog_Variable_Namespace", "Prolog_Functor_Namespace"));

            while (true)
            {
                // Parse the next sentence or directive.
                Object nextParsing = parser.clause();

                console.info(nextParsing.toString());
            }
        }
        catch (Exception e)
        {
            console.log(Level.SEVERE, e.getMessage(), e);
            System.exit(1);
        }
    }

Parses statements and print the parse tree to the console for quick interactive testing of the parser.

@param args The command line arguments.

Parses statements and print the parse tree to the console for quick interactive testing of the parser .


public Clause clause() throws SourceCodeException
    {
        // Each new sentence provides a new scope in which to make variables unique.
        variableContext.clear();

        Term term = term();

        Clause clause = TermUtils.convertToClause(term, interner);

        if (clause == null)
        {
            throw new SourceCodeException("Only queries and clauses are valid sentences in Prolog, not " + term + ".",
                null, null, null, term.getSourceCodePosition());
        }

        return clause;
    }

Parses a single sentence in first order logic. A sentence consists of a term followed by a full stop.

@return A sentence in first order logic.

@throws SourceCodeException If the token sequence does not parse into a valid sentence.

Parses a single sentence in first order logic . A sentence consists of a term followed by a full stop .


public List<Term> terms(List<Term> terms) throws SourceCodeException
    {
        Term term;

        Token nextToken = tokenSource.peek();

        switch (nextToken.kind)
        {
        case FUNCTOR:
            term = functor();
            break;

        case LSQPAREN:
            term = listFunctor();
            break;

        case VAR:
            term = variable();
            break;

        case INTEGER_LITERAL:
            term = intLiteral();
            break;

        case FLOATING_POINT_LITERAL:
            term = doubleLiteral();
            break;

        case STRING_LITERAL:
            term = stringLiteral();
            break;

        case ATOM:
            term = atom();
            break;

        case LPAREN:
            consumeToken(LPAREN);

            term = term();

            // Mark the term as bracketed to ensure that this is its final parsed form. In particular the
            // #arglist method will not break it up if it contains commas.
            term.setBracketed(true);

            consumeToken(RPAREN);
            break;

        default:
            throw new SourceCodeException("Was expecting one of " + BEGIN_TERM_TOKENS + " but got " +
                tokenImage[nextToken.kind] + ".", null, null, null,
                new SourceCodePositionImpl(nextToken.beginLine, nextToken.beginColumn, nextToken.endLine,
                    nextToken.endColumn));
        }

        terms.add(term);

        switch (tokenSource.peek().kind)
        {
        case LPAREN:
        case LSQPAREN:
        case INTEGER_LITERAL:
        case FLOATING_POINT_LITERAL:
        case STRING_LITERAL:
        case VAR:
        case FUNCTOR:
        case ATOM:
            terms(terms);
            break;

        default:
        }

        return terms;
    }

Recursively parses terms, which may be functors, atoms, variables, literals or operators, into a flat list in the
order in which they are encountered.

@param  terms A list of terms to accumulate in.

@return The list of terms encountered in order.

@throws SourceCodeException If the sequence of tokens does not form a valid syntactical construction as a list of
first order logic terms.

Recursively parses terms which may be functors atoms variables literals or operators into a flat list in the order in which they are encountered .


public Term functor() throws SourceCodeException
    {
        Token name = consumeToken(FUNCTOR);
        Term[] args = arglist();
        consumeToken(RPAREN);

        int nameId =
            interner.internFunctorName((args == null) ? name.image : name.image.substring(0, name.image.length() - 1),
                (args == null) ? 0 : args.length);

        Functor result = new Functor(nameId, args);

        SourceCodePosition position =
            new SourceCodePositionImpl(name.beginLine, name.beginColumn, name.endLine, name.endColumn);
        result.setSourceCodePosition(position);

        return result;
    }

public Term functor ( ) throws SourceCodeException { Token name = consumeToken ( FUNCTOR ) ; Term [ ] args = arglist ( ) ; consumeToken ( RPAREN ) ; int nameId = interner . internFunctorName ( ( args == null ) ? name . image : name . image . substring ( 0 , name . image . length ( ) - 1 ) , ( args == null ) ? 0 : args . length ) ; Functor result = new Functor ( nameId , args ) ; SourceCodePosition position = new SourceCodePositionImpl ( name . beginLine , name . beginColumn , name . endLine , name . endColumn ) ; result . setSourceCodePosition ( position ) ; return result ; }

Parses a single functor in first order logic with its arguments.

@return A single functor in first order logic with its arguments.

@throws SourceCodeException If the token sequence does not parse as a valid functor.

Parses a single functor in first order logic with its arguments .


public Term listFunctor() throws SourceCodeException
    {
        // Get the interned names of the nil and cons functors.
        int nilId = interner.internFunctorName("nil", 0);
        int consId = interner.internFunctorName("cons", 2);

        // A list always starts with a '['.
        Token leftDelim = consumeToken(LSQPAREN);

        // Check if the list contains any arguments and parse them if so.
        Term[] args = null;

        Token nextToken = tokenSource.peek();

        switch (nextToken.kind)
        {
        case LPAREN:
        case LSQPAREN:
        case INTEGER_LITERAL:
        case FLOATING_POINT_LITERAL:
        case STRING_LITERAL:
        case VAR:
        case FUNCTOR:
        case ATOM:
            args = arglist();
            break;

        default:
        }

        // Work out what the terminal element in the list is. It will be 'nil' unless an explicit cons '|' has
        // been used to specify a different terminal element. In the case where cons is used explciitly, the
        // list prior to the cons must not be empty.
        Term accumulator;

        if (tokenSource.peek().kind == CONS)
        {
            if (args == null)
            {
                throw new SourceCodeException("Was expecting one of " + BEGIN_TERM_TOKENS + " but got " +
                    tokenImage[nextToken.kind] + ".", null, null, null,
                    new SourceCodePositionImpl(nextToken.beginLine, nextToken.beginColumn, nextToken.endLine,
                        nextToken.endColumn));
            }

            consumeToken(CONS);

            accumulator = term();
        }
        else
        {
            accumulator = new Nil(nilId, null);
        }

        // A list is always terminated with a ']'.
        Token rightDelim = consumeToken(RSQPAREN);

        // Walk down all of the lists arguments joining them together with cons/2 functors.
        if (args != null) // 'args' will contain one or more elements if not null.
        {
            for (int i = args.length - 1; i >= 0; i--)
            {
                Term previousAccumulator = accumulator;

                //accumulator = new Functor(consId.ordinal(), new Term[] { args[i], previousAccumulator });
                accumulator = new Cons(consId, new Term[] { args[i], previousAccumulator });
            }
        }

        // Set the position that the list was parsed from, as being the region between the '[' and ']' brackets.
        SourceCodePosition position =
            new SourceCodePositionImpl(leftDelim.beginLine, leftDelim.beginColumn, rightDelim.endLine,
                rightDelim.endColumn);
        accumulator.setSourceCodePosition(position);

        // The cast must succeed because arglist must return at least one argument, therefore the cons generating
        // loop must have been run at least once. If arglist is not called at all because an empty list was
        // encountered, then the accumulator will contain the 'nil' constant which is a functor of arity zero.
        return (Functor) accumulator;
    }

Parses a list expressed as a sequence of functors in first order logic. The empty list consists of the atom 'nil'
and a non-empty list consists of the functor 'cons' with arguments the head of the list and the remainder of the
list.

<p/>A list can be empty '[]', contains a sequence of terms seperated by commas '[a,...]', contain a sequence of
terms seperated by commas consed onto another term '[a,...|T]'. In the case where a term is consed onto the end,
if the term is itself a list the whole will form a list with a cons nil terminator, otherwise the term will be
consed onto the end as the list terminal.

@return A list expressed as a sequence of functors in first order.

@throws SourceCodeException If the token sequence does not parse as a valid list.

Parses a list expressed as a sequence of functors in first order logic . The empty list consists of the atom nil and a non - empty list consists of the functor cons with arguments the head of the list and the remainder of the list .


public Term[] arglist() throws SourceCodeException
    {
        Term term = term();
        List<Term> result = TermUtils.flattenTerm(term, Term.class, ",", interner);

        return result.toArray(new Term[result.size()]);
    }

public Term [ ] arglist ( ) throws SourceCodeException { Term term = term ( ) ; List < Term > result = TermUtils . flattenTerm ( term , Term . class , "," , interner ) ; return result . toArray ( new Term [ result . size ( ) ] ) ; }

Parses a sequence of terms as a comma seperated argument list. The ',' operator in prolog can be used as an
operator, when it behaves as a functor of arity 2, or it can be used to separate a sequence of terms that are
arguments to a functor or list. The sequence of functors must first be parsed as a term, using the operator
precedence of "," to form the term. This method takes such a term and flattens it back into a list of terms,
breaking it only on a sequence of commas. Terms that have been parsed as a bracketed expression will not be
broken up.

<p/>For example, 'a, b, c' is broken into the list { a, b, c}. The example, 'a, (b, c), d' is broken into the
list { a, (b, c), d} and so on.

@return A sequence of terms parsed as a term, then flattened back into a list seperated on commas.

@throws SourceCodeException If the token sequence is not a valid term.

Parses a sequence of terms as a comma seperated argument list . The operator in prolog can be used as an operator when it behaves as a functor of arity 2 or it can be used to separate a sequence of terms that are arguments to a functor or list . The sequence of functors must first be parsed as a term using the operator precedence of to form the term . This method takes such a term and flattens it back into a list of terms breaking it only on a sequence of commas . Terms that have been parsed as a bracketed expression will not be broken up .


public Term variable() throws SourceCodeException
    {
        Token name = consumeToken(VAR);

        // Intern the variables name.
        int nameId = interner.internVariableName(name.image);

        // Check if the variable already exists in this scope, or create a new one if it does not.
        // If the variable is the unidentified anonymous variable '_', a fresh one will always be created.
        Variable var = null;

        if (!"_".equals(name.image))
        {
            var = variableContext.get(nameId);
        }

        if (var != null)
        {
            return var;
        }
        else
        {
            var = new Variable(nameId, null, name.image.equals("_"));
            variableContext.put(nameId, var);

            return var;
        }
    }

Parses a variable in first order logic. Variables are scoped within the current sentence being parsed, so if the
variable has been seen previously in the sentence it is returned rather than a new one being created.

@return A variable.

@throws SourceCodeException If the next token in the sequence is not a variable.

Parses a variable in first order logic . Variables are scoped within the current sentence being parsed so if the variable has been seen previously in the sentence it is returned rather than a new one being created .


public Term intLiteral() throws SourceCodeException
    {
        Token valToken = consumeToken(INTEGER_LITERAL);

        NumericType result = new IntLiteral(Integer.parseInt(valToken.image));

        // Set the position that the literal was parsed from.
        SourceCodePosition position =
            new SourceCodePositionImpl(valToken.beginLine, valToken.beginColumn, valToken.endLine, valToken.endColumn);
        result.setSourceCodePosition(position);

        return result;
    }

Parses an integer literal.

@return An integer literal.

@throws SourceCodeException If the next token in the sequence is not an integer literal.


public Term doubleLiteral() throws SourceCodeException
    {
        Token valToken = consumeToken(FLOATING_POINT_LITERAL);

        NumericType result = new DoubleLiteral(Double.parseDouble(valToken.image));

        // Set the position that the literal was parsed from.
        SourceCodePosition position =
            new SourceCodePositionImpl(valToken.beginLine, valToken.beginColumn, valToken.endLine, valToken.endColumn);
        result.setSourceCodePosition(position);

        return result;
    }

Parses a real number literal.

@return A real number literal.

@throws SourceCodeException If the next token in the sequence is not a real number literal.


public Term stringLiteral() throws SourceCodeException
    {
        Token valToken = consumeToken(STRING_LITERAL);

        String valWithQuotes = valToken.image;

        StringLiteral result = new StringLiteral(valWithQuotes.substring(1, valWithQuotes.length() - 1));

        // Set the position that the literal was parsed from.
        SourceCodePosition position =
            new SourceCodePositionImpl(valToken.beginLine, valToken.beginColumn, valToken.endLine, valToken.endColumn);
        result.setSourceCodePosition(position);

        return result;
    }

Parses a string literal.

@return A string literal.

@throws SourceCodeException If the next token in the sequence is not a string literal.


public Directive peekAndConsumeDirective() throws SourceCodeException
    {
        if (peekAndConsumeTrace())
        {
            return Directive.Trace;
        }

        if (peekAndConsumeInfo())
        {
            return Directive.Info;
        }

        if (peekAndConsumeUser())
        {
            return Directive.User;
        }

        return null;
    }

public Directive peekAndConsumeDirective ( ) throws SourceCodeException { if ( peekAndConsumeTrace ( ) ) { return Directive . Trace ; } if ( peekAndConsumeInfo ( ) ) { return Directive . Info ; } if ( peekAndConsumeUser ( ) ) { return Directive . User ; } return null ; }

Peeks and consumes the next interactive system directive.

@return The directive, or <tt>null</tt> if none is found.

@throws SourceCodeException If the source being parsed does not match the grammar.

Peeks and consumes the next interactive system directive .


public void internOperator(String operatorName, int priority, OpSymbol.Associativity associativity)
    {
        int arity;

        if ((associativity == XFY) | (associativity == YFX) | (associativity == XFX))
        {
            arity = 2;
        }
        else
        {
            arity = 1;
        }

        int name = interner.internFunctorName(operatorName, arity);
        operatorTable.setOperator(name, operatorName, priority, associativity);
    }

public void internOperator ( String operatorName , int priority , OpSymbol . Associativity associativity ) { int arity ; if ( ( associativity == XFY ) | ( associativity == YFX ) | ( associativity == XFX ) ) { arity = 2 ; } else { arity = 1 ; } int name = interner . internFunctorName ( operatorName , arity ) ; operatorTable . setOperator ( name , operatorName , priority , associativity ) ; }

Interns an operators name as a functor of appropriate arity for the operators fixity, and sets the operator in
the operator table.

@param operatorName  The name of the operator to create.
@param priority      The priority of the operator, zero unsets it.
@param associativity The operators associativity.

Interns an operators name as a functor of appropriate arity for the operators fixity and sets the operator in the operator table .


protected void initializeBuiltIns()
    {
        // Initializes the operator table with the standard ISO prolog built-in operators.
        internOperator(":-", 1200, XFX);
        internOperator(":-", 1200, FX);
        internOperator("-->", 1200, XFX);
        internOperator("?-", 1200, FX);

        internOperator(";", 1100, XFY);
        internOperator("->", 1050, XFY);
        internOperator(",", 1000, XFY);
        internOperator("\\+", 900, FY);

        internOperator("=", 700, XFX);
        internOperator("\\=", 700, XFX);
        internOperator("==", 700, XFX);
        internOperator("\\==", 700, XFX);
        internOperator("@<", 700, XFX);
        internOperator("@=<", 700, XFX);
        internOperator("@>", 700, XFX);
        internOperator("@>=", 700, XFX);
        internOperator("=..", 700, XFX);
        internOperator("is", 700, XFX);
        internOperator("=:=", 700, XFX);
        internOperator("=\\=", 700, XFX);
        internOperator("<", 700, XFX);
        internOperator("=<", 700, XFX);
        internOperator(">", 700, XFX);
        internOperator(">=", 700, XFX);

        internOperator("+", 500, YFX);
        internOperator("-", 500, YFX);

        internOperator("\\/", 500, YFX);
        internOperator("/\\", 500, YFX);

        internOperator("/", 400, YFX);
        internOperator("//", 400, YFX);
        internOperator("*", 400, YFX);
        internOperator(">>", 400, YFX);
        internOperator("<<", 400, YFX);
        internOperator("rem", 400, YFX);
        internOperator("mod", 400, YFX);

        internOperator("-", 200, FY);
        internOperator("^", 200, YFX);
        internOperator("**", 200, YFX);
        internOperator("\\", 200, FY);

        // Intern all built in functors.
        interner.internFunctorName("nil", 0);
        interner.internFunctorName("cons", 2);
        interner.internFunctorName("true", 0);
        interner.internFunctorName("fail", 0);
        interner.internFunctorName("!", 0);
    }

Interns and inserts into the operator table all of the built in operators and functors in Prolog.

Interns and inserts into the operator table all of the built in operators and functors in Prolog .


protected Token consumeToken(int kind) throws SourceCodeException
    {
        Token nextToken = tokenSource.peek();

        if (nextToken.kind != kind)
        {
            throw new SourceCodeException("Was expecting " + tokenImage[kind] + " but got " +
                tokenImage[nextToken.kind] + ".", null, null, null,
                new SourceCodePositionImpl(nextToken.beginLine, nextToken.beginColumn, nextToken.endLine,
                    nextToken.endColumn));
        }
        else
        {
            nextToken = tokenSource.poll();

            return nextToken;
        }
    }

protected
Token
consumeToken
(
int
kind
)
throws
SourceCodeException
{
Token
nextToken
=
tokenSource
.
peek
(
)
;
if
(
nextToken
.
kind
!=
kind
)
{
throw
new
SourceCodeException
(
"Was expecting "
+
tokenImage
[
kind
]
+
" but got "
+
tokenImage
[
nextToken
.
kind
]
+
"."
,
,
,
,
new
SourceCodePositionImpl
(
nextToken
.
beginLine
,
nextToken
.
beginColumn
,
nextToken
.
endLine
,
nextToken
.
endColumn
)
)
;
}
else
{
nextToken
=
tokenSource
.
poll
(
)
;
return
nextToken
;
}
}

Consumes a token of the expected kind from the token sequence. If the next token in the sequence is not of the
expected kind an error will be raised.

@param  kind The kind of token to consume.

@return The consumed token of the expected kind.

@throws SourceCodeException If the next token in the sequence is not of the expected kind.

Consumes a token of the expected kind from the token sequence . If the next token in the sequence is not of the expected kind an error will be raised .


private boolean peekAndConsume(int kind)
    {
        Token nextToken = tokenSource.peek();

        if (nextToken.kind == kind)
        {
            try
            {
                consumeToken(kind);
            }
            catch (SourceCodeException e)
            {
                // If the peek ahead kind can not be consumed then something strange has gone wrong so report this
                // as a bug rather than try to recover from it.
                throw new IllegalStateException(e);
            }

            return true;
        }
        else
        {
            return false;
        }
    }

Peeks ahead for the given token type, and if one is foudn with that type, it is consumed.

@param  kind The token kind to look for.

@return <tt>true</tt> iff the token was found and consumed.

Peeks ahead for the given token type and if one is foudn with that type it is consumed .


public void bind()
    {
        // If necessary create a fresh transaction id.
        if ((txId == null) || !txId.isValid())
        {
            txId = TxManager.createTxId();
        }

        // Bind the transaction to the current thread.
        TxManager.assignTxIdToThread(txId);

        // Bind this session to the current thread.
        threadSession.set(this);
    }

Binds the session as a transactional context to the current thread, if it is not already bound.

Binds the session as a transactional context to the current thread if it is not already bound .


public void rollback()
    {
        // Rollback all soft resources.
        for (Transactional enlist : enlists)
        {
            enlist.rollback();
        }

        // Clear all of the rolled back resources.
        enlists.clear();

        // Invalidate the transaction id, so that a fresh transaction is begun.
        txId = TxManager.removeTxIdFromThread();
        TxManager.invalidateTxId(txId);
        bind();
    }


public static <T> Collection<T> collectIterator(Iterator<T> iterator, Collection<T> targetCollection)
    {
        while (iterator.hasNext())
        {
            targetCollection.add(iterator.next());
        }

        return targetCollection;
    }

public static < T > Collection < T > collectIterator ( Iterator < T > iterator , Collection < T > targetCollection ) { while ( iterator . hasNext ( ) ) { targetCollection . add ( iterator . next ( ) ) ; } return targetCollection ; }

Extracts all elements from an iterator, usually created from a filterator, and adds them into the target
collection, returning that collection as the result.

@param  <T>              The type of the iterator and collection to add to.
@param  iterator         The iterator to extract from.
@param  targetCollection The collection to add to.

@return The collection added to.

Extracts all elements from an iterator usually created from a filterator and adds them into the target collection returning that collection as the result .


public CallPoint reserveCallPoint(int name, int length)
    {
        // Work out where the code will go and advance the insertion point beyond its end, so that additional code
        // will be added beyond the reserved space.
        int address = getCodeInsertionPoint();
        advanceCodeInsertionPoint(length);

        // Create a call point for the reserved space.
        CallPoint callPoint = new CallPoint(address, length, name);

        // Add the call point to the symbol table under the interned name.
        symbolTable.put(name, getCallPointSymbolField(), callPoint);

        return callPoint;
    }

Reserves a call point for a block of named callable code. The size of the block of code must be known fully in
advance. If the named block already has a call point, this will replace it with a new one.

<p/>Adding code into a code machine may be a two-stage process, first reserve call-points for all blocks of code,
then add the blocks of code into the machine, resolving internal call points within the code onto previously
reserved call points as this is done. A two-stage process is required to support recursive or mutually recursive
callable procedures.

@param  name   The interned name of the procedure to create a call point for.
@param  length The length of the procedures code.

@return A new call point for the procedure.

Reserves a call point for a block of named callable code . The size of the block of code must be known fully in advance . If the named block already has a call point this will replace it with a new one .