public static int get24BitIntFromBytes(byte[] buf, int offset)
    {
        int i = 0;

        offset++;
        i += buf[offset++] & 0xFF;
        i += ((buf[offset++] & 0xFF) << 8);
        i += ((buf[offset] & 0xFF) << 16);

        return i;
    }

public static int get24BitIntFromBytes ( byte [ ] buf , int offset ) { int i = 0 ; offset ++ ; i += buf [ offset ++ ] & 0xFF ; i += ( ( buf [ offset ++ ] & 0xFF ) << 8 ) ; i += ( ( buf [ offset ] & 0xFF ) << 16 ) ; return i ; }

Extracts an int from an array of bytes. Only three bytes are pulled together from the array to make a 24 bit
integer, albeit returned as a java 32 bit int.

@param  buf    The array of bytes to extract the int from.
@param  offset The offset of the start of the int in the byte array.

@return An integer extracted from the 4 bytes of data.

Extracts an int from an array of bytes . Only three bytes are pulled together from the array to make a 24 bit integer albeit returned as a java 32 bit int .


public static short getShortFromBytes(byte[] buf, int offset)
    {
        short result = 0;

        result += buf[offset++] & 0xFF;
        result += ((buf[offset]) << 8);

        return result;
    }

public static short getShortFromBytes ( byte [ ] buf , int offset ) { short result = 0 ; result += buf [ offset ++ ] & 0xFF ; result += ( ( buf [ offset ] ) << 8 ) ; return result ; }

Extracts a short from an array of bytes.

@param  buf    The array of bytes to extract the short from.
@param  offset The offset of the start of the short in the byte array.

@return A short extracted from the 2 bytes of data.

Extracts a short from an array of bytes .


public static void writeShortToByteArray(byte[] buf, int offset, short value)
    {
        buf[offset++] = (byte) (value & 0x000000ff);
        buf[offset] = (byte) ((value & 0x0000ff00) >> 8);
    }

public static void writeShortToByteArray ( byte [ ] buf , int offset , short value ) { buf [ offset ++ ] = ( byte ) ( value & 0x000000ff ) ; buf [ offset ] = ( byte ) ( ( value & 0x0000ff00 ) >> 8 ) ; }

Outputs a short into a byte array.

@param buf    The byte array to write to.
@param offset The offset within the byte array to output the short.
@param value  The short value to write into the array.


public TreeSearchState<E> getChildStateForOperator(Operator<Tree<E>> op)
    {
        /*log.fine("public Traversable getChildStateForOperator(Operator op): called");*/

        // Extract the child tree from the operator and create a new tree search state from it.
        return new TreeSearchState<E>(op.getOp());
    }

Returns the state obtained by applying the specified operation. If the operation is not valid then this should
return null.

@param  op The operator to apply to the traversable state.

@return The new traversable state generated by applying the specified operator.

Returns the state obtained by applying the specified operation . If the operation is not valid then this should return null .


public Iterator<Operator<Tree<E>>> validOperators(boolean reverse)
    {
        /*log.fine("public Iterator<Operator> validOperators(): called");*/

        // Check if the tree is a leaf and return an empty iterator if so.
        if (tree.isLeaf())
        {
            /*log.fine("is leaf");*/

            return new ArrayList<Operator<Tree<E>>>().iterator();
        }

        // Generate an iterator over the child trees of the current node, encapsulating them as operators.
        else
        {
            /*log.fine("is node");*/

            Tree.Node<E> node = tree.getAsNode();

            return new TreeSearchOperatorIterator<E>(node.getChildIterator());
        }
    }

Gets all operators valid from this state. If the current tree to search has any children these are encoded as
operators to access those child trees as tree search states. If the current tree is a leaf then an empty iterator
is returned.

@param  reverse <tt>true</tt> if the operators are to be presented in reverse order.

@return An iterator over all the operators that may be applied to this state.

Gets all operators valid from this state . If the current tree to search has any children these are encoded as operators to access those child trees as tree search states . If the current tree is a leaf then an empty iterator is returned .


public long getId()
    {
        // Check if the attribute class has been finalized yet.
        if (attributeClass.finalized)
        {
            // Fetch the object value from the attribute class array of finalized values.
            return attributeClass.lookupValue[value].id;
        }

        // The attribute class has not been finalized yet.
        else
        {
            // Fetch the object value from the attribute class list of unfinalized values.
            return attributeClass.lookupValueList.get(value).id;
        }
    }

Returns the integer id of the attribute.

@return The integer id of the attribute.

Returns the integer id of the attribute .


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

Gets the object value of a object attribute.

@return The underlying object value of this attribute.

Gets the object value of a object attribute .


public void setValue(T value) throws IllegalArgumentException
    {
        Integer b = attributeClass.lookupInt.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 IdType, " + 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.
                IdAttribute newAttribute = attributeClass.createIdAttribute(value);
                b = newAttribute.value;
            }
        }

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

Sets the specified object 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 object 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 .


public static String[] listToArray(String value, String delim)
    {
        List<String> result = new ArrayList<String>();
        StringTokenizer tokenizer = new StringTokenizer(value, delim);

        while (tokenizer.hasMoreTokens())
        {
            result.add(tokenizer.nextToken());
        }

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

public static String [ ] listToArray ( String value , String delim ) { List < String > result = new ArrayList < String > ( ) ; StringTokenizer tokenizer = new StringTokenizer ( value , delim ) ; while ( tokenizer . hasMoreTokens ( ) ) { result . add ( tokenizer . nextToken ( ) ) ; } return result . toArray ( new String [ result . size ( ) ] ) ; }

Converts a string listing sub-strings seperated by a delimeter into an array of strings.

<p/>For example, suppose the string, "one,two,three" is presented with the delimter ",", then this will be
converted into the string array { "one", "two", "three" }.

@param  value The string to convert.
@param  delim The delimeter.

@return The string converted into an array of strings.

Converts a string listing sub - strings seperated by a delimeter into an array of strings .


public static String arrayToList(String[] array, String delim)
    {
        String result = "";

        for (int i = 0; i < array.length; i++)
        {
            result += array[i] + ((i == (array.length - 1)) ? "" : delim);
        }

        return result;
    }

public static String arrayToList ( String [ ] array , String delim ) { String result = "" ; for ( int i = 0 ; i < array . length ; i ++ ) { result += array [ i ] + ( ( i == ( array . length - 1 ) ) ? "" : delim ) ; } return result ; }

Converts an array of strings into a delimeter seperated string.

@param  array The array to convert.
@param  delim The delimeter to use.

@return The array of strings converted into a delimeter seperated string.

Converts an array of strings into a delimeter seperated string .


public static String toCamelCase(String name)
    {
        String[] parts = name.split("_");
        String result = parts[0];

        for (int i = 1; i < parts.length; i++)
        {
            if (parts[i].length() > 0)
            {
                result += upperFirstChar(parts[i]);
            }
        }

        return result;
    }

public static String toCamelCase ( String name ) { String [ ] parts = name . split ( "_" ) ; String result = parts [ 0 ] ; for ( int i = 1 ; i < parts . length ; i ++ ) { if ( parts [ i ] . length ( ) > 0 ) { result += upperFirstChar ( parts [ i ] ) ; } } return result ; }

Converts a string to camel case.

@param  name The string to convert to camel case.

@return The string in camel case.


public static String convertCase(String value, String separator, boolean firstLetterUpper, boolean firstLetterOfWordUpper) {
        final StringBuffer result = new StringBuffer();

        boolean firstWord = true;
        boolean firstLetter = true;
        boolean upper = false;

        WordMachineState state = WordMachineState.Initial;

        Function2<Character, Boolean, StringBuffer> writeChar = new Function2<Character, Boolean, StringBuffer>() {
            public StringBuffer apply(Character nextChar, Boolean upper) {
                if (upper)
                    result.append(Character.toUpperCase(nextChar));
                else
                    result.append(Character.toLowerCase(nextChar));

                return result;
            }
        };

        for (int i = 0; i < value.length(); i++) {
            char nextChar = value.charAt(i);

            if (Character.isUpperCase(nextChar)) {
                switch (state) {
                    case Initial:
                        state = WordMachineState.StartWord;
                        upper = firstLetterOfWordUpper;
                        if (!firstWord) {
                            result.append(separator);
                        }
                        firstWord = false;
                        break;
                    case StartWord:
                    case ContinueWordCaps:
                        state = WordMachineState.ContinueWordCaps;
                        upper = false;
                        break;
                    case ContinueWordLower:
                        state = WordMachineState.StartWord;
                        upper = firstLetterOfWordUpper;
                        result.append(separator);
                        break;
                }

                writeChar.apply(nextChar, (!firstLetter && upper) || (firstLetter & firstLetterUpper));
                firstLetter = false;
            } else if (Character.isLetterOrDigit(nextChar)) {
                switch (state) {
                    case Initial:
                        state = WordMachineState.StartWord;
                        upper = firstLetterOfWordUpper;
                        if (!firstWord) {
                            result.append(separator);
                        }
                        firstWord = false;
                        break;
                    case StartWord:
                    case ContinueWordLower:
                    case ContinueWordCaps:
                        state = WordMachineState.ContinueWordLower;
                        upper = false;
                        break;
                }

                writeChar.apply(nextChar, (!firstLetter && upper) || (firstLetter & firstLetterUpper));
                firstLetter = false;
            } else {
                switch (state) {
                    case Initial:
                        state = WordMachineState.Initial;
                        break;
                    case StartWord:
                    case ContinueWordCaps:
                    case ContinueWordLower:
                        state = WordMachineState.Initial;
                        break;
                }

                upper = false;
            }
        }

        return result.toString();
    }

public static String convertCase ( String value , String separator , boolean firstLetterUpper , boolean firstLetterOfWordUpper ) { final StringBuffer result = new StringBuffer ( ) ; boolean firstWord = true ; boolean firstLetter = true ; boolean upper = false ; WordMachineState state = WordMachineState . Initial ; Function2 < Character , Boolean , StringBuffer > writeChar = new Function2 < Character , Boolean , StringBuffer > ( ) { public StringBuffer apply ( Character nextChar , Boolean upper ) { if ( upper ) result . append ( Character . toUpperCase ( nextChar ) ) ; else result . append ( Character . toLowerCase ( nextChar ) ) ; return result ; } } ; for ( int i = 0 ; i < value . length ( ) ; i ++ ) { char nextChar = value . charAt ( i ) ; if ( Character . isUpperCase ( nextChar ) ) { switch ( state ) { case Initial : state = WordMachineState . StartWord ; upper = firstLetterOfWordUpper ; if ( ! firstWord ) { result . append ( separator ) ; } firstWord = false ; break ; case StartWord : case ContinueWordCaps : state = WordMachineState . ContinueWordCaps ; upper = false ; break ; case ContinueWordLower : state = WordMachineState . StartWord ; upper = firstLetterOfWordUpper ; result . append ( separator ) ; break ; } writeChar . apply ( nextChar , ( ! firstLetter && upper ) || ( firstLetter & firstLetterUpper ) ) ; firstLetter = false ; } else if ( Character . isLetterOrDigit ( nextChar ) ) { switch ( state ) { case Initial : state = WordMachineState . StartWord ; upper = firstLetterOfWordUpper ; if ( ! firstWord ) { result . append ( separator ) ; } firstWord = false ; break ; case StartWord : case ContinueWordLower : case ContinueWordCaps : state = WordMachineState . ContinueWordLower ; upper = false ; break ; } writeChar . apply ( nextChar , ( ! firstLetter && upper ) || ( firstLetter & firstLetterUpper ) ) ; firstLetter = false ; } else { switch ( state ) { case Initial : state = WordMachineState . Initial ; break ; case StartWord : case ContinueWordCaps : case ContinueWordLower : state = WordMachineState . Initial ; break ; } upper = false ; } } return result . toString ( ) ; }

Converts string between various case forms such as camel case, snake case or kebab case.

Characters in the string are characterized as whitespace, upper case, or other by the following rules.

 An upper case letter is marked as upper case (U).

 A lower case letter or digit is marked as lower case (L).

 Any other character is marked as whitespace (W).

The string is processed into words by these rules.

 W at the start is discarded.

 U or L begins a word.

 U after the initial character of a word continues the same word, so long as no W or L is encountered.

 L after U or L continues the word, so long as no W is encountered.

 U after L begins a new word.

 W after U or L is discarded and ends the current word.

@param value                  The string to convert.
@param separator              The separator to place between words.
@param firstLetterUpper       <tt>true</tt> iff the first letter should be in capitals.
@param firstLetterOfWordUpper <tt>true</tt> iff the first letter of subsequent words should be in capitals.

@return The input converted to lower case words separated by spaces, as per the rules described above.

Converts string between various case forms such as camel case snake case or kebab case .


public static String currentConfiguration()
    {
        StringBuffer rtn = new StringBuffer(1024);

        String loggingConfigClass = System.getProperty("java.util.logging.config.class");
        String loggingConfigFile = System.getProperty("java.util.logging.config.file");
        boolean configClassOK = false;

        if (loggingConfigClass == null)
        {
            rtn.append("No java.util.logging.config.class class is set.\n");
        }
        else
        {
            rtn.append("java.util.logging.config.class is set to '").append(loggingConfigClass).append("'\n");

            try
            {
                Class c = Class.forName(loggingConfigClass);
                c.newInstance();
                rtn.append("This class was loaded and a new instance was sucessfully created.\n");
                configClassOK = true;
            }
            catch (ClassNotFoundException e)
            {
                e = null;
                rtn.append(loggingConfigClass).append(" could not be found.");
            }
            catch (InstantiationException e)
            {
                e = null;
                rtn.append(loggingConfigClass).append(" could not be instantiated.");
            }
            catch (IllegalAccessException e)
            {
                e = null;
                rtn.append(loggingConfigClass).append(" could not be accessed.");
            }
        }

        if (loggingConfigFile == null)
        {
            rtn.append("No java.util.logging.config.file file is set.\n");
        }
        else
        {
            rtn.append("java.util.logging.config.file is set to '").append(loggingConfigFile).append("'\n");

            File loggingFile = new File(loggingConfigFile);
            rtn.append(loggingFile.getAbsolutePath()).append("\n");

            if (!loggingFile.exists() || !loggingFile.isFile())
            {
                rtn.append("This file does NOT EXIST.\n");
            }

            if (loggingConfigClass != null)
            {
                if (configClassOK)
                {
                    rtn.append("This file is ignored because java.util.logging.config.class is set.\n");
                }
            }
        }

        Handler[] handlers = Logger.getLogger("").getHandlers();
        listHandlers(handlers, rtn);

        return rtn.toString();
    }

Provides a string containing information about the configured logging set up.

@return A string containing information about the configured logging set up.

Provides a string containing information about the configured logging set up .


private static StringBuffer listHandlers(Handler[] handlers, StringBuffer buffer)
    {
        for (Handler handler : handlers)
        {
            Class<? extends Handler> handlerClass = handler.getClass();
            Formatter formatter = handler.getFormatter();

            buffer.append("Handler:").append(handlerClass.getName()).append("\n");
            buffer.append("Level:").append(handler.getLevel().toString()).append("\n");

            if (formatter != null)
            {
                buffer.append("Formatter:").append(formatter.getClass().getName()).append("\n");
            }
        }

        return buffer;
    }

private static StringBuffer listHandlers ( Handler [ ] handlers , StringBuffer buffer ) { for ( Handler handler : handlers ) { Class < ? extends Handler > handlerClass = handler . getClass ( ) ; Formatter formatter = handler . getFormatter ( ) ; buffer . append ( "Handler:" ) . append ( handlerClass . getName ( ) ) . append ( "\n" ) ; buffer . append ( "Level:" ) . append ( handler . getLevel ( ) . toString ( ) ) . append ( "\n" ) ; if ( formatter != null ) { buffer . append ( "Formatter:" ) . append ( formatter . getClass ( ) . getName ( ) ) . append ( "\n" ) ; } } return buffer ; }

Lists information about logging handlers.

@param  handlers The handlers.
@param  buffer   A string buffer to build up the listing in.

@return The string buffer to build up the listing in.

Lists information about logging handlers .


public WAMCallPoint resolveCallPoint(int functorName)
    {
        /*log.fine("public WAMCallPoint resolveCallPoint(int functorName): called");*/

        WAMCallPoint result = (WAMCallPoint) symbolTable.get(functorName, SYMKEY_CALLPOINTS);

        if (result == null)
        {
            result = new WAMCallPoint(-1, 0, functorName);
        }

        return result;
    }

Looks up the offset of the start of the code for the named functor.

@param  functorName The interned name of the functor to find the start address of the code for.

@return The call table entry of the functors code within the code area of the machine, or an invalid address if
the functor is not known to the machine.

Looks up the offset of the start of the code for the named functor .


protected WAMCallPoint setCodeAddress(int functorName, int offset, int length)
    {
        WAMCallPoint entry = new WAMCallPoint(offset, length, functorName);
        symbolTable.put(functorName, SYMKEY_CALLPOINTS, entry);

        // Keep a reverse lookup from address to functor name.
        reverseTable.put(offset, functorName);

        return entry;
    }

Records the offset of the start of the code for the named functor.

@param  functorName The interned name of the functor to find the start address of the code for.
@param  offset      The offset of the start of the functors code within the code area.
@param  length      The size of the code to set the address for.

@return The call table entry for the functors code within the code area of the machine.

Records the offset of the start of the code for the named functor .


public boolean isSubCategory(HierarchyAttribute comp)
    {
        // Check that the comparator is of the same type class as this one.
        if (!comp.attributeClass.attributeClassName.equals(attributeClass.attributeClassName))
        {
            return false;
        }

        // Extract the path labels from this and the comparator.
        List<String> otherPath = comp.getPathValue();
        List<String> path = getPathValue();

        // Check that the path length of the comparator is the same as this plus one or longer.
        if (otherPath.size() <= path.size())
        {
            return false;
        }

        // Start by assuming that the paths prefixes are the same, then walk down both paths checking they are
        // the same.
        boolean subcat = true;

        for (int i = 0; i < path.size(); i++)
        {
            // Check that the labels really are equal.
            if (!otherPath.get(i).equals(path.get(i)))
            {
                subcat = false;

                break;
            }
        }

        return subcat;
    }

Tests if another hierarchy attribute is strict a sub-category of this one. It is a sub-category if it has the
same sequence of path labels as this one as a prefix of its whole path label.

@param  comp The hierarchy attribute to compare to.

@return True if the comparator is of the same type and is a sub-category of this one.

Tests if another hierarchy attribute is strict a sub - category of this one . It is a sub - category if it has the same sequence of path labels as this one as a prefix of its whole path label .


public long getId()
    {
        // Find the category for this hierarchy attribute value.
        Tree<CategoryNode> category = attributeClass.lookup.get(value);

        // Extract and return the id.
        return category.getElement().id;
    }

Returns the long id of the attribute.

@return The long id of the attribute.


public String getValueAtLevel(String level)
    {
        /*log.fine("public String getValueAtLevel(String level): called");*/
        /*log.fine("level = " + level);*/

        int index = attributeClass.levels.indexOf(level);

        /*log.fine("index = " + index);*/

        if (index == -1)
        {
            throw new IllegalArgumentException("Level name " + level +
                " is not known to this hierarchy attribute type.");
        }

        return getValueAtLevel(index);
    }

Gets the label value at the named level of the hierarchy.

@param  level The level to get the label at.

@return The label value at the specified level of the hierarchy.

Gets the label value at the named level of the hierarchy .


public String getLastValue()
    {
        List<String> pathValue = getPathValue();

        return pathValue.get(pathValue.size() - 1);
    }

public String getLastValue ( ) { List < String > pathValue = getPathValue ( ) ; return pathValue . get ( pathValue . size ( ) - 1 ) ; }

Gets the label value at the last level of the hierarchy.

@return The label value at the last level of the hierarchy.

Gets the label value at the last level of the hierarchy .


private void writeObject(ObjectOutputStream out) throws IOException
    {
        // Print out some information about the serialized object.
        /*log.fine("Serialized hierarchy attribute = " + this);*/
        /*log.fine("Serialized hierarchy attribute class = " + attributeClass);*/

        /*log.fine("Serialized attribute classes in static class map are: ");*/

        for (HierarchyClassImpl attributeClass : attributeClasses.values())
        {
            /*log.fine(attributeClass.toString());*/
        }

        // Perform default serialization.
        // out.defaultWriteObject();

        // Serialized the attribute by value, that is, its full path and the name of its attribute class.
        List<String> pathValue = getPathValue();
        String[] pathArrayValue = pathValue.toArray(new String[pathValue.size()]);

        out.writeObject(pathArrayValue);
        out.writeObject(attributeClass.getName());
    }

Serialized a hierarchy attribute.

@param  out The object output stream.

@throws IOException If an IO exception occurs.


private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException
    {
        // Perform default de-serialization.
        // in.defaultReadObject();

        // Deserialize the attribute by value, from its attribute class and full path.
        String[] pathArrayValue = (String[]) in.readObject();
        String attributeClassName = (String) in.readObject();

        // Re-create the attribute from its value representation.
        HierarchyAttribute attr = getFactoryForClass(attributeClassName).createHierarchyAttribute(pathArrayValue);

        // Copy the fields from the freshly constructed attribute into this one.
        value = attr.value;
        attributeClass = attr.attributeClass;

        // Print out some information about the deserialized object.
        /*log.fine("Deserialized hierarchy attribute = " + this);*/
        /*log.fine("Deserialized hierarchy attribute class = " + attributeClass);*/

        /*log.fine("Deserialized attribute classes in static class map are: ");*/

        for (HierarchyClassImpl attributeClass : attributeClasses.values())
        {
            /*log.fine(attributeClass.toString());*/
        }
    }

Deserializes a hierarchy attribute.

@param  in The object input stream.

@throws IOException            If any IO exception occurs.
@throws ClassNotFoundException If any classes to deserialize cannot be found.


public float computeH(EightPuzzleState state, HeuristicSearchNode searchNode)
    {
        // Get the parent heuristic search node.
        HeuristicSearchNode parentNode = (HeuristicSearchNode) searchNode.getParent();

        // Check if there is no parent, in which case this is the start state so the complete heuristic needs
        // to be calculated.
        if (parentNode == null)
        {
            // Used to hold the running total.
            int h = 0;

            // Loop over the whole board.
            for (int j = 0; j < 3; j++)
            {
                for (int i = 0; i < 3; i++)
                {
                    char nextTile = state.getTileAt(i, j);

                    // Look up the board position of the tile in the solution.
                    int goalX = state.getGoalXForTile(nextTile);
                    int goalY = state.getGoalYForTile(nextTile);

                    // Compute the manhattan distance and add it to the total.
                    int diffX = goalX - i;

                    diffX = (diffX < 0) ? -diffX : diffX;

                    int diffY = goalY - j;

                    diffY = (diffY < 0) ? -diffY : diffY;

                    h += diffX + diffY;
                }
            }

            // Convert the result to a float and return it
            return (float) h;
        }

        // There is a parent node so calculate the heuristic incrementally from it.
        else
        {
            // Get the parent board state.
            EightPuzzleState parentState = (EightPuzzleState) parentNode.getState();

            // Get the parent heurstic value.
            float h = parentNode.getH();

            // Get the move that was played.
            char playedMove = ((String) searchNode.getAppliedOp().getOp()).charAt(0);

            // Get the position of the empty tile on the parent board.
            int emptyX = parentState.getEmptyX();
            int emptyY = parentState.getEmptyY();

            // Work out which tile has been moved, this is the tile that now sits where the empty tile was.
            char movedTile = state.getTileAt(emptyX, emptyY);

            // The tile has either moved one step closer to its goal location or one step further away, decide which it
            // is. Calculate the X or Y position that the tile moved from.
            int oldX = 0;
            int oldY = 0;

            switch (playedMove)
            {
            case 'L':
            {
                oldX = emptyX - 1;
                break;
            }

            case 'R':
            {
                oldX = emptyX + 1;
                break;
            }

            case 'U':
            {
                oldY = emptyY - 1;
                break;
            }

            case 'D':
            {
                oldY = emptyY + 1;
                break;
            }

            default:
            {
                throw new IllegalStateException("Unkown operator: " + playedMove + ".");
            }
            }

            // Calculate the change in heuristic.
            int change = 0;

            switch (playedMove)
            {
            // Catch the case where a horizontal move was made.
            case 'L':
            case 'R':
            {
                // Get the X position of the tile in the goal state and current state
                int goalX = state.getGoalXForTile(movedTile);
                int newX = emptyX;

                // Calculate the change in the heuristic
                int oldDiffX = oldX - goalX;

                oldDiffX = (oldDiffX < 0) ? -oldDiffX : oldDiffX;

                int newDiffX = newX - goalX;

                newDiffX = (newDiffX < 0) ? -newDiffX : newDiffX;

                change = newDiffX - oldDiffX;
                break;
            }

            // Catch the case where a vertical move was made.
            case 'U':
            case 'D':
            {
                // Get the Y position of the tile in the goal state and current state
                int goalY = state.getGoalYForTile(movedTile);
                int newY = emptyY;

                // Calculate the change in the heuristic
                int oldDiffY = oldY - goalY;

                oldDiffY = (oldDiffY < 0) ? -oldDiffY : oldDiffY;

                int newDiffY = newY - goalY;

                newDiffY = (newDiffY < 0) ? -newDiffY : newDiffY;

                change = newDiffY - oldDiffY;

                break;
            }

            default:
            {
                throw new IllegalStateException("Unkown operator: " + playedMove + ".");
            }
            }

            // Return the parent heuristic plus or minus one.
            return (change > 0) ? (h + 1.0f) : (h - 1.0f);
        }
    }

Returns heuristic evaluation of an eight puzzle board position as the manhattan distance of all tiles from their
correct positions.

@param  state      The EightPuzzleState to calculate the heuristic for.
@param  searchNode The heuristic search node for the state in some heuristic search.

@return The heuristic estimation of the cost to the goal from this board position.

Returns heuristic evaluation of an eight puzzle board position as the manhattan distance of all tiles from their correct positions .


private int mod(long c, int bucketSize)
    {
        return (int) ((c < 0) ? ((bucketSize + (c % bucketSize)) % bucketSize) : (c % bucketSize));
    }

private int mod ( long c , int bucketSize ) { return ( int ) ( ( c < 0 ) ? ( ( bucketSize + ( c % bucketSize ) ) % bucketSize ) : ( c % bucketSize ) ) ; }

Calculates the modulo of a coordinate with the bucket size. Correctly calculates this module for negative
coordinates such the the first negative bucket is -1 with element 0 corresponding to -100 running to 99
corresponding to -1.

@param  c          The coordinate value.
@param  bucketSize The bucket size.

@return The coordinate offset into the bucket modulo the bucket size.

Calculates the modulo of a coordinate with the bucket size . Correctly calculates this module for negative coordinates such the the first negative bucket is - 1 with element 0 corresponding to - 100 running to 99 corresponding to - 1 .


public void addErrorMessage(String key, String userMessage)
    {
        /*log.fine("addErrorMessage(String key, String userMessage): called");*/
        /*log.fine("userMessage = " + userMessage);*/

        errors.add(new UserReadableErrorImpl(key, userMessage));
    }

Adds another user readable error message to this exception.

@param key         A key to look up user readable messages with.
@param userMessage The user readable message or data string.

Adds another user readable error message to this exception .


public static void handleErrors(Throwable exception, ActionErrors errors)
    {
        // Log the error.
        log.log(Level.SEVERE, exception.getMessage(), exception);

        if (exception.getCause() == null)
        {
            log.fine("Exception.getCause() is null");
        }

        // Unwrap the exception if it is a WrappedStrutsServletException, which is a place holder for returning
        // other throwables from struts actions.
        // See BaseAction and WrappedStrutsServletException for more information.
        if ((exception instanceof WrappedStrutsServletException) && (exception.getCause() != null))
        {
            exception = exception.getCause();
            log.fine("Unwrapped WrappedStrutsServletException");
        }

        // Create an error called 'exception' in the Struts errors for debugging purposes
        // Debugging code can print this piece of html containing the exception stack trace at the bottom
        // of the page for convenience.
        Writer stackTrace = new StringWriter();

        exception.printStackTrace(new PrintWriter(new HTMLFilter(stackTrace)));
        errors.add("exception", new ActionError("error.general", stackTrace));

        // Check if the exception is a user readable exception
        if (exception instanceof UserReadableError)
        {
            UserReadableError userError = (UserReadableError) exception;

            // Check that it contains a user readable message
            if (userError.isUserReadable())
            {
                // Check if there is an error message key to use
                if (userError.getUserMessageKey() != null)
                {
                    errors.add("generalerror",
                        new ActionError(userError.getUserMessageKey(), userError.getUserMessageKey()));
                }

                // There is no error message key to use so default to error.general and pass the error message as an
                // argument so that it will be displayed
                else
                {
                    errors.add("generalerror", new ActionError("error.general", userError.getUserMessage()));
                }

                return;
            }
        }

        // Not a user reable exception so print a standard error message
        errors.add("generalerror", new ActionError("error.internalerror"));
    }

Converts an exception into struts action errors. The exception stack trace is stored under the 'exception'
message key. The message resource 'error.internalerror' is stored under the message key 'generalerror'. The stack
trace is pretty printed in HTML.

@param exception The exception to be converted into struts action errors.
@param errors    The struts action errors object into which the action errors should be placed.

@todo  This method can be modified to check if the exception is a user readable exception and to insert the user
readable message under the 'generalerror' message key. Currently it does not handle user readable errors
like this.

Converts an exception into struts action errors . The exception stack trace is stored under the exception message key . The message resource error . internalerror is stored under the message key generalerror . The stack trace is pretty printed in HTML .


public void write(String str, int off, int len) throws IOException
    {
        // Get just the portion of the input string to display
        String inputString = str.substring(off, off + len);

        StringBuffer outputString = new StringBuffer();

        // Build a string tokenizer that uses '\n' as its splitting character
        // Cycle through all tokens
        for (StringTokenizer tokenizer = new StringTokenizer(inputString, "\n", true); tokenizer.hasMoreTokens();)
        {
            // Replace '\n' token with a

            String nextToken = tokenizer.nextToken();

            if ("\n".equals(nextToken))
            {
                outputString.append("
");
            }
            else
            {
                outputString.append(nextToken);
            }
        }

        // Write out the generated string
        out.write(outputString.toString());
    }

Writes a string of characters to the filtered writer. Any newline characters '\n' are replaced with an HTML break
tag "<br>".

@param  str The character array to write.
@param  off The offset into the array to begin writing from.
@param  len The number of characters to write.

@throws IOException If the writer won't accept the string.

Writes a string of characters to the filtered writer . Any newline characters \ n are replaced with an HTML break tag &lt ; br&gt ; .


public Map<String, OrdinalAttribute> classify(State state) throws ClassifyingFailureException
    {
        // Start at the root of the decision tree.
        DecisionTree currentNode = dt;

        // Loop down the decision tree until a leaf node is found.
        while (true) // !currentNode.isLeaf())
        {
            DecisionTreeElement element = currentNode.getElement();

            // Check that the current element really is a decision.
            if (element instanceof Decision)
            {
                Decision decision = (Decision) element;

                // Apply the decision at the current node to the state to be classified to get a new tree.
                currentNode = decision.decide(state); // , currentNode);
            }
            else if (element instanceof Assignment)
            {
                // Cast the element to an Assignment as this is the only type of leaf that is possible.
                Assignment assignment = (Assignment) element;

                // Return the assignment in a map.
                Map<String, OrdinalAttribute> assignmentMap = new HashMap<String, OrdinalAttribute>();

                assignmentMap.put(assignment.getPropertyName(), assignment.getAttribute());

                return assignmentMap;
            }

            // It is possible that a node may be of type Pending if an incomplete tree has been used to
            // run this classification on.
            else
            {
                // Throw a classification exception due to an incomplete decision tree.
                throw new ClassifyingFailureException("A node which is not a decision was encountered.", null);
            }
            // What happens if the decision could not operate on the state, either because of a missing property or
            // because its property was not of the type that the decision was expecting? Can either throw an exception,
            // return an empty assignment, or implement an algorithm for coping with missing properties.
        }
    }

Classifies a state using the decision tree.

@param  state The input data point to classify.

@return A classification of the data point as an mapping from the output property that the decision tree was
trained on to this classifiers belief abouts its value.

@throws ClassifyingFailureException If the decision tree is not completed and this classifier encounters a
pending node in the tree that is still to be built.

Classifies a state using the decision tree .


public int compare(T a, T b)
    {
        boolean aRb = partialOrdering.evaluate(a, b);

        if (!aRb)
        {
            return -1;
        }

        boolean bRa = partialOrdering.evaluate(b, a);

        return (aRb && bRa) ? 0 : 1;
    }

public int compare ( T a , T b ) { boolean aRb = partialOrdering . evaluate ( a , b ) ; if ( ! aRb ) { return - 1 ; } boolean bRa = partialOrdering . evaluate ( b , a ) ; return ( aRb && bRa ) ? 0 : 1 ; }

Translates the partial order into the +1, 0, -1 convention needed by Comparators.

@param  a The first item to compare.
@param  b The second item to compare.

@return 0 if the two elements are equal under the partial ordering, 1 if aRb, and -1 if !aRb.

Translates the partial order into the + 1 0 - 1 convention needed by Comparators .


public Iterator iterator()
    {
        try
        {
            DistributedIteratorImpl di;

            di = new DistributedIteratorImpl(super.iterator());

            return new ClientIterator(di);
        }
        catch (RemoteException e)
        {
            // Rethrow the RemoteException as a RuntimeException so as not to conflict with the interface of ArrayList
            throw new IllegalStateException("There was a RemoteExcpetion.", e);
        }
    }

Returns a distriubuted iterator that can provide elements of the list on demand over a remote connection.

@return A {@link com.thesett.common.util.distributed.DistributedIterator} that provides the elements of the list
on demand instead of all at once.

Returns a distriubuted iterator that can provide elements of the list on demand over a remote connection .


public static int intLogBase2(int value)
    {
        int temp1;
        int temp2 = value >> 16;

        if (temp2 > 0)
        {
            temp1 = temp2 >> 8;

            return (temp1 > 0) ? (24 + LOG_TABLE_256[temp1]) : (16 + LOG_TABLE_256[temp2]);
        }
        else
        {
            temp1 = value >> 8;

            return (temp1 > 0) ? (8 + LOG_TABLE_256[temp1]) : LOG_TABLE_256[value];
        }
    }

public static int intLogBase2 ( int value ) { int temp1 ; int temp2 = value >> 16 ; if ( temp2 > 0 ) { temp1 = temp2 >> 8 ; return ( temp1 > 0 ) ? ( 24 + LOG_TABLE_256 [ temp1 ] ) : ( 16 + LOG_TABLE_256 [ temp2 ] ) ; } else { temp1 = value >> 8 ; return ( temp1 > 0 ) ? ( 8 + LOG_TABLE_256 [ temp1 ] ) : LOG_TABLE_256 [ value ] ; } }

Calcalates the log base 2 of an integer. This code is tuned to uniformly distributed output values, longer
numbers are slightly favoured.

@param  value The value to calculate for.

@return Log base 2 of the input value.

Calcalates the log base 2 of an integer . This code is tuned to uniformly distributed output values longer numbers are slightly favoured .


public static int intLogBase2v2(int value)
    {
        int temp;

        if ((temp = value >> 24) > 0)
        {
            return 24 + LOG_TABLE_256[temp];
        }
        else if ((temp = value >> 16) > 0)
        {
            return 16 + LOG_TABLE_256[temp];
        }
        else if ((temp = value >> 8) > 0)
        {
            return 8 + LOG_TABLE_256[temp];
        }
        else
        {
            return LOG_TABLE_256[value];
        }
    }

public static int intLogBase2v2 ( int value ) { int temp ; if ( ( temp = value >> 24 ) > 0 ) { return 24 + LOG_TABLE_256 [ temp ] ; } else if ( ( temp = value >> 16 ) > 0 ) { return 16 + LOG_TABLE_256 [ temp ] ; } else if ( ( temp = value >> 8 ) > 0 ) { return 8 + LOG_TABLE_256 [ temp ] ; } else { return LOG_TABLE_256 [ value ] ; } }

Calcalates the log base 2 of an integer. This code is tuned to uniformly distributed input values, longer numbers
are favoured.

@param  value The value to calculate for.

@return Log base 2 of the input value.

Calcalates the log base 2 of an integer . This code is tuned to uniformly distributed input values longer numbers are favoured .


Calcalates the log base 10 of an integer. This produces results faster for longer numbers.

@param  value The value to calculate for.

@return Log base 10 of the input value.

Calcalates the log base 10 of an integer . This produces results faster for longer numbers .


Calcalates the log base 10 of an integer. This produces results faster for shorter numbers.

@param  value The value to calculate for.

@return Log base 10 of the input value.

Calcalates the log base 10 of an integer . This produces results faster for shorter numbers .


Calcalates the log base 10 of an integer. This method favours shorter numbers.

@param  value The value to calculate for.

@return Log base 10 of the input value.

Calcalates the log base 10 of an integer . This method favours shorter numbers .


Calcalates the log base 10 of an integer. This method favours longer numbers, or evenly distributed input.

@param  value The value to calculate for.

@return Log base 10 of the input value.

Calcalates the log base 10 of an integer . This method favours longer numbers or evenly distributed input .


public static int getCharacterCountInt32(int value)
    {
        if (value >= 0)
        {
            return getCharacterCountUInt32(value);
        }
        else if (value == Integer.MIN_VALUE)
        {
            return getCharacterCountUInt32(Integer.MAX_VALUE) + 1;
        }
        else
        {
            return getCharacterCountUInt32(-value) + 1;
        }
    }

public static int getCharacterCountInt32 ( int value ) { if ( value >= 0 ) { return getCharacterCountUInt32 ( value ) ; } else if ( value == Integer . MIN_VALUE ) { return getCharacterCountUInt32 ( Integer . MAX_VALUE ) + 1 ; } else { return getCharacterCountUInt32 ( - value ) + 1 ; } }

Calculates the number of ASCII characters that will be needed to represent a specifed signed 32-bit integer.

@param  value The value to get the character count for.

@return The number of ASCII character need to represent an signed 32-bit integer.

Calculates the number of ASCII characters that will be needed to represent a specifed signed 32 - bit integer .


public static int getCharacterCountInt64(long value)
    {
        if (value >= 0)
        {
            return getCharacterCountUInt64(value);
        }
        else if (value == Long.MIN_VALUE)
        {
            return getCharacterCountUInt64(Long.MAX_VALUE) + 1;
        }
        else
        {
            return getCharacterCountUInt64(-value) + 1;
        }
    }

public static int getCharacterCountInt64 ( long value ) { if ( value >= 0 ) { return getCharacterCountUInt64 ( value ) ; } else if ( value == Long . MIN_VALUE ) { return getCharacterCountUInt64 ( Long . MAX_VALUE ) + 1 ; } else { return getCharacterCountUInt64 ( - value ) + 1 ; } }

Calculates the number of ASCII characters that will be needed to represent a specifed signed 64-bit integer.

@param  value The value to get the character count for.

@return The number of ASCII character need to represent an signed 64-bit integer.

Calculates the number of ASCII characters that will be needed to represent a specifed signed 64 - bit integer .


public static int getCharacterCountDecimal(long integerValue, int scale)
    {
        boolean isNeg = integerValue < 0;

        // Work out how many digits will be needed for the number, adding space for the minus sign, the decimal
        // point and leading zeros if needed.
        int totalDigits = BitHackUtils.getCharacterCountInt64(integerValue);
        int totalLength = totalDigits;

        if (isNeg)
        {
            totalDigits--; // Minus sign already accounted for.
        }

        if (scale > 0)
        {
            totalLength++; // For the decimal point.

            if (scale >= totalDigits)
            {
                // For the leading zeros (+ 1 for the zero before decimal point).
                totalLength += (scale - totalDigits) + 1;
            }
        }
        else
        {
            // Add a zero for each negative point in scale
            totalLength -= scale;
        }

        return totalLength;
    }

Calculates the number of ASCII characters that will be needed to represent a specified signed decimal number.

@param  integerValue The integer component of the decimal number.
@param  scale        The scale component of the decimal number.

@return The number of ASCII character need to represent a signed decimal number.

Calculates the number of ASCII characters that will be needed to represent a specified signed decimal number .


public void setHead(Functor head, SizeableList<WAMInstruction> instructions)
    {
        this.head = head;

        addInstructions(instructions);
    }

public void setHead ( Functor head , SizeableList < WAMInstruction > instructions ) { this . head = head ; addInstructions ( instructions ) ; }

Sets a compiled head functor to this clause.

@param head         The head of this clause.
@param instructions A list of instructions to add to the head.

Sets a compiled head functor to this clause .


public void emmitCode(ByteBuffer buffer, WAMMachine machine, WAMCallPoint callPoint) throws LinkageException
    {
        // Ensure that the size of the instruction listing does not exceed max int (highly unlikely).
        if (sizeof() > Integer.MAX_VALUE)
        {
            throw new IllegalStateException("The instruction listing size exceeds Integer.MAX_VALUE.");
        }

        // Used to keep track of the size of the emitted code, in bytes, as it is written.
        int length = 0;

        // Insert the compiled code into the byte code machine's code area.
        for (WAMInstruction instruction : instructions)
        {
            instruction.emmitCode(buffer, machine);
            length += instruction.sizeof();
        }

        // Keep record of the machine that the code is hosted in, and the call point of the functor within the machine.
        this.machine = machine;
        this.callPoint = callPoint;

        // Record the fact that the code is now linked into a machine.
        this.status = LinkStatus.Linked;
    }

Emmits the binary byte code for the clause into a machine, writing into the specified byte array. The state of
this clause is changed to 'Linked' to indicate that it has been linked into a binary machine.

@param  buffer    The code buffer to write to.
@param  machine   The binary machine to resolve call-points against, and to record as being linked into.
@param  callPoint The call point within the machine, at which the code is to be stored.

@throws LinkageException If required symbols to link to cannot be found in the binary machine.

Emmits the binary byte code for the clause into a machine writing into the specified byte array . The state of this clause is changed to Linked to indicate that it has been linked into a binary machine .


protected void setCurrentScreen(WorkFlowScreenPanel screen)
    {
        // Remove any existing screen from the panel
        panel.removeAll();

        // Place the new screen into the panel
        panel.add(screen);

        // Check if the screen is not already in the stack of accessed screens. It may be if this is the second time
        // the screen is visited foir example if the back button is used.
        if (!accessedScreens.contains(screen))
        {
            // Add the screen to the stack of accessed screens
            accessedScreens.push(screen);
        }

        // Update the work flow state to reflect the change to a new screen state
        state.setCurrentScreenState(screen.getState());

        // Keep track of the current screen in a local member variable
        currentScreen = screen;

        // Initialize the new screen
        screen.initialize();

        // Force the panel to redraw
        panel.validate();
    }

This is a helper method that controller implementations may find useful for moving to a new screen. It places the
screen into the panel that this controller was built with, replacing any existing screen, changes the underlying
state to reflect the change to a new current screen and calls the new screens initialize method.

@param screen The new work flow screen to be displayed.

This is a helper method that controller implementations may find useful for moving to a new screen . It places the screen into the panel that this controller was built with replacing any existing screen changes the underlying state to reflect the change to a new current screen and calls the new screens initialize method .


public boolean evaluate(T t)
    {
        // Start by assuming that the candidate will be a member of the predicate.
        boolean passed = true;

        // Loop through all predicates and fail if any one of them does.
        for (UnaryPredicate<T> predicate : chain)
        {
            if (!predicate.evaluate(t))
            {
                passed = false;

                break;
            }
        }

        return passed;
    }

Evaluates a logical predicate.

@param  t The object to test for predicate membership.

@return <tt>true</tt> if the object is a member of the predicate, <tt>false</tt> otherwise.


public String getProperty(String key)
    {
        // Try to get the callers class name and method name by examing the stack.
        String className = null;
        String methodName = null;

        // Java 1.4 onwards only.
        /*try
        {
            throw new Exception();
        }
        catch (Exception e)
        {
            StackTraceElement[] stack = e.getStackTrace();

            // Check that the stack trace contains at least two elements, one for this method and one for the caller.
            if (stack.length >= 2)
            {
                className = stack[1].getClassName();
                methodName = stack[1].getMethodName();
            }
        }*/

        // Java 1.5 onwards only.
        StackTraceElement[] stack = Thread.currentThread().getStackTrace();

        // Check that the stack trace contains at least two elements, one for this method and one for the caller.
        if (stack.length >= 2)
        {
            className = stack[1].getClassName();
            methodName = stack[1].getMethodName();
        }

        // Java 1.3 and before? Not sure, some horrible thing that parses the text spat out by printStackTrace?

        return getProperty(className, methodName, key);
    }

Looks up a property value relative to the environment, callers class and method. The default environment will be
checked for a matching property if defaults are being used. In order to work out the callers class and method
this method throws an exception and then searches one level up its stack frames.

@param  key The property key.

@return The value of this property searching from the most specific definition (environment, class, method, key)
to the most general (key only), unless use of default environments is turned off in which case the most
general proeprty searched is (environment, key).

Looks up a property value relative to the environment callers class and method . The default environment will be checked for a matching property if defaults are being used . In order to work out the callers class and method this method throws an exception and then searches one level up its stack frames .


public String[] getProperties(String key)
    {
        // Try to get the callers class name and method name by throwing an exception an searching the stack frames.
        String className = null;
        String methodName = null;

        /* Java 1.4 onwards only.
           try {
             throw new Exception();
           } catch (Exception e) {
             StackTraceElement[] stack = e.getStackTrace();
             // Check that the stack trace contains at least two elements, one for this method and one for the caller.
             if (stack.length >= 2) {
               className = stack[1].getClassName();
               methodName = stack[1].getMethodName();
             }
           }*/
        return getProperties(className, methodName, key);
    }

Looks up an array property value relative to the environment, callers class and method. The default environment
will be checked for a matching array property if defaults are being used. In order to work out the callers class
and method this method throws an exception and then searches one level up its stack frames.

@param  key The property key.

@return The array value of this indexed property searching from the most specific definition (environment, class,
method, key) to the most general (key only), unless use of default environments is turned off in which
case the most general proeprty searched is (environment, key).

Looks up an array property value relative to the environment callers class and method . The default environment will be checked for a matching array property if defaults are being used . In order to work out the callers class and method this method throws an exception and then searches one level up its stack frames .


protected Iterator getKeyIterator(final String base, final String modifier, final String key)
    {
        return new Iterator()
            {
                // The key ordering count always begins at the start of the ORDER array.
                private int i;

                public boolean hasNext()
                {
                    return (useDefaults ? ((i < ORDER.length) && (ORDER[i] > ENVIRONMENT_DEFAULTS_CUTOFF))
                                        : (i < ORDER.length));
                }

                public Object next()
                {
                    // Check that there is a next element and return null if not.
                    if (!hasNext())
                    {
                        return null;
                    }

                    // Get the next ordering count.
                    int o = ORDER[i];

                    // Do bit matching on the count to choose which elements to include in the key.
                    String result =
                        (((o & E) != 0) ? (environment + ".") : "") + (((o & B) != 0) ? (base + ".") : "") +
                        (((o & M) != 0) ? (modifier + ".") : "") + key;

                    // Increment the iterator to get the next key on the next call.
                    i++;

                    return result;
                }

                public void remove()
                {
                    // This method is not supported.
                    throw new UnsupportedOperationException("remove() is not supported on this key order iterator as " +
                        "the ordering cannot be changed");
                }
            };
    }

For a given environment, base, modifier and key and setting of the use of default environments feature this
generates an iterator that walks over the order in which to try and access properties.

<p>See the {@link #ORDER} constant for an explanation of how the key ordering is generated.

@param  base     The name of the class to retrieve properties relative to.
@param  modifier The modifier (which may stand for a method of the class).
@param  key      The property key.

@return An Iterator over String keys defining the order in which properties should be accessed.

For a given environment base modifier and key and setting of the use of default environments feature this generates an iterator that walks over the order in which to try and access properties .


protected void createArrayProperties()
    {
        // Scan through all defined properties.
        for (Object o : keySet())
        {
            String key = (String) o;
            String value = super.getProperty(key);

            // Split the property key into everything before the last '.' and after it.
            int lastDotIndex = key.lastIndexOf('.');
            String keyEnding = key.substring(lastDotIndex + 1, key.length());
            String keyStart = key.substring(0, (lastDotIndex == -1) ? 0 : lastDotIndex);

            // Check if the property key ends in an integer, in which case it is an array property.
            int index = 0;

            try
            {
                index = Integer.parseInt(keyEnding);
            }
            catch (NumberFormatException e)
            {
                // The ending is not an integer so its not an array.
                // Exception can be ignored as it means this property is not an array.
                e = null;

                continue;
            }

            // Check if an array property already exists for this base name and create one if not.
            ArrayList propArray = (ArrayList) arrayProperties.get(keyStart);

            if (propArray == null)
            {
                propArray = new ArrayList();
                arrayProperties.put(keyStart, propArray);
            }

            // Add the new property value to the array property for the index.
            propArray.set(index, value);
        }
    }

Scans all the properties in the parent Properties object and creates arrays for any array property definitions.

Array properties are defined with indexes. For example:

property.1=one

property.2=two

property.3=three

Note that these properties will be stored as the 'empty string' or "" property array.

.1=one

2=two

Scans all the properties in the parent Properties object and creates arrays for any array property definitions .


public void setRate(float hertz)
    {
        // Check that the argument is above zero.
        if (hertz <= 0.0f)
        {
            throw new IllegalArgumentException("The throttle rate must be above zero.");
        }

        // Calculate the cycle time.
        cycleTimeNanos = (long) (1000000000f / hertz);

        // Reset the first pass flag.
        firstCall = false;
        firstCheckCall = false;
    }

Specifies the throttling rate in operations per second. This must be called with with a value, the inverse of
which is a measurement in nano seconds, such that the number of nano seconds do not overflow a long integer. The
value must also be larger than zero.

@param hertz The throttling rate in cycles per second.

Specifies the throttling rate in operations per second . This must be called with with a value the inverse of which is a measurement in nano seconds such that the number of nano seconds do not overflow a long integer . The value must also be larger than zero .


protected NumericType evaluate(NumericType firstNumber)
    {
        // If the argument is a real number, then use real number arithmetic, otherwise use integer arithmetic.
        if (firstNumber.isInteger())
        {
            return new IntLiteral(-firstNumber.intValue());
        }
        else
        {
            return new DoubleLiteral(-firstNumber.doubleValue());
        }
    }

Evaluates the arithmetic operator on its numeric argument.

@param  firstNumber The first argument.

@return The result of performing the arithmetic operator on its argument.

Evaluates the arithmetic operator on its numeric argument .


protected void findProperties()
    {
        /*log.fine("findProperties: called");*/

        // Try to load the properties from a file referenced by the system property matching
        // the properties file name.
        properties = getPropertiesUsingSystemProperty();

        if (properties != null)
        {
            /*log.fine("loaded properties using the system property");*/

            // The properties were succesfully located and loaded
            return;
        }

        /*log.fine("failed to get properties from the system properties");*/

        // Try to load the properties from a resource on the classpath using the current
        // class loader
        properties = getPropertiesUsingClasspath();

        if (properties != null)
        {
            /*log.fine("loaded properties from the class path");*/

            // The properties were succesfully located and loaded
            return;
        }

        /*log.fine("failed to get properties from the classpath");*/

        // Try to load the properties from a file relative to the current working directory
        properties = getPropertiesUsingCWD();

        if (properties != null)
        {
            /*log.fine("loaded properties from the current working directory");*/

            // The properties were succesfully located and loaded
            return;
        }

        /*log.fine("failed to get properties from the current working directory");*/
    }

This methods attempts to load the properties from a file or URL referenced by the system property with the same
name as the properties resource name, from a resource on the classpath with the same name as the properties
resource name or from a properties file name relative to the current working directory. It tries these methods
sequentially one after the other until one succeeds.

This methods attempts to load the properties from a file or URL referenced by the system property with the same name as the properties resource name from a resource on the classpath with the same name as the properties resource name or from a properties file name relative to the current working directory . It tries these methods sequentially one after the other until one succeeds .


protected Properties getPropertiesUsingSystemProperty()
    {
        /*log.fine("getPropertiesUsingSystemProperty: called");*/

        // Get the path to the file from the system properties
        /*log.fine("getPropertiesResourceName() = " + getPropertiesResourceName());*/

        String path = System.getProperty(getPropertiesResourceName());

        /*log.fine("properties resource name = " + getPropertiesResourceName());*/
        /*log.fine("path = " + path);*/

        // Use PropertiesHelper to try to load the properties from the path
        try
        {
            return PropertiesHelper.getProperties(path);
        }
        catch (IOException e)
        {
            /*log.fine("Could not load properties from path " + path);*/

            // Failure of this method is noted, so exception is ignored.
            e = null;
        }

        return null;
    }

Tries to load the properties from the file or URL named by the system property with name mathching the properties
resource name.

@return The properties found under the file name or URL or null if none can be found there.

Tries to load the properties from the file or URL named by the system property with name mathching the properties resource name .


protected Properties getPropertiesUsingClasspath()
    {
        /*log.fine("getPropertiesUsingClasspath: called");*/

        // Try to open the properties resource name as an input stream from the classpath
        InputStream is = this.getClass().getClassLoader().getResourceAsStream(getPropertiesResourceName());

        // Use PropertiesHelper to try to load the properties from the input stream if one was succesfully created
        if (is != null)
        {
            try
            {
                return PropertiesHelper.getProperties(is);
            }
            catch (IOException e)
            {
                /*log.fine("Could not load properties from classpath");*/

                // Failure of this method is noted, so exception is ignored.
                e = null;
            }
        }

        return null;
    }

Tries to load the properties from the classpath using the classloader for this class.

@return The properties loaded from the resource name under the classpath or null if none can be found there.

Tries to load the properties from the classpath using the classloader for this class .


protected Properties getPropertiesUsingCWD()
    {
        /*log.fine("getPropertiesUsingCWD: called");*/

        // Use PropertiesHelper to try to load the properties from a file or URl
        try
        {
            return PropertiesHelper.getProperties(getPropertiesResourceName());
        }
        catch (IOException e)
        {
            /*log.fine("Could not load properties from file or URL " + getPropertiesResourceName());*/

            // Failure of this method is noted, so exception is ignored.
            e = null;
        }

        return null;
    }

Tries to load the properties as a file or URL matching the properties resource name. File names will be taken
relative to the current working directory.

@return The properties found from the resource name as a file in the current working directory or null if none
can be found there.

Tries to load the properties as a file or URL matching the properties resource name . File names will be taken relative to the current working directory .


protected void leaveFunctor(Functor functor)
    {
        int pos = traverser.getPosition();

        if (!traverser.isInHead() && (pos >= 0))
        {
            Functor transformed = builtInTransform.apply(functor);

            if (functor != transformed)
            {
                /*log.fine("Transformed: " + functor + " to " + transformed.getClass());*/

                BuiltInFunctor builtInFunctor = (BuiltInFunctor) transformed;

                Term parentTerm = traverser.getParentContext().getTerm();

                if (parentTerm instanceof Clause)
                {
                    Clause parentClause = (Clause) parentTerm;

                    parentClause.getBody()[pos] = builtInFunctor;

                }
                else if (parentTerm instanceof Functor)
                {
                    Functor parentFunctor = (Functor) parentTerm;

                    parentFunctor.getArguments()[pos] = builtInFunctor;
                }
            }
        }
    }

Applies the built-in transform during a post-fix visit of a term.

@param functor The functor to visit.

Applies the built - in transform during a post - fix visit of a term .


public Term getValue()
    {
        Term result = this;
        Term assignment = this.substitution;

        // If the variable is assigned, loops down the chain of assignments until no more can be found. Whatever term
        // is found at the end of the chain of assignments is the value of this variable.
        while (assignment != null)
        {
            result = assignment;

            if (!assignment.isVar())
            {
                break;
            }
            else
            {
                assignment = ((Variable) assignment).substitution;
            }
        }

        return result;
    }

Gets the actual value of a term, which is either the term itself, or in the case of variables, the value that is
currently assigned to the variable. When the variable is free, the variable term itself is returned.

@return The term itself, or the assigned value of this variable.

Gets the actual value of a term which is either the term itself or in the case of variables the value that is currently assigned to the variable . When the variable is free the variable term itself is returned .


public void setSubstitution(Term term)
    {
        Term termToBindTo = term;

        // When binding against a variable, always bind to its storage cell and not the variable itself.
        if (termToBindTo instanceof Variable)
        {
            Variable variableToBindTo = (Variable) term;
            termToBindTo = variableToBindTo.getStorageCell(variableToBindTo);
        }

        substitution = termToBindTo;
    }

Binds this variable to the specified value.

@param term The value to bind this variable to.

Binds this variable to the specified value .


public Queue<SearchNode<O, T>> createQueue()
    {
        return new PriorityQueue<SearchNode<O, T>>(11, new GreedyComparator());
    }

public Queue < SearchNode < O , T > > createQueue ( ) { return new PriorityQueue < SearchNode < O , T > > ( 11 , new GreedyComparator ( ) ) ; }

Creates the correct type of queue for this search. This search uses a priority queue ordered by heuristic value.

@return An empty priority queue with heuristic ordering.

Creates the correct type of queue for this search . This search uses a priority queue ordered by heuristic value .


public void cleanUp()
    {
        if (oos != null)
        {
            try
            {
                oos.close();
            }
            catch (IOException e)
            {
                LogLog.error("Could not close oos.", e);
            }

            oos = null;
        }

        if (connector != null)
        {
            // LogLog.debug("Interrupting the connector.");
            connector.interrupted = true;
            connector = null; // allow gc
        }
    }

Drop the connection to the remote host and release the underlying connector thread if it has been created.

Drop the connection to the remote host and release the underlying connector thread if it has been created .


public void append(LoggingEvent event)
    {
        if (event == null)
        {
            return;
        }

        if (address == null)
        {
            errorHandler.error("No remote host is set for SocketAppender named \"" + this.name + "\".");

            return;
        }

        if (oos != null)
        {
            try
            {
                if (locationInfo)
                {
                    event.getLocationInformation();
                }

                oos.writeObject(event);

                // LogLog.debug("=========Flushing.");
                oos.flush();

                if (++counter >= RESET_FREQUENCY)
                {
                    counter = 0;

                    // Failing to reset the object output stream every now and
                    // then creates a serious memory leak.
                    // System.err.println("Doing oos.reset()");
                    oos.reset();
                }
            }
            catch (IOException e)
            {
                oos = null;
                LogLog.warn("Detected problem with connection: " + e);

                if (reconnectionDelay > 0)
                {
                    fireConnector();
                }
            }
        }
    }

Appends a logging event to the remote event reciever.

@param event The logging event to send.

Appends a logging event to the remote event reciever .


void fireConnector()
    {
        if (connector == null)
        {
            LogLog.debug("Starting a new connector thread.");
            connector = new Connector();
            connector.setDaemon(true);
            connector.setPriority(Thread.MIN_PRIORITY);
            connector.start();
        }
    }

void
fireConnector
(
)
{
if
(
connector
==
)
{
LogLog
.
debug
(
"Starting a new connector thread."
)
;
connector
=
new
Connector
(
)
;
connector
.
setDaemon
(
true
)
;
connector
.
setPriority
(
Thread
.
MIN_PRIORITY
)
;
connector
.
start
(
)
;
}
}


protected void initializePrinters()
    {
        int maxColumns = 0;

        printers.add(new SourceClausePrinter(interner, symbolTable, traverser, maxColumns++, printTable));
        printers.add(new PositionPrinter(interner, symbolTable, traverser, maxColumns++, printTable));
        printers.add(new UnoptimizedLabelPrinter(interner, symbolTable, traverser, maxColumns++, printTable));
        printers.add(new UnoptimizedByteCodePrinter(interner, symbolTable, traverser, maxColumns++, printTable));
        printers.add(new LabelPrinter(interner, symbolTable, traverser, maxColumns++, printTable));
        printers.add(new ByteCodePrinter(interner, symbolTable, traverser, maxColumns++, printTable));
    }

protected void initializePrinters ( ) { int maxColumns = 0 ; printers . add ( new SourceClausePrinter ( interner , symbolTable , traverser , maxColumns ++ , printTable ) ) ; printers . add ( new PositionPrinter ( interner , symbolTable , traverser , maxColumns ++ , printTable ) ) ; printers . add ( new UnoptimizedLabelPrinter ( interner , symbolTable , traverser , maxColumns ++ , printTable ) ) ; printers . add ( new UnoptimizedByteCodePrinter ( interner , symbolTable , traverser , maxColumns ++ , printTable ) ) ; printers . add ( new LabelPrinter ( interner , symbolTable , traverser , maxColumns ++ , printTable ) ) ; printers . add ( new ByteCodePrinter ( interner , symbolTable , traverser , maxColumns ++ , printTable ) ) ; }


public void commit()
    {
        TxId txId = null;

        // Check if in a higher transactional mode than none, otherwise commit does nothing.
        if (!getIsolationLevel().equals(IsolationLevel.None))
        {
            // Extract the current transaction id.
            txId = TxManager.getTxIdFromThread();

            // Wait until the global write lock can be acquired by this transaction.
            try
            {
                acquireGlobalWriteLock(txId);
            }
            catch (InterruptedException e)
            {
                // The commit was interrupted, so cannot succeed.
                throw new IllegalStateException("Interrupted whilst commit is waiting for global write lock.", e);
            }

            // Check that this transaction has made changes to be committed.
            List<TxOperation> alterations = txWrites.get(txId);

            try
            {
                if (alterations != null)
                {
                    // Loop through all the writes that the transaction wants to apply to the resource.
                    for (TxOperation nextAlteration : alterations)
                    {
                        // Apply the change and update the term resource.
                        nextAlteration.execute();
                    }

                    // Clear the write behind cache for this transaction as its work has been completed.
                    txWrites.remove(txId);
                }
            }
            finally
            {
                // Release the global write lock.
                releaseGlobalWriteLock();
            }
        }
    }

When operating in transactional mode causes any changes since the last commit to be made visible to the search
method.

When operating in transactional mode causes any changes since the last commit to be made visible to the search method .


public void rollback()
    {
        TxId txId = null;

        // Check if in a higher transactional mode than none, otherwise commit does nothing.
        if (!getIsolationLevel().equals(IsolationLevel.None))
        {
            // Extract the current transaction id.
            txId = TxManager.getTxIdFromThread();

            // Check that this transaction has made changes to be rolled back.
            List<TxOperation> alterations = txWrites.get(txId);

            if (alterations != null)
            {
                // Loop through all the writes that the transaction wants to apply to the resource.
                for (TxOperation nextAlteration : alterations)
                {
                    // Cancel the operation.
                    nextAlteration.cancel(false);
                }
            }

            // Discard all the changes that the transaction was going to make.
            txWrites.remove(txId);
        }
    }

When operation in transactional mode causes any changes since the last commit to be dropped and never made
visible to the search method.

When operation in transactional mode causes any changes since the last commit to be dropped and never made visible to the search method .


public void requestWriteOperation(TxOperation op)
    {
        // Check if in a higher transactional mode than none and capture the transaction id if so.
        TxId txId = null;

        if (getIsolationLevel().compareTo(IsolationLevel.None) > 0)
        {
            // Extract the current transaction id.
            txId = TxManager.getTxIdFromThread();

            // Ensure that this resource is enlisted with the current session.
            enlistWithSession();

        }

        // For non-transactional isolation levels, apply the requested operation immediately.
        if (getIsolationLevel().equals(IsolationLevel.None))
        {
            op.execute();
        }

        // Add the operation to the transaction write-behind cache for the transaction id, if using transactional
        // isolation, to defer the operation untill commit time.
        else
        {
            addCachedOperation(txId, op);
        }
    }

Requests an operation that alters the transactional resource. This may be blocked until an appropriate lock can
be acquired, delayed until commit time, or actioned upon a copy of the data structure private to a transaction
branch.

<p/>This stores the requested operation for execution at commit time, unless running in non-transactional mode in
which case it is run immediately.

@param op The write operation as a future.

Requests an operation that alters the transactional resource . This may be blocked until an appropriate lock can be acquired delayed until commit time or actioned upon a copy of the data structure private to a transaction branch .


private void addCachedOperation(TxId txId, TxOperation cachedWriteOperation)
    {
        List<TxOperation> writeCache = txWrites.get(txId);

        if (writeCache == null)
        {
            writeCache = new ArrayList<TxOperation>();
            txWrites.put(txId, writeCache);
        }

        writeCache.add(cachedWriteOperation);
    }

private void addCachedOperation ( TxId txId , TxOperation cachedWriteOperation ) { List < TxOperation > writeCache = txWrites . get ( txId ) ; if ( writeCache == null ) { writeCache = new ArrayList < TxOperation > ( ) ; txWrites . put ( txId , writeCache ) ; } writeCache . add ( cachedWriteOperation ) ; }

Adds a transactional operation to the transactional write-behind cache for the specified transaction. If no cache
exists for the specified transaction id, a new one is created.

@param txId                 The transaction id to store the operation against.
@param cachedWriteOperation The operation to store.

Adds a transactional operation to the transactional write - behind cache for the specified transaction . If no cache exists for the specified transaction id a new one is created .


private void acquireGlobalWriteLock(TxId txId) throws InterruptedException
    {
        // Get the global write lock to ensure only one thread at a time can execute this code.
        globalLock.writeLock().lock();

        // Use a try block so that the corresponding finally block guarantees release of the thread lock.
        try
        {
            // Check that this transaction does not already own the lock.
            if (!txId.equals(globalWriteLockTxId))
            {
                // Wait until the write lock becomes free.
                while (globalWriteLockTxId != null)
                {
                    globalWriteLockFree.await();
                }

                // Assign the global write lock to this transaction.
                globalWriteLockTxId = txId;
            }
        }
        finally
        {
            // Ensure that the thread lock is released once assignment of the write lock to the transaction is complete.
            globalLock.writeLock().unlock();
        }
    }

Waits until the global write lock can be acquired by the specified transaction.

@param  txId The transaction id to acquite the global write lock for.

@throws InterruptedException If interrupted whilst waiting for the global write lock.

Waits until the global write lock can be acquired by the specified transaction .


private void releaseGlobalWriteLock()
    {
        // Get the global write lock to ensure only one thread at a time can execute this code.
        globalLock.writeLock().lock();

        // Use a try block so that the corresponding finally block guarantees release of the thread lock.
        try
        {
            // Release the global write lock, assigning it to no transaction.
            globalWriteLockTxId = null;

            // Signal that the write lock is now free.
            globalWriteLockFree.signal();
        }

        // Ensure that the thread lock is released once assignment of the write lock to the transaction is complete.
        finally
        {
            globalLock.writeLock().unlock();
        }
    }

Releases the global write lock from being assigned to a transaction.

Releases the global write lock from being assigned to a transaction .


private void enlistWithSession()
    {
        TxSession session = TxSessionImpl.getCurrentSession();

        // Ensure that this resource is being used within a session.
        if (session == null)
        {
            throw new IllegalStateException("Cannot access transactional resource outside of a session.");
        }

        // Ensure that this resource is enlisted with the session.
        session.enlist(this);
    }

Enlists this transactional resource with the current session. If no session exists this will fail.

@throws IllegalStateException If this resource is transactional and accessed outside of a transaction.

Enlists this transactional resource with the current session . If no session exists this will fail .


@Override
    public boolean enter(RuleSetNode ruleSetNode) {

        ScopeNode scopeNode = NodeTreeUtils.getFirstChild(ruleSetNode, ScopeNode.class);
        SelectorGroupNode selectorGroupNode = NodeTreeUtils.getFirstChild(ruleSetNode, SelectorGroupNode.class);

        if (selectorGroupNode == null) {
            return true;
        }

        List<SelectorNode> selectorNodes = NodeTreeUtils.getChildren(selectorGroupNode, SelectorNode.class);

        if (selectorNodes.size() < 0) {
            return true;
        }

        List<MediaQueryNode> mediaQueryNodes = NodeTreeUtils.getAndRemoveChildren(scopeNode, MediaQueryNode.class);

        for (MediaQueryNode mediaQueryNode : mediaQueryNodes) {
            ScopeNode mediaScopeNode = NodeTreeUtils.getFirstChild(mediaQueryNode, ScopeNode.class);

            List<RuleSetNode> nestedRuleSets = NodeTreeUtils.getAndRemoveChildren(mediaScopeNode, RuleSetNode.class);

            // if scope node for media query has anything more but whitespaces and rule sets than wrap it with rule set with the same selector group as outer rule set has
            if (mediaScopeNode.getChildren().size() > NodeTreeUtils.getChildren(mediaScopeNode, WhiteSpaceCollectionNode.class).size()) {
                RuleSetNode newRuleSetNode = new RuleSetNode();
                ScopeNode newScopeNode = new ScopeNode();
                newRuleSetNode.addChild(selectorGroupNode.clone());
                newRuleSetNode.addChild(newScopeNode);

                NodeTreeUtils.moveChildren(mediaScopeNode, newScopeNode);

                mediaScopeNode.clearChildren();
                mediaScopeNode.addChild(newRuleSetNode);
            }

            // adding outer selectors to every nested selectors
            for (RuleSetNode nestedRuleSet : nestedRuleSets) {
                List<SelectorGroupNode> nestedSelectorGroupNodes = NodeTreeUtils.getChildren(nestedRuleSet, SelectorGroupNode.class);

                for (SelectorGroupNode nestedSelectorGroupNode : nestedSelectorGroupNodes) {
                    List<SelectorNode> nestedSelectorNodes = NodeTreeUtils.getAndRemoveChildren(nestedSelectorGroupNode, SelectorNode.class);
                    NodeTreeUtils.getAndRemoveChildren(nestedSelectorGroupNode, SpacingNode.class);

                    for (SelectorNode selectorNode : selectorNodes) {
                        for (SelectorNode nestedSelectorNode : nestedSelectorNodes) {
                            if (nestedSelectorNode.getChildren().get(0) != null) {
                                if (nestedSelectorNode.getChildren().get(0) instanceof SelectorSegmentNode) {
                                    SelectorSegmentNode selectorSegmentNode = (SelectorSegmentNode) nestedSelectorNode.getChildren().get(0);
                                    selectorSegmentNode.setCombinator(" ");
                                }
                            }

                            for (int j = selectorNode.getChildren().size() - 1; j >= 0; j--) {
                                if (selectorNode.getChildren().get(j) instanceof SelectorSegmentNode) {
                                    SelectorSegmentNode selectorSegmentNode = (SelectorSegmentNode) selectorNode.getChildren().get(j).clone();

                                    nestedSelectorNode.addChild(0, selectorSegmentNode);
                                }
                            }

                            nestedSelectorGroupNode.addChild(nestedSelectorNode);
                            nestedSelectorGroupNode.addChild(new SpacingNode(" "));
                        }
                    }
                }
                mediaScopeNode.addChild(nestedRuleSet);
            }

            if (ruleSetNode.getParent() != null) {
                ruleSetNode.getParent().addChild(new SpacingNode("\n"));
                ruleSetNode.getParent().addChild(mediaQueryNode);
            }
        }

        return true;
    }

Locates nested MediaQueryNode inside RuleSetNode,
separates RuleSetNode and MediaQueryNode

If MediaQueryNode has nested RuleSetNodes than to every
nested selectors will added selector of input RuleSetNode

If MediaQueryNode has other nodes except WhiteSpaceCollectionNode and
RuleSetNode than all of that will be wrapped with new RuleSetNode with
the same selectors as has input RuleSetNode

Locates nested MediaQueryNode inside RuleSetNode separates RuleSetNode and MediaQueryNode


public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException
    {
        if (e == null)
        {
            throw new IllegalArgumentException("The 'e' parameter may not be null.");
        }

        ReentrantLock lock = this.lock;
        lock.lockInterruptibly();

        long nanos = unit.toNanos(timeout);

        try
        {
            do
            {
                if (insert(e, false))
                {
                    return true;
                }

                try
                {
                    nanos = notFull.awaitNanos(nanos);
                }
                catch (InterruptedException ie)
                {
                    // Wake up another thread waiting on notFull, as the condition may be true, but this thread
                    // was interrupted so cannot make use of it.
                    notFull.signal();

                    throw ie;
                }
            }
            while (nanos > 0);

            return false;
        }
        finally
        {
            lock.unlock();
        }
    }

Inserts the specified element into this queue, waiting if necessary up to the specified wait time for space to
become available.

@param  e       The element to add, may not be null.
@param  timeout How long to wait before giving up, in units of <tt>unit</tt>
@param  unit    A <tt>TimeUnit</tt> determining how to interpret the <tt>timeout</tt> parameter.

@return <tt>true</tt> if successful, or <tt>false</tt> if the specified waiting time elapses before space is
available.

@throws InterruptedException     If interrupted while waiting.
@throws IllegalArgumentException If the specified element is <tt>null</tt>.

Inserts the specified element into this queue waiting if necessary up to the specified wait time for space to become available .


public E poll(long timeout, TimeUnit unit) throws InterruptedException
    {
        ReentrantLock lock = this.lock;
        lock.lockInterruptibly();

        try
        {
            long nanos = unit.toNanos(timeout);

            do
            {
                if (count != 0)
                {
                    return extract(true, true).getElement();
                }

                try
                {
                    nanos = notEmpty.awaitNanos(nanos);
                }
                catch (InterruptedException ie)
                {
                    notEmpty.signal(); // propagate to non-interrupted thread
                    throw ie;
                }
            }
            while (nanos > 0);

            return null;
        }
        finally
        {
            lock.unlock();
        }
    }

public
E
poll
(
long
timeout
,
TimeUnit
unit
)
throws
InterruptedException
{
ReentrantLock
lock
=
this
.
lock
;
lock
.
lockInterruptibly
(
)
;
try
{
long
nanos
=
unit
.
toNanos
(
timeout
)
;
do
{
if
(
count
!=
0
)
{
return
extract
(
true
,
true
)
.
getElement
(
)
;
}
try
{
nanos
=
notEmpty
.
awaitNanos
(
nanos
)
;
}
catch
(
InterruptedException
ie
)
{
notEmpty
.
signal
(
)
;
// propagate to non-interrupted thread
throw
ie
;
}
}
while
(
nanos
>
0
)
;
return
;
}
finally
{
lock
.
unlock
(
)
;
}
}

Retrieves and removes the head of this queue, waiting if necessary up to the specified wait time if no elements
are present on this queue.

@param  timeout How long to wait before giving up, in units of <tt>unit</tt>.
@param  unit    A <tt>TimeUnit</tt> determining how to interpret the <tt>timeout</tt> parameter.

@return The head of this queue, or <tt>null</tt> if the specified waiting time elapses before an element is
present.

@throws InterruptedException If interrupted while waiting.

Retrieves and removes the head of this queue waiting if necessary up to the specified wait time if no elements are present on this queue .


public void put(E e) throws InterruptedException
    {
        try
        {
            tryPut(e);
        }
        catch (SynchException ex)
        {
            // This exception is deliberately ignored. See the method comment for information about this.
            ex = null;
        }
    }

Adds the specified element to this queue, waiting if necessary for space to become available.

<p/>This method delegated to {@link #tryPut} which can raise {@link SynchException}s. If any are raised this
method silently ignores them. Use the {@link #tryPut} method directly if you want to catch these exceptions.

@param  e The element to add.

@throws InterruptedException If interrupted while waiting.

Adds the specified element to this queue waiting if necessary for space to become available .


protected boolean insert(E element, boolean unlockAndBlock)
    {
        // Create a new record for the data item.
        SynchRecordImpl<E> record = new SynchRecordImpl<E>(element);

        boolean result = buffer.offer(record);

        if (result)
        {
            count++;

            // Tell any waiting consumers that the queue is not empty.
            notEmpty.signal();

            if (unlockAndBlock)
            {
                // Allow other threads to read/write the queue.
                lock.unlock();

                // Wait until a consumer takes this data item.
                record.waitForConsumer();
            }

            return true;
        }
        else
        {
            return false;
        }
    }

Insert element into the queue, then possibly signal that the queue is not empty and block the producer on the
element until permission to procede is given.

If the producer is to be blocked then the lock must be released first, otherwise no other process will be
able to get access to the queue. Hence, unlock and block are always set together.

Call only when holding the global lock.

@param  element        The element to insert in the queue.
@param  unlockAndBlock <tt>true</tt>If the global queue lock should be released and the producer should be
blocked.

@return <tt>true</tt> if the operation succeeded, <tt>false</tt> otherwise. If the result is <tt>true</tt> this
method may not return straight away, but only after the producer is unblocked by having its data consumed
if the unlockAndBlock flag is set. In the false case the method will return straight away, no matter what
value the unlockAndBlock flag has, leaving the global lock on.

Insert element into the queue then possibly signal that the queue is not empty and block the producer on the element until permission to procede is given .


public Object next()
    {
        try
        {
            Object ob = source.next();

            return ob;
        }
        catch (RemoteException e)
        {
            throw new IllegalStateException(e);
        }
    }

public Object next ( ) { try { Object ob = source . next ( ) ; return ob ; } catch ( RemoteException e ) { throw new IllegalStateException ( e ) ; } }

Fetches the next element from this iterator.

@return The next element in the iterator.

Fetches the next element from this iterator .


public boolean getPropertyAsBoolean(String propName)
    {
        String prop = getProperty(propName);

        return (prop != null) && Boolean.parseBoolean(prop);
    }

public boolean getPropertyAsBoolean ( String propName ) { String prop = getProperty ( propName ) ; return ( prop != null ) && Boolean . parseBoolean ( prop ) ; }

Parses a property as a boolean.

@param  propName The property.

@return The property as a boolean, or false if it does not exist.


public Integer getPropertyAsInteger(String propName)
    {
        String prop = getProperty(propName);

        return (prop != null) ? Integer.valueOf(prop) : null;
    }

public Integer getPropertyAsInteger ( String propName ) { String prop = getProperty ( propName ) ; return ( prop != null ) ? Integer . valueOf ( prop ) : null ; }

Parses a property as an integer.

@param  propName The property.

@return The property as a integer, or null if it does not exist.


public Long getPropertyAsLong(String propName)
    {
        String prop = getProperty(propName);

        return (prop != null) ? Long.valueOf(prop) : null;
    }

public Long getPropertyAsLong ( String propName ) { String prop = getProperty ( propName ) ; return ( prop != null ) ? Long . valueOf ( prop ) : null ; }

Parses a property as a long.

@param  propName The property.

@return The property as a long, or null if it does not exist.