Input: Creates a new time range type with the specified name if it does not already exist . [CODESPLIT] public static Type createInstance ( String name , TimeOnly min , TimeOnly max ) { // Ensure that min is less than or equal to max. if ( ( min != null ) && ( max != null ) && ( min . compareTo ( max ) > 0 ) ) { throw new IllegalArgumentException ( "'min' must be less than or equal to 'max'." ) ; } synchronized ( INT_RANGE_TYPES ) { // Add the newly created type to the map of all types. TimeRangeType newType = new TimeRangeType ( name , min , max ) ; // Ensure that the named type does not already exist, unless it has an identical definition already, in which // case the old definition can be re-used and the new one discarded. TimeRangeType oldType = INT_RANGE_TYPES . get ( name ) ; if ( ( oldType != null ) && ! oldType . equals ( newType ) ) { throw new IllegalArgumentException ( "The type '" + name + "' already exists and cannot be redefined." ) ; } else if ( ( oldType != null ) && oldType . equals ( newType ) ) { return oldType ; } else { INT_RANGE_TYPES . put ( name , newType ) ; return newType ; } } }


Input: { @inheritDoc } [CODESPLIT] public TimeOnly createRandomInstance ( ) { int start = minValue . getMilliseconds ( ) ; int end = maxValue . getMilliseconds ( ) ; return new TimeOnly ( ( long ) ( start + random . nextInt ( end - start ) ) ) ; }


Input: { [CODESPLIT] public void acceptVisitor ( TypeVisitor visitor ) { if ( visitor instanceof TimeRangeTypeVisitor ) { ( ( TimeRangeTypeVisitor ) visitor ) . visit ( this ) ; } else { super . acceptVisitor ( visitor ) ; } }


Input: Creates a new string pattern type with the specified name if it does not already exist . [CODESPLIT] public static Type createInstance ( String name , int maxLength , String pattern ) { synchronized ( STRING_PATTERN_TYPES ) { StringPatternType newType = new StringPatternType ( name , maxLength , pattern ) ; // Ensure that the named type does not already exist. StringPatternType oldType = STRING_PATTERN_TYPES . get ( name ) ; if ( ( oldType != null ) && ! oldType . equals ( newType ) ) { throw new IllegalArgumentException ( "The type '" + name + "' already exists and cannot be redefined." ) ; } else if ( ( oldType != null ) && oldType . equals ( newType ) ) { return oldType ; } else { // Add the newly created type to the map of all types. STRING_PATTERN_TYPES . put ( name , newType ) ; return newType ; } } }


Input: Checks a string value against this type to see if it is a valid instance of the type . [CODESPLIT] public boolean isInstance ( CharSequence value ) { // Check the value is under the maximum if one is set. // Check the value matches the pattern if one is set. return ( ( maxLength <= 0 ) || ( value . length ( ) <= maxLength ) ) && compiledPattern . matcher ( value ) . matches ( ) ; }


Input: { [CODESPLIT] public boolean isTopLevel ( ) { PositionalTermTraverserImpl . PositionalContextOperator position = contextStack . peek ( ) ; return ( position != null ) && position . isTopLevel ( ) ; }


Input: { [CODESPLIT] public boolean isInHead ( ) { PositionalTermTraverserImpl . PositionalContextOperator position = contextStack . peek ( ) ; return ( position != null ) && position . isInHead ( ) ; }


Input: { [CODESPLIT] public boolean isLastBodyFunctor ( ) { PositionalTermTraverserImpl . PositionalContextOperator position = contextStack . peek ( ) ; return ( position != null ) && position . isLastBodyFunctor ( ) ; }


Input: { [CODESPLIT] public Term getTerm ( ) { PositionalTermTraverserImpl . PositionalContextOperator position = contextStack . peek ( ) ; return ( position != null ) ? position . getTerm ( ) : null ; }


Input: { [CODESPLIT] public int getPosition ( ) { PositionalTermTraverserImpl . PositionalContextOperator position = contextStack . peek ( ) ; return ( position != null ) ? position . getPosition ( ) : - 1 ; }


Input: { [CODESPLIT] public PositionalContext getParentContext ( ) { PositionalTermTraverserImpl . PositionalContextOperator position = contextStack . peek ( ) ; return ( position != null ) ? position . getParentContext ( ) : null ; }


Input: { [CODESPLIT] protected StackableOperator createHeadOperator ( Functor head , Clause clause ) { return new PositionalContextOperator ( head , - 1 , true , true , false , null , contextStack . peek ( ) ) ; }


Input: { [CODESPLIT] protected StackableOperator createBodyOperator ( Functor bodyFunctor , int pos , Functor [ ] body , Clause clause ) { return new PositionalContextOperator ( bodyFunctor , pos , true , false , pos == ( body . length - 1 ) , null , contextStack . peek ( ) ) ; }


Input: { [CODESPLIT] protected StackableOperator createTermOperator ( Term argument , int pos , Functor functor ) { return new PositionalContextOperator ( argument , pos , false , null , false , null , contextStack . peek ( ) ) ; }


Input: { [CODESPLIT] protected StackableOperator createClauseOperator ( Clause bodyClause , int pos , Clause [ ] body , Predicate predicate ) { return new PositionalContextOperator ( bodyClause , pos , false , false , false , null , contextStack . peek ( ) ) ; }


Input: Sets up the initial context once at the start of a traversal . [CODESPLIT] private void createInitialContext ( Term term ) { if ( ! initialContextCreated ) { PositionalContextOperator initialContext = new PositionalContextOperator ( term , - 1 , false , false , false , null , contextStack . peek ( ) ) ; contextStack . offer ( initialContext ) ; term . setReversable ( initialContext ) ; initialContextCreated = true ; } }


Input: Updates the layout register file with a new set of layout registers . [CODESPLIT] public void updateRegisters ( WAMMemoryLayout layout ) { List < PropertyChangeEvent > changes = delta ( this , layout ) ; regBase = layout . regBase ; regSize = layout . regSize ; heapBase = layout . heapBase ; heapSize = layout . heapSize ; stackBase = layout . stackBase ; stackSize = layout . stackSize ; trailBase = layout . trailBase ; trailSize = layout . trailSize ; pdlBase = layout . pdlBase ; pdlSize = layout . pdlSize ; notifyChanges ( changes ) ; }


Input: Compares the current register file with a new set and creates a list property change notifications for any that have changed value . [CODESPLIT] private List < PropertyChangeEvent > delta ( WAMMemoryLayout oldRegisters , WAMMemoryLayout newRegisters ) { List < PropertyChangeEvent > result = new LinkedList < PropertyChangeEvent > ( ) ; if ( oldRegisters . regBase != newRegisters . regBase ) { result . add ( new PropertyChangeEvent ( this , "regBase" , oldRegisters . regBase , newRegisters . regBase ) ) ; } if ( oldRegisters . regSize != newRegisters . regSize ) { result . add ( new PropertyChangeEvent ( this , "regSize" , oldRegisters . regSize , newRegisters . regSize ) ) ; } if ( oldRegisters . heapBase != newRegisters . heapBase ) { result . add ( new PropertyChangeEvent ( this , "heapBase" , oldRegisters . heapBase , newRegisters . heapBase ) ) ; } if ( oldRegisters . heapSize != newRegisters . heapSize ) { result . add ( new PropertyChangeEvent ( this , "heapSize" , oldRegisters . heapSize , newRegisters . heapSize ) ) ; } if ( oldRegisters . stackBase != newRegisters . stackBase ) { result . add ( new PropertyChangeEvent ( this , "stackBase" , oldRegisters . stackBase , newRegisters . stackBase ) ) ; } if ( oldRegisters . stackSize != newRegisters . stackSize ) { result . add ( new PropertyChangeEvent ( this , "stackSize" , oldRegisters . stackSize , newRegisters . stackSize ) ) ; } if ( oldRegisters . trailBase != newRegisters . trailBase ) { result . add ( new PropertyChangeEvent ( this , "trailBase" , oldRegisters . trailBase , newRegisters . trailBase ) ) ; } if ( oldRegisters . trailSize != newRegisters . trailSize ) { result . add ( new PropertyChangeEvent ( this , "trailSize" , oldRegisters . trailSize , newRegisters . trailSize ) ) ; } if ( oldRegisters . pdlBase != newRegisters . pdlBase ) { result . add ( new PropertyChangeEvent ( this , "pdlBase" , oldRegisters . pdlBase , newRegisters . pdlBase ) ) ; } if ( oldRegisters . pdlSize != newRegisters . pdlSize ) { result . add ( new PropertyChangeEvent ( this , "pdlSize" , oldRegisters . pdlSize , newRegisters . pdlSize ) ) ; } return result ; }


Input: Search up the scope tree to locate the variable s value . The parser has already verified that the variable is defined . [CODESPLIT] public String getValue ( ) { for ( ScopeNode scope = NodeTreeUtils . getParentScope ( this ) ; scope != null ; scope = NodeTreeUtils . getParentScope ( scope ) ) { ExpressionGroupNode value = scope . getVariable ( _name ) ; if ( value == null ) { continue ; } return value . toString ( ) ; } return _name ; // Unable to find the variable's value, return the name for now (helpful for debugging) }


Input: Implementation of the general bi - dircetional search . The search alternated between taking a forward and a reverse step . [CODESPLIT] public SearchNode < O , T > findGoalPath ( ) throws SearchNotExhaustiveException { // Keep running until the queue becomes empty or a goal state is found while ( ! forwardQueue . isEmpty ( ) || ! reverseQueue . isEmpty ( ) ) { // Only run the forward step of the search if the forward queue is not empty if ( ! forwardQueue . isEmpty ( ) ) { // Extract the next node from the forward queue SearchNode < O , T > currentForwardNode = forwardQueue . remove ( ) ; // Remove this node from the forward fringe map as it will soon be replaced by more fringe members forwardFringe . remove ( currentForwardNode . getState ( ) ) ; // Check the reverse fringe against the next forward node for a match. if ( reverseFringe . containsKey ( currentForwardNode . getState ( ) ) ) { // A path from start to the goal has been found. Walk backwards along the reverse path adding all // nodes encountered to the forward path until the goal is reached. return joinBothPaths ( currentForwardNode , reverseFringe . get ( currentForwardNode . getState ( ) ) ) ; } // There was no match so a path to the goal has not been found else { // Get all of the successor states to the current node Queue < SearchNode < O , T > > newStates = new LinkedList < SearchNode < O , T > > ( ) ; currentForwardNode . expandSuccessors ( newStates , false ) ; // Expand all the successors to the current forward node into the buffer to be searched. forwardQueue . addAll ( newStates ) ; // Also add all the successors to the current forward fringe map. for ( SearchNode < O , T > nextSearchNode : newStates ) { forwardFringe . put ( nextSearchNode . getState ( ) , nextSearchNode ) ; } } } // Only run the reverse step of the search if the reverse queue is not empty if ( ! reverseQueue . isEmpty ( ) ) { // Extract the next node from the reverse queue SearchNode < O , T > currentReverseNode = reverseQueue . remove ( ) ; // Remove this node from the reverse fringe set as it will soon be replaced by more fringe members reverseFringe . remove ( currentReverseNode . getState ( ) ) ; // Check the forward fringe against the next reverse node for a match. if ( forwardFringe . containsKey ( currentReverseNode . getState ( ) ) ) { // A path from start to goal has been found. // Walk backwards along the reverse path adding all nodes encountered to the foward path until the // goal is reached. return joinBothPaths ( forwardFringe . get ( currentReverseNode . getState ( ) ) , currentReverseNode ) ; } // There was no match so a path to the goal has not been found else { // Get all of the successor states to the current node (really predecessor state) Queue < SearchNode < O , T > > newStates = new LinkedList < SearchNode < O , T > > ( ) ; currentReverseNode . expandSuccessors ( newStates , false ) ; // Expand all the successors to the current reverse node into the reverse buffer to be searched. reverseQueue . addAll ( newStates ) ; // Add all the successors to the current reverse fringe set for ( SearchNode < O , T > nextSearchNode : newStates ) { reverseFringe . put ( nextSearchNode . getState ( ) , nextSearchNode ) ; } } } } // No goal state was found so return null return null ; }


Input: Once a match has been found between the forward and reverse fringes of the search a path is known to exist from the start to the goal . The path is not complete at this stage because it remains to reverse all of the steps in the backward half of the path and add them to the forward half of the path to produce the complete forward path from start to the goal . [CODESPLIT] private SearchNode < O , T > joinBothPaths ( SearchNode < O , T > forwardPath , SearchNode < O , T > reversePath ) throws SearchNotExhaustiveException { // Check if an alternative path join algorithm has been set and delegate to it if so if ( pathJoiner != null ) { return pathJoiner . joinBothPaths ( forwardPath , reversePath ) ; } // No alternative path join algorithm has been supplied so use this default one else { // Used to hold the current position along the reverse path of search nodes SearchNode < O , T > currentReverseNode = reversePath ; // Used to hold the current position along the forward path of search nodes SearchNode < O , T > currentForwardNode = forwardPath ; // Loop over all nodes in the reverse path checking if the current reverse node is the // goal state to terminate on. while ( ! goalPredicate . evaluate ( currentReverseNode . getState ( ) ) ) { // Create a new forward node from the parent state of the current reverse node, the current reverse // nodes applied operation and cost, and an increment of one to the path depth SearchNode < O , T > reverseParentNode = currentReverseNode . getParent ( ) ; T state = currentReverseNode . getParent ( ) . getState ( ) ; Operator < O > operation = currentReverseNode . getAppliedOp ( ) ; float cost = currentReverseNode . getPathCost ( ) - reverseParentNode . getPathCost ( ) ; currentForwardNode = currentForwardNode . makeNode ( new Successor < O > ( state , operation , cost ) ) ; // Move one step up the reverse path currentReverseNode = reverseParentNode ; } // Return the last forward search node found return currentForwardNode ; } }


Input: { @inheritDoc } [CODESPLIT] public Variable transform ( Variable variable ) { StackVariable stackVar = varMapping . get ( variable ) ; // Check if a stack variable for the variable has not been created yet, and if so create a new stack variable, // setting the clause that it is in as its binding context supplier. if ( stackVar == null ) { stackVar = new StackVariable ( variable . getName ( ) , null , variable . isAnonymous ( ) , offset ++ , context ) ; varMapping . put ( variable , stackVar ) ; } return stackVar ; }


Input: Gets the element from the list at the specified index . If the indexes block is not currently cached then a call is made to the { @link #getBlock } method to fetch it . [CODESPLIT] public T get ( int index ) { /*log.fine("public T get(int index): called");*/ /*log.fine("index = " + index);*/ // Turn the absolute index into a block and offset. int block = index / blockSize ; int offset = index % blockSize ; /*log.fine("block = " + block);*/ /*log.fine("offset = " + offset);*/ // Check if the desired block is already cached. List < T > blockList = blockMap . get ( block ) ; // Fetch the block if it is not already cached and cache it. if ( blockList == null ) { blockList = cacheBlock ( block ) ; } // Get the element from the offset within the cached block. return blockList . get ( offset ) ; }


Input: Fetches and caches the specified block . [CODESPLIT] public List < T > cacheBlock ( int block ) { /*log.fine("public List<T> cacheBlock(int block): called");*/ // Get the new block. List < T > blockList = getBlock ( block * blockSize , blockSize ) ; // Cache it. blockMap . put ( block , blockList ) ; /*log.fine("Cached block " + block + " with list of size " + blockList.size());*/ return blockList ; }


Input: Static factory method that locates an existing instance or creates a new property reader for a named resource . [CODESPLIT] public static synchronized Properties getProperties ( String resourceName ) { /*log.fine("public static synchronized Properties getProperties(String resourceName): called");*/ /*log.fine("resourceName = " + resourceName);*/ // Try to find an already created singleton property reader for the resource PropertyReaderBase propertyReader = ( PropertyReaderBase ) propertyReaders . get ( resourceName ) ; if ( propertyReader != null ) { /*log.fine("found property reader in the cache for resource: " + resourceName);*/ return propertyReader . getProperties ( ) ; } /*log.fine("did not find property reader in the cache for resource: " + resourceName);*/ // There is not already a singleton for the named resource so create a new one propertyReader = new DefaultPropertyReader ( resourceName ) ; // Keep the newly created singleton for next time propertyReaders . put ( resourceName , propertyReader ) ; return propertyReader . getProperties ( ) ; }


Input: Specifies the throttling rate in operations per second . [CODESPLIT] public void setRate ( float hertz ) { // Pass the rate unaltered down to the base implementation, for the check method. super . setRate ( hertz ) ; // Log base 10 over 2 is used here to get a feel for what power of 100 the total rate is. // As the total rate goes up the powers of 100 the batch size goes up by powers of 100 to keep the // throttle rate in the range 1 to 100. int x = ( int ) ( Math . log10 ( hertz ) / 2 ) ; batchSize = ( int ) Math . pow ( 100 , x ) ; float throttleRate = hertz / batchSize ; // Reset the call count. callCount = 0 ; // Set the sleep throttle wrapped implementation at a rate within its abilities. batchRateThrottle . setRate ( throttleRate ) ; }


Input: Reads some number of bytes from the input stream and stores them into the buffer array b . [CODESPLIT] public int read ( byte [ ] b ) throws IOException { try { ByteBlock block = source . read ( b ) ; System . arraycopy ( block . data , 0 , b , 0 , block . count ) ; return block . count ; } catch ( RemoteException e ) { throw new IOException ( "There was a Remote Exception." , e ) ; } }


Input: Reads up to len bytes of data from the input stream into an array of bytes . [CODESPLIT] public int read ( byte [ ] b , int off , int len ) throws IOException { try { ByteBlock block = source . read ( b , off , len ) ; System . arraycopy ( block . data , off , b , off , len ) ; return block . count ; } catch ( RemoteException e ) { throw new IOException ( "There was a Remote Exception." , e ) ; } }


Input: Skips over and discards n bytes of data from this input stream . [CODESPLIT] public long skip ( long n ) throws IOException { try { return source . skip ( n ) ; } catch ( RemoteException e ) { throw new IOException ( "There was a Remote Exception." , e ) ; } }


Input: { [CODESPLIT] public SizeableLinkedList < WAMInstruction > compileBodyArguments ( Functor functor , boolean isFirstBody , FunctorName clauseName , int bodyNumber ) { SizeableLinkedList < WAMInstruction > result = new SizeableLinkedList < WAMInstruction > ( ) ; SizeableLinkedList < WAMInstruction > instructions ; // Invent some unique names for choice points within a clause. clauseName = new FunctorName ( clauseName . getName ( ) + "_" + bodyNumber , 0 ) ; FunctorName choicePointRootName = new FunctorName ( clauseName . getName ( ) + "_ilc" , 0 ) ; FunctorName continuationPointName = new FunctorName ( clauseName . getName ( ) + "_cnt" , 0 ) ; // Labels the continuation point to jump to, when a choice point succeeds. WAMLabel continueLabel = new WAMLabel ( continuationPointName , 0 ) ; // Do a loop over the children of this disjunction, and any child disjunctions encountered. This could be a // search? or just recursive exploration. I think it will need to be a DFS. List < Term > expressions = new ArrayList < Term > ( ) ; gatherDisjunctions ( ( Disjunction ) functor , expressions ) ; for ( int i = 0 ; i < expressions . size ( ) ; i ++ ) { Functor expression = ( Functor ) expressions . get ( i ) ; boolean isFirst = i == 0 ; boolean isLast = i == ( expressions . size ( ) - 1 ) ; // Labels the entry point to each choice point. WAMLabel entryLabel = new WAMLabel ( choicePointRootName , i ) ; // Label for the entry point to the next choice point, to backtrack to. WAMLabel retryLabel = new WAMLabel ( choicePointRootName , i + 1 ) ; if ( isFirst && ! isLast ) { // try me else. result . add ( new WAMInstruction ( entryLabel , WAMInstruction . WAMInstructionSet . TryMeElse , retryLabel ) ) ; } else if ( ! isFirst && ! isLast ) { // retry me else. result . add ( new WAMInstruction ( entryLabel , WAMInstruction . WAMInstructionSet . RetryMeElse , retryLabel ) ) ; } else if ( isLast ) { // trust me. result . add ( new WAMInstruction ( entryLabel , WAMInstruction . WAMInstructionSet . TrustMe ) ) ; } Integer permVarsRemaining = ( Integer ) defaultBuiltIn . getSymbolTable ( ) . get ( expression . getSymbolKey ( ) , SYMKEY_PERM_VARS_REMAINING ) ; // Select a non-default built-in implementation to compile the functor with, if it is a built-in. BuiltIn builtIn ; if ( expression instanceof BuiltIn ) { builtIn = ( BuiltIn ) expression ; } else { builtIn = defaultBuiltIn ; } // The 'isFirstBody' parameter is only set to true, when this is the first functor of a rule. instructions = builtIn . compileBodyArguments ( expression , false , clauseName , i ) ; result . addAll ( instructions ) ; // Call the body. The number of permanent variables remaining is specified for environment trimming. instructions = builtIn . compileBodyCall ( expression , false , false , false , 0 /*permVarsRemaining*/ ) ; result . addAll ( instructions ) ; // Proceed if this disjunctive branch completes successfully. This does not need to be done for the last // branch, as the continuation point will come immediately after. if ( ! isLast ) { result . add ( new WAMInstruction ( null , WAMInstruction . WAMInstructionSet . Continue , continueLabel ) ) ; } } result . add ( new WAMInstruction ( continueLabel , WAMInstruction . WAMInstructionSet . NoOp ) ) ; return result ; }


Input: { [CODESPLIT] public SizeableLinkedList < WAMInstruction > compileBodyCall ( Functor expression , boolean isFirstBody , boolean isLastBody , boolean chainRule , int permVarsRemaining ) { return new SizeableLinkedList < WAMInstruction > ( ) ; }


Input: Gathers the functors to compile as a sequence of choice points . These exist as the arguments to disjunctions recursively below the supplied disjunction . They are flattened into a list by performing a left - to - right depth first traversal over the disjunctions and adding their arguments into a list . [CODESPLIT] private void gatherDisjunctions ( Disjunction disjunction , List < Term > expressions ) { // Left argument. gatherDisjunctionsExploreArgument ( disjunction . getArguments ( ) [ 0 ] , expressions ) ; // Right argument. gatherDisjunctionsExploreArgument ( disjunction . getArguments ( ) [ 1 ] , expressions ) ; }


Input: Explores one argument of a disjunction as part of the { @link #gatherDisjunctions ( Disjunction List ) } function . [CODESPLIT] private void gatherDisjunctionsExploreArgument ( Term term , List < Term > expressions ) { if ( term instanceof Disjunction ) { gatherDisjunctions ( ( Disjunction ) term , expressions ) ; } else { expressions . add ( term ) ; } }


Input: { [CODESPLIT] public boolean proofStep ( ResolutionState state ) { Functor isOp = state . getGoalStack ( ) . poll ( ) . getFunctor ( ) ; // Evaluate both sides of the comparison, checking that they are fully instantiated numbers. NumericType n1 = BuiltInUtils . evaluateAsNumeric ( isOp . getArgument ( 0 ) ) ; NumericType n2 = BuiltInUtils . evaluateAsNumeric ( isOp . getArgument ( 1 ) ) ; // Evaluate the comparison operator. return evaluate ( n1 , n2 ) ; }


Input: { [CODESPLIT] public void visit ( Clause clause ) { if ( traverser . isEnteringContext ( ) ) { initializePrinters ( ) ; } else if ( traverser . isLeavingContext ( ) ) { printTable ( ) ; } super . visit ( clause ) ; }


Input: Returns the first ( lowest ) key currently in this priority map . [CODESPLIT] public K pollKey ( ) { // Scan through the buckets until a non empty one is found. int i = 0 ; for ( ; i < n ; i ++ ) { if ( ! maps [ i ] . isEmpty ( ) ) { break ; } // If all maps are empty then the whole data structure is emtpy. if ( i == ( n - 1 ) ) { return null ; } } return maps [ i ] . keySet ( ) . iterator ( ) . next ( ) ; }


Input: Returns the value of the first ( lowest ) key currently in this priority map . [CODESPLIT] public V pollValue ( ) { K lowestKey = pollKey ( ) ; if ( lowestKey == null ) { return null ; } else { return maps [ p . apply ( lowestKey ) ] . get ( lowestKey ) ; } }


Input: Extracts an int from an array of bytes . [CODESPLIT] public static int getIntFromBytes ( byte [ ] buf , int offset ) { int result = 0 ; result += buf [ offset ++ ] & 0xFF ; result += ( ( buf [ offset ++ ] & 0xFF ) << 8 ) ; result += ( ( buf [ offset ++ ] & 0xFF ) << 16 ) ; result += ( ( buf [ offset ] ) << 24 ) ; return result ; }


Input: Outputs an int into a byte array . [CODESPLIT] public static void writeIntToByteArray ( byte [ ] buf , int offset , int value ) { buf [ offset ++ ] = ( byte ) ( value & 0x000000ff ) ; buf [ offset ++ ] = ( byte ) ( ( value & 0x0000ff00 ) >> 8 ) ; buf [ offset ++ ] = ( byte ) ( ( value & 0x00ff0000 ) >> 16 ) ; buf [ offset ] = ( byte ) ( ( value & 0xff000000 ) >> 24 ) ; }


Input: Outputs an int into a byte array copying only the bottom 24 bits of the integer . The top sign bit is lost by this operation so this only works on positive ints below 2^24 . [CODESPLIT] public static void write24BitIntToByteArray ( byte [ ] buf , int offset , int value ) { buf [ offset ++ ] = ( byte ) ( value & 0x000000ff ) ; buf [ offset ++ ] = ( byte ) ( ( value & 0x0000ff00 ) >> 8 ) ; buf [ offset ] = ( byte ) ( ( value & 0x00ff0000 ) >> 16 ) ; }


Input: 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 . [CODESPLIT] 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 ; }


Input: Extracts a short from an array of bytes . [CODESPLIT] public static short getShortFromBytes ( byte [ ] buf , int offset ) { short result = 0 ; result += buf [ offset ++ ] & 0xFF ; result += ( ( buf [ offset ] ) << 8 ) ; return result ; }


Input: Outputs a short into a byte array . [CODESPLIT] public static void writeShortToByteArray ( byte [ ] buf , int offset , short value ) { buf [ offset ++ ] = ( byte ) ( value & 0x000000ff ) ; buf [ offset ] = ( byte ) ( ( value & 0x0000ff00 ) >> 8 ) ; }


Input: { [CODESPLIT] public SizeableLinkedList < WAMInstruction > compileBodyCall ( Functor expression , boolean isFirstBody , boolean isLastBody , boolean chainRule , int permVarsRemaining ) { SizeableLinkedList < WAMInstruction > instructions = new SizeableLinkedList < WAMInstruction > ( ) ; instructions . add ( new WAMInstruction ( WAMInstruction . WAMInstructionSet . Execute , new FunctorName ( "__fail__" , 0 ) ) ) ; return instructions ; }


Input: Provides an implementation of the { @link BoundProperty } interface to extract the cost as the bound property . [CODESPLIT] public float getBoundProperty ( SearchNode < O , T > searchNode ) { return ( ( HeuristicSearchNode < O , T > ) searchNode ) . getF ( ) ; }


Input: Returns the state obtained by applying the specified operation . If the operation is not valid then this should return null . [CODESPLIT] 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 ( ) ) ; }


Input: 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 . [CODESPLIT] 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 ( ) ) ; } }


Input: Returns the integer id of the attribute . [CODESPLIT] 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 ; } }


Input: Gets the object value of a object attribute . [CODESPLIT] 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 ; } }


Input: 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 . [CODESPLIT] 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 ; }


Input: Converts a string listing sub - strings seperated by a delimeter into an array of strings . [CODESPLIT] 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 ( ) ] ) ; }


Input: Converts an array of strings into a delimeter seperated string . [CODESPLIT] 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 ; }


Input: Converts a string to camel case . [CODESPLIT] 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 ; }


Input: Converts string between various case forms such as camel case snake case or kebab case . [CODESPLIT] 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 ( ) ; }


Input: ---------------------------------------------------------------------------------------------------------------- [CODESPLIT] public List < MicrodataItem > getItems ( String type ) { List < WebElement > elements = driver . findElements ( byItemType ( newUrl ( type ) ) ) ; return Lists . transform ( elements , new Function < WebElement , MicrodataItem > ( ) { public MicrodataItem apply ( WebElement element ) { return new SeleniumMicrodataItem ( driver , element ) ; } } ) ; }


Input: ---------------------------------------------------------------------------------------------------------------- [CODESPLIT] public < T > T unwrap ( Class < T > type ) { checkArgument ( WebDriver . class . equals ( type ) , "Cannot unwrap to: %s" , type ) ; return type . cast ( driver ) ; }


Input: Provides a string containing information about the configured logging set up . [CODESPLIT] 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 ( ) ; }


Input: Lists information about logging handlers . [CODESPLIT] 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 ; }


Input: ---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void setValueWhenHiddenControlThrowsException ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( "" + "<form name='f'>" + "<input type='hidden' name='c' value='x'/>" + "</form>" + "" ) ) ; Control control = newBrowser ( ) . get ( url ( server ( ) ) ) . getForm ( "f" ) . getControl ( "c" ) ; thrown ( ) . expect ( IllegalArgumentException . class ) ; thrown ( ) . expectMessage ( "Cannot set hidden control value: c" ) ; control . setValue ( "y" ) ; }


Input: ---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void unwrapWithUnknownTypeThrowsException ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( "" + "<form name='f'>" + "<input type='text' name='x'/>" + "</form>" + "" ) ) ; Control control = newBrowser ( ) . get ( url ( server ( ) ) ) . getForm ( "f" ) . getControl ( "x" ) ; thrown ( ) . expect ( IllegalArgumentException . class ) ; thrown ( ) . expectMessage ( "Cannot unwrap to: class java.lang.Void" ) ; control . unwrap ( Void . class ) ; }


Input: { [CODESPLIT] public void visit ( Term term ) { if ( traverser . isEnteringContext ( ) ) { enterTerm ( term ) ; } else if ( traverser . isLeavingContext ( ) ) { leaveTerm ( term ) ; term . setTermTraverser ( null ) ; } }


Input: { [CODESPLIT] public void visit ( Functor functor ) { if ( traverser . isEnteringContext ( ) ) { enterFunctor ( functor ) ; } else if ( traverser . isLeavingContext ( ) ) { leaveFunctor ( functor ) ; functor . setTermTraverser ( null ) ; } }


Input: { [CODESPLIT] public void visit ( Variable variable ) { if ( traverser . isEnteringContext ( ) ) { enterVariable ( variable ) ; } else if ( traverser . isLeavingContext ( ) ) { leaveVariable ( variable ) ; variable . setTermTraverser ( null ) ; } }


Input: { [CODESPLIT] public void visit ( Predicate predicate ) { if ( traverser . isEnteringContext ( ) ) { enterPredicate ( predicate ) ; } else if ( traverser . isLeavingContext ( ) ) { leavePredicate ( predicate ) ; predicate . setTermTraverser ( null ) ; } }


Input: { [CODESPLIT] public void visit ( Clause clause ) { if ( traverser . isEnteringContext ( ) ) { enterClause ( clause ) ; } else if ( traverser . isLeavingContext ( ) ) { leaveClause ( clause ) ; clause . setTermTraverser ( null ) ; } }


Input: { [CODESPLIT] public void visit ( IntegerType literal ) { if ( traverser . isEnteringContext ( ) ) { enterIntLiteral ( literal ) ; } else if ( traverser . isLeavingContext ( ) ) { leaveIntLiteral ( literal ) ; literal . setTermTraverser ( null ) ; } }


Input: { [CODESPLIT] public void visit ( LiteralType literal ) { if ( traverser . isEnteringContext ( ) ) { enterLiteral ( literal ) ; } else if ( traverser . isLeavingContext ( ) ) { leaveLiteral ( literal ) ; literal . setTermTraverser ( null ) ; } }


Input: Looks up the offset of the start of the code for the named functor . [CODESPLIT] 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 ; }


Input: { [CODESPLIT] public void reserveReferenceToLabel ( int labelName , int offset ) { // Create call point with label name if it does not already exist. WAMReservedLabel label = ( WAMReservedLabel ) symbolTable . get ( labelName , SYMKEY_CALLPOINTS ) ; if ( label == null ) { label = new WAMReservedLabel ( labelName ) ; symbolTable . put ( labelName , SYMKEY_CALLPOINTS , label ) ; } // Add to the mapping from the label to referenced from addresses to fill in later. label . referenceList . add ( offset ) ; }


Input: { [CODESPLIT] public void resolveLabelPoint ( int labelName , int address ) { // Create the label with resolved address, if it does not already exist. WAMReservedLabel label = ( WAMReservedLabel ) symbolTable . get ( labelName , SYMKEY_CALLPOINTS ) ; if ( label == null ) { label = new WAMReservedLabel ( labelName ) ; symbolTable . put ( labelName , SYMKEY_CALLPOINTS , label ) ; } label . entryPoint = address ; // Fill in all references to the label with the correct value. This does nothing if the label was just created. for ( Integer offset : label . referenceList ) { emmitCode ( offset , label . entryPoint ) ; } // Keep a reverse lookup from address to label name. reverseTable . put ( address , labelName ) ; }


Input: Records the offset of the start of the code for the named functor . [CODESPLIT] 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 ; }


Input: Records the id of an internal function for the named functor . The method name uses the word address but this is not really accurate the address field is used to hold an id of the internal function to be invoked . This method differs from { @link #setCodeAddress ( int int int ) } as it does not set the reverse mapping from the address to the functor name since an address is not really being used . [CODESPLIT] protected WAMCallPoint setInternalCodeAddress ( int functorName , int id ) { WAMCallPoint entry = new WAMCallPoint ( id , 0 , functorName ) ; symbolTable . put ( functorName , SYMKEY_CALLPOINTS , entry ) ; return entry ; }


Input: 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 . [CODESPLIT] 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 ; }


Input: Returns the long id of the attribute . [CODESPLIT] 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 ; }


Input: Sets the integer id of the attribute . If the attribute class is finalized this will change the value of this attribute to that of the matched id or raise an exception if no matching id exists . If the attribute class is unfinalized this will change the id value of this attribute within the attribute class to the new id provided that the id has not already been assigned to another attribute value . If it has been assigned to another attribute value then an exception is raised . [CODESPLIT] public void setId ( long id ) throws IllegalArgumentException { // Find the category for this hierarchy attribute value. Tree < CategoryNode > category = attributeClass . lookup . get ( value ) ; // Extract the id. long existingId = category . getElement ( ) . id ; // Do nothing if the new id matches the existing one. if ( id == existingId ) { return ; } // The type is finalized. if ( attributeClass . finalized ) { // Raise an illegal argument exception if the id is not known. HierarchyAttribute newValue = attributeClass . getAttributeFromId ( id ) ; // Otherwise, change the value of this attribute to that of the new id. this . value = newValue . value ; } // The type is unfinalized. else { // Check if another instance of the type already has the id and raise an exception if so. Tree < CategoryNode > existingNode = attributeClass . idMap . get ( id ) ; if ( existingNode != null ) { throw new IllegalArgumentException ( "The id value, " + id + ", cannot be set because another instance of this type with that " + "id already exists." ) ; } // Assign it to this instance if the type is unfinalized. Also removing the old id mapping from the id // map and replacing it with the new one. category . getElement ( ) . id = id ; attributeClass . idMap . remove ( existingId ) ; attributeClass . idMap . put ( id , category ) ; } }


Input: Gets the label value at the named level of the hierarchy . [CODESPLIT] 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 ) ; }


Input: Gets the label value at the last level of the hierarchy . [CODESPLIT] public String getLastValue ( ) { List < String > pathValue = getPathValue ( ) ; return pathValue . get ( pathValue . size ( ) - 1 ) ; }


Input: Serialized a hierarchy attribute . [CODESPLIT] 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 ( ) ) ; }


Input: Deserializes a hierarchy attribute . [CODESPLIT] 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());*/ } }


Input: Returns heuristic evaluation of an eight puzzle board position as the manhattan distance of all tiles from their correct positions . [CODESPLIT] 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 ' ' : { oldX = emptyX - 1 ; break ; } case ' ' : { oldX = emptyX + 1 ; break ; } case ' ' : { oldY = emptyY - 1 ; break ; } case ' ' : { 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 ' ' : case ' ' : { // 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 ' ' : case ' ' : { // 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 ) ; } }


Input: Associates the specified value with the specified key in this map . [CODESPLIT] public V put ( K key , V value ) { // Remove any existing matching key from the data V removedObject = remove ( key ) ; // Insert the data into the map. dataMap . put ( key , value ) ; // If the key is fresh, enqueue it. if ( removedObject != null ) { keys . offer ( key ) ; } // Return the replaced value if there was one return removedObject ; }


Input: Returns <tt > true< / tt > if this map contains a mapping for the specified coordinates . [CODESPLIT] public boolean containsKey ( Long x , Long y ) { // Extract the region containing the coordinates from the hash table Bucket region = ( Bucket ) regions . get ( new Coordinates ( div ( x , bucketSize ) , div ( y , bucketSize ) ) ) ; // Check if the whole region is empty if ( region == null ) { return false ; } // Check if the coordinates within the region contain data return ( region . array [ mod ( x , bucketSize ) ] [ mod ( y , bucketSize ) ] != null ) ; }


Input: Associates the specified value with the specified coordinate in this map ( optional operation ) . If the map previously contained a mapping for this coordinate the old value is replaced . [CODESPLIT] public E put ( Long x , Long y , E value ) { // Check that the value is not null as this data structure does not allow nulls if ( value == null ) { throw new IllegalArgumentException ( "Null values not allowed in HashMapXY data structure." ) ; } // Extract the region containing the coordinates from the hash table Bucket < E > region = ( Bucket < E > ) regions . get ( new Coordinates ( div ( x , bucketSize ) , div ( y , bucketSize ) ) ) ; // Check if the region does not exist yet and create it if so if ( region == null ) { region = new Bucket < E > ( bucketSize ) ; regions . put ( new Coordinates ( div ( x , bucketSize ) , div ( y , bucketSize ) ) , region ) ; } // Take a reference to the old value if there is one E old = region . array [ mod ( x , bucketSize ) ] [ mod ( y , bucketSize ) ] ; // Insert the new value into the bucket region . array [ mod ( x , bucketSize ) ] [ mod ( y , bucketSize ) ] = value ; // Increment the bucket and whole data structure item counts to reflect the true size size ++ ; region . itemCount ++ ; // Return the replaced value return old ; }


Input: Removes the mapping for this coordinate from this map if present ( optional operation ) . [CODESPLIT] public E remove ( Long x , Long y ) { // Extract the region containing the coordinates from the hash table Bucket < E > region = ( Bucket < E > ) regions . get ( new Coordinates ( div ( x , bucketSize ) , div ( y , bucketSize ) ) ) ; // Check if the whole region is empty if ( region == null ) { // Return null as nothing to remove return null ; } // Get the coordinates within the region E removed = ( region . array [ mod ( x , bucketSize ) ] [ mod ( y , bucketSize ) ] ) ; // Clear the coordinate within the region region . array [ mod ( x , bucketSize ) ] [ mod ( y , bucketSize ) ] = null ; // Decrement the bucket and whole data strucutre item counts to reflect the true size size -- ; region . itemCount -- ; // Return the removed data item return removed ; }


Input: 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 . [CODESPLIT] private int mod ( long c , int bucketSize ) { return ( int ) ( ( c < 0 ) ? ( ( bucketSize + ( c % bucketSize ) ) % bucketSize ) : ( c % bucketSize ) ) ; }


Input: Adds another user readable error message to this exception . [CODESPLIT] 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 ) ) ; }


Input: 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 . [CODESPLIT] 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" ) ) ; }


Input:
Writes a string of characters to the filtered writer . Any newline characters \ n are replaced with an HTML break tag &lt ; br&gt ; . [CODESPLIT] 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 ( ) ) ; }


Input:
/ * Perform any handshaking processing . <P > If a SelectionKey is passed register for selectable operations . <P > In the blocking case our caller will keep calling us until we finish the handshake . Our reads / writes will block as expected . <P > In the non - blocking case we just received the selection notification that this channel is ready for whatever the operation is so give it a try . <P > return : true when handshake is done . false while handshake is in progress [CODESPLIT] boolean doHandshake ( SelectionKey sk ) throws IOException { SSLEngineResult result ; if ( initialHSComplete ) { return true ; } /*
     * Flush out the outgoing buffer, if there's anything left in
	 * it.
	 */ if ( outNetBB . hasRemaining ( ) ) { if ( ! tryFlush ( outNetBB ) ) { return false ; } // See if we need to switch from write to read mode. switch ( initialHSStatus ) { /*
         * Is this the last buffer?
	     */ case FINISHED : initialHSComplete = true ; // Fall-through to reregister need for a Read. case NEED_UNWRAP : if ( sk != null ) { sk . interestOps ( SelectionKey . OP_READ ) ; } break ; } return initialHSComplete ; } switch ( initialHSStatus ) { case NEED_UNWRAP : if ( sc . read ( inNetBB ) == - 1 ) { sslEngine . closeInbound ( ) ; return initialHSComplete ; } needIO : while ( initialHSStatus == HandshakeStatus . NEED_UNWRAP ) { /*
         * Don't need to resize requestBB, since no app data should
		 * be generated here.
		 */ inNetBB . flip ( ) ; result = sslEngine . unwrap ( inNetBB , requestBB ) ; inNetBB . compact ( ) ; initialHSStatus = result . getHandshakeStatus ( ) ; switch ( result . getStatus ( ) ) { case OK : switch ( initialHSStatus ) { case NOT_HANDSHAKING : throw new IOException ( "Not handshaking during initial handshake" ) ; case NEED_TASK : initialHSStatus = doTasks ( ) ; break ; case FINISHED : initialHSComplete = true ; break needIO ; } break ; case BUFFER_UNDERFLOW : /*
             * Need to go reread the Channel for more data.
		     */ if ( sk != null ) { sk . interestOps ( SelectionKey . OP_READ ) ; } break needIO ; default : // BUFFER_OVERFLOW/CLOSED: throw new IOException ( "Received" + result . getStatus ( ) + "during initial handshaking" ) ; } } // "needIO" block. /*
         * Just transitioned from read to write.
	     */ if ( initialHSStatus != HandshakeStatus . NEED_WRAP ) { break ; } // Fall through and fill the write buffers. case NEED_WRAP : /*
         * The flush above guarantees the out buffer to be empty
	     */ outNetBB . clear ( ) ; result = sslEngine . wrap ( hsBB , outNetBB ) ; outNetBB . flip ( ) ; initialHSStatus = result . getHandshakeStatus ( ) ; switch ( result . getStatus ( ) ) { case OK : if ( initialHSStatus == HandshakeStatus . NEED_TASK ) { initialHSStatus = doTasks ( ) ; } if ( sk != null ) { sk . interestOps ( SelectionKey . OP_WRITE ) ; } break ; default : // BUFFER_OVERFLOW/BUFFER_UNDERFLOW/CLOSED: throw new IOException ( "Received" + result . getStatus ( ) + "during initial handshaking" ) ; } break ; default : // NOT_HANDSHAKING/NEED_TASK/FINISHED throw new RuntimeException ( "Invalid Handshaking State" + initialHSStatus ) ; } // switch return initialHSComplete ; }


Input:
/ * Read the channel for more information then unwrap the ( hopefully application ) data we get . <P > If we run out of data we ll return to our caller ( possibly using a Selector ) to get notification that more is available . <P > Each call to this method will perform at most one underlying read () . [CODESPLIT] ByteBuffer read ( ) throws IOException { SSLEngineResult result ; if ( ! initialHSComplete ) { throw new IllegalStateException ( ) ; } int pos = requestBB . position ( ) ; if ( sc . read ( inNetBB ) == - 1 ) { sslEngine . closeInbound ( ) ; // probably throws exception throw new EOFException ( ) ; } do { resizeRequestBB ( inNetBB . remaining ( ) ) ; // guarantees enough room for unwrap inNetBB . flip ( ) ; result = sslEngine . unwrap ( inNetBB , requestBB ) ; inNetBB . compact ( ) ; /*
         * Could check here for a renegotation, but we're only
	     * doing a simple read/write, and won't have enough state
	     * transitions to do a complete handshake, so ignore that
	     * possibility.
	     */ switch ( result . getStatus ( ) ) { case BUFFER_UNDERFLOW : case OK : if ( result . getHandshakeStatus ( ) == HandshakeStatus . NEED_TASK ) { doTasks ( ) ; } break ; default : throw new IOException ( "sslEngine error during data read: " + result . getStatus ( ) ) ; } } while ( ( inNetBB . position ( ) != 0 ) && result . getStatus ( ) != Status . BUFFER_UNDERFLOW ) ; int readLength = requestBB . position ( ) - pos ; ByteBuffer byteBuffer = ByteBuffer . allocate ( readLength ) ; byteBuffer . put ( BytesUtil . subBytes ( requestBB . array ( ) , pos , readLength ) ) ; return byteBuffer ; }


Input:
/ * Try to flush out any existing outbound data then try to wrap anything new contained in the src buffer . <P > Return the number of bytes actually consumed from the buffer but the data may actually be still sitting in the output buffer waiting to be flushed . [CODESPLIT] private int doWrite ( ByteBuffer src ) throws IOException { int retValue = 0 ; if ( outNetBB . hasRemaining ( ) && ! tryFlush ( outNetBB ) ) { return retValue ; } /*
     * The data buffer is empty, we can reuse the entire buffer.
	 */ outNetBB . clear ( ) ; SSLEngineResult result = sslEngine . wrap ( src , outNetBB ) ; retValue = result . bytesConsumed ( ) ; outNetBB . flip ( ) ; switch ( result . getStatus ( ) ) { case OK : if ( result . getHandshakeStatus ( ) == HandshakeStatus . NEED_TASK ) { doTasks ( ) ; } break ; default : throw new IOException ( "sslEngine error during data write: " + result . getStatus ( ) ) ; } /*
     * Try to flush the data, regardless of whether or not
	 * it's been selected.  Odds of a write buffer being full
	 * is less than a read buffer being empty.
	 */ tryFlush ( src ) ; if ( outNetBB . hasRemaining ( ) ) { tryFlush ( outNetBB ) ; } return retValue ; }


Input: / * Flush any remaining data . <P > Return true when the fileChannelBB and outNetBB are empty . [CODESPLIT] boolean dataFlush ( ) throws IOException { boolean fileFlushed = true ; if ( ( fileChannelBB != null ) && fileChannelBB . hasRemaining ( ) ) { doWrite ( fileChannelBB ) ; fileFlushed = ! fileChannelBB . hasRemaining ( ) ; } else if ( outNetBB . hasRemaining ( ) ) { tryFlush ( outNetBB ) ; } return ( fileFlushed && ! outNetBB . hasRemaining ( ) ) ; }


Input:
/ * Begin the shutdown process . <P > Close out the SSLEngine if not already done so then wrap our outgoing close_notify message and try to send it on . <P > Return true when we re done passing the shutdown messsages . [CODESPLIT] boolean shutdown ( ) throws IOException { if ( ! shutdown ) { sslEngine . closeOutbound ( ) ; shutdown = true ; } if ( outNetBB . hasRemaining ( ) && tryFlush ( outNetBB ) ) { return false ; } /*
     * By RFC 2616, we can "fire and forget" our close_notify
	 * message, so that's what we'll do here.
	 */ outNetBB . clear ( ) ; SSLEngineResult result = sslEngine . wrap ( hsBB , outNetBB ) ; if ( result . getStatus ( ) != Status . CLOSED ) { throw new SSLException ( "Improper close state" ) ; } outNetBB . flip ( ) ; /*
     * We won't wait for a select here, but if this doesn't work,
	 * we'll cycle back through on the next select.
	 */ if ( outNetBB . hasRemaining ( ) ) { tryFlush ( outNetBB ) ; } return ( ! outNetBB . hasRemaining ( ) && ( result . getHandshakeStatus ( ) != HandshakeStatus . NEED_WRAP ) ) ; }


Input: { [CODESPLIT] public Iterator < Operator < Term > > traverse ( Predicate predicate , boolean reverse ) { /*log.fine("Traversing predicate " + predicate.toString());*/ Clause [ ] body = predicate . getBody ( ) ; Queue < Operator < Term > > queue = ( ! reverse ) ? new StackQueue < Operator < Term > > ( ) : new LinkedList < Operator < Term > > ( ) ; // For the predicate bodies. if ( body != null ) { for ( int i = leftToRightPredicateBodies ? 0 : ( body . length - 1 ) ; leftToRightPredicateBodies ? ( i < body . length ) : ( i >= 0 ) ; i = i + ( leftToRightPredicateBodies ? 1 : - 1 ) ) { Clause bodyClause = body [ i ] ; bodyClause . setReversable ( createClauseOperator ( bodyClause , i , body , predicate ) ) ; bodyClause . setTermTraverser ( this ) ; queue . offer ( bodyClause ) ; } } return queue . iterator ( ) ; }


Input: { [CODESPLIT] public Iterator < Operator < Term > > traverse ( Clause clause , boolean reverse ) { /*log.fine("Traversing clause " + clause.toString());*/ Functor head = clause . getHead ( ) ; Functor [ ] body = clause . getBody ( ) ; Queue < Operator < Term > > queue = ( ! reverse ) ? new StackQueue < Operator < Term > > ( ) : new LinkedList < Operator < Term > > ( ) ; // For the head functor, set the top-level flag, set in head context. if ( head != null ) { head . setReversable ( createHeadOperator ( head , clause ) ) ; head . setTermTraverser ( this ) ; queue . offer ( head ) ; } // For the body functors, set the top-level flag, clear in head context. if ( body != null ) { for ( int i = leftToRightClauseBodies ? 0 : ( body . length - 1 ) ; leftToRightClauseBodies ? ( i < body . length ) : ( i >= 0 ) ; i = i + ( leftToRightClauseBodies ? 1 : - 1 ) ) { Functor bodyFunctor = body [ i ] ; bodyFunctor . setReversable ( createBodyOperator ( bodyFunctor , i , body , clause ) ) ; bodyFunctor . setTermTraverser ( this ) ; queue . offer ( bodyFunctor ) ; } } return queue . iterator ( ) ; }


Input: { [CODESPLIT] public Iterator < Operator < Term > > traverse ( Functor functor , boolean reverse ) { /*log.fine("Traversing functor " + functor.toString());*/ Queue < Operator < Term >> queue = ( ! reverse ) ? new StackQueue < Operator < Term > > ( ) : new LinkedList < Operator < Term > > ( ) ; Term [ ] arguments = functor . getArguments ( ) ; // For a top-level functor clear top-level flag, so that child functors are not taken as top-level. if ( arguments != null ) { for ( int i = leftToRightFunctorArgs ? 0 : ( arguments . length - 1 ) ; leftToRightFunctorArgs ? ( i < arguments . length ) : ( i >= 0 ) ; i = i + ( leftToRightFunctorArgs ? 1 : - 1 ) ) { Term argument = arguments [ i ] ; argument . setReversable ( createTermOperator ( argument , i , functor ) ) ; argument . setTermTraverser ( this ) ; queue . offer ( argument ) ; } } return queue . iterator ( ) ; }


Input: { @inheritDoc } [CODESPLIT] protected void enterFunctor ( Functor functor ) { if ( isTopLevel ( ) ) { symbolTable . put ( functor . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_TOP_LEVEL_FUNCTOR , true ) ; } }


Input: Functors are considered top - level when they appear at the top - level within a clause or directly beneath a parent conjunction or disjunction that is considered to be top - level . [CODESPLIT] private boolean isTopLevel ( ) { if ( traverser . isTopLevel ( ) ) { return true ; } else { PositionalContext parentContext = traverser . getParentContext ( ) ; if ( parentContext != null ) { Term parentTerm = parentContext . getTerm ( ) ; if ( ( parentTerm instanceof Conjunction ) || ( parentTerm instanceof Disjunction ) ) { Boolean isTopLevel = ( Boolean ) symbolTable . get ( parentTerm . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_TOP_LEVEL_FUNCTOR ) ; return ( isTopLevel == null ) ? false : isTopLevel ; } } } return false ; }


Input: { [CODESPLIT] public void insertAttribute ( AttributeSet attributes , int c , int r ) { attributeGrid . insertAttribute ( attributes , c , r ) ; updateListeners ( ) ; }


Input: { [CODESPLIT] public void select ( int row , int col ) { for ( TextGridSelectionListener listener : textGridSelectionListeners ) { listener . select ( new TextGridEvent ( this , row , col ) ) ; } }


Input: { @inheritDoc } [CODESPLIT] public EnhancedTextTable createTable ( int c , int r , int w , int h ) { // Supply a text table, with this grid set up to listen for updates to the table, and to be re-rendered as the // table changes. EnhancedTextTable textTable = new EnhancedTextTableImpl ( ) ; textTable . addTextTableListener ( new EnhancedTableListener ( ) ) ; return textTable ; }


Input: Classifies a state using the decision tree . [CODESPLIT] 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. } }


Input:
---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void getIdReturnsId ( ) throws MalformedURLException { server ( ) . enqueue ( new MockResponse ( ) . setBody ( "" + "
" + "" ) ) ; URL actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getItem ( "http://y" ) . getId ( ) ; assertThat ( "item id" , actual , is ( new URL ( "http://x" ) ) ) ; }


Input:
---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void getTypeReturnsType ( ) throws MalformedURLException { server ( ) . enqueue ( new MockResponse ( ) . setBody ( "" + "
" + "" ) ) ; URL actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getItem ( "http://x" ) . getType ( ) ; assertThat ( "item type" , actual , is ( new URL ( "http://x" ) ) ) ; }


Input:
---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void getPropertyReturnsProperty ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( "" + "
" + "
" + "
" + "" ) ) ; MicrodataProperty actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getItem ( "http://i" ) . getProperty ( "x" ) ; assertThat ( "item property" , actual . getName ( ) , is ( "x" ) ) ; }


Input:
---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void unwrapWithUnknownTypeThrowsException ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( "" + "
" + "" ) ) ; MicrodataItem item = newBrowser ( ) . get ( url ( server ( ) ) ) . getItem ( "http://i" ) ; thrown ( ) . expect ( IllegalArgumentException . class ) ; thrown ( ) . expectMessage ( "Cannot unwrap to: class java.lang.Void" ) ; item . unwrap ( Void . class ) ; }


Input: Translates the partial order into the + 1 0 - 1 convention needed by Comparators . [CODESPLIT] 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 ; }


Input: Creates a priority queue with an { @link AStarComparator } to control the search ordering of the basic queue search algorithm . [CODESPLIT] public Queue < SearchNode < O , T > > createQueue ( ) { return new PriorityQueue < SearchNode < O , T > > ( 11 , new AStarComparator ( ) ) ; }


Input:
{ [CODESPLIT] public Iterator < Operator < Term > > traverse ( Clause clause , boolean reverse ) { /*log.fine("Traversing clause " + clause.toString(interner, true, false));*/ Functor head = clause . getHead ( ) ; Functor [ ] body = clause . getBody ( ) ; Queue < Operator < Term > > queue = ( ! reverse ) ? new StackQueue < Operator < Term > > ( ) : new LinkedList < Operator < Term > > ( ) ; // Create a nested scope in the symbol table for the clause, under its functor name/arity. int predicateName ; int clauseIndex ; if ( clause . isQuery ( ) ) { predicateName = - 1 ; } else { predicateName = head . getName ( ) ; } Integer numberOfClauses = ( Integer ) rootSymbolTable . get ( predicateName , CLAUSE_NO_SYMBOL_FIELD ) ; if ( numberOfClauses == null ) { numberOfClauses = 0 ; } rootSymbolTable . put ( predicateName , CLAUSE_NO_SYMBOL_FIELD , numberOfClauses + 1 ) ; clauseIndex = numberOfClauses ; SymbolTable < Integer , String , Object > predicateScopedSymbolTable = rootSymbolTable . enterScope ( predicateName ) ; /*log.fine(indenter.generateTraceIndent(2) + "Enter predicate scope " + predicateName);*/ clauseScopedSymbolTable = predicateScopedSymbolTable . enterScope ( clauseIndex ) ; /*log.fine(indenter.generateTraceIndent(2) + "Enter clause scope " + clauseIndex);*/ // For the head functor, clear the top-level flag, set in head context. if ( head != null ) { head . setReversable ( new ContextOperator ( clauseScopedSymbolTable , 0 , createHeadOperator ( head , clause ) ) ) ; head . setTermTraverser ( this ) ; queue . offer ( head ) ; /*log.fine("Set SKT as traverser on " + head.toString(interner, true, false));*/ /*log.fine("Created: " + ("head operator " + 0 + " on " + head.toString(interner, true, false)));*/ } // For the body functors, set the top-level flag, clear in head context. if ( body != null ) { for ( int i = 0 ; i < body . length ; i ++ ) { Functor bodyFunctor = body [ i ] ; bodyFunctor . setReversable ( new ContextOperator ( clauseScopedSymbolTable , i + 1 , createBodyOperator ( bodyFunctor , i , body , clause ) ) ) ; bodyFunctor . setTermTraverser ( this ) ; queue . offer ( bodyFunctor ) ; /*log.fine("Set SKT as traverser on " + bodyFunctor.toString(interner, true, false));*/ /*log.fine("Created: " +
                    ("body operator " + (i + 1) + " on " + bodyFunctor.toString(interner, true, false)));*/ } } return queue . iterator ( ) ; }


Input:
{ [CODESPLIT] public Iterator < Operator < Term > > traverse ( Functor functor , boolean reverse ) { /*log.fine("Traversing functor " + functor.toString(interner, true, false));*/ Queue < Operator < Term >> queue = ( ! reverse ) ? new StackQueue < Operator < Term > > ( ) : new LinkedList < Operator < Term > > ( ) ; Term [ ] arguments = functor . getArguments ( ) ; // For a top-level functor clear top-level flag, so that child functors are not taken as top-level. if ( arguments != null ) { for ( int i = 0 ; i < arguments . length ; i ++ ) { Term argument = arguments [ i ] ; // When navigating onto a variable, the variable is scoped within a clause, and may appear many times // within it. Therefore it always uses its unique id relative to the root symbol table for the // clause as its contextual position. Other terms use their position path and are relative to the // the current positions symbol table. SymbolTable < Integer , String , Object > contextSymbolTable ; if ( argument . isVar ( ) ) { contextSymbolTable = clauseScopedSymbolTable . enterScope ( CLAUSE_FREEVAR_INDEX ) ; /*log.fine("Enter freevar scope");*/ argument . setReversable ( new ContextOperator ( contextSymbolTable , createTermOperator ( argument , i , functor ) ) ) ; argument . setTermTraverser ( this ) ; queue . offer ( argument ) ; /*log.fine("Created: " +
                        ("var argument operator on " + argument.toString(interner, true, false)));*/ } else { contextSymbolTable = null ; argument . setReversable ( new ContextOperator ( contextSymbolTable , i , createTermOperator ( argument , i , functor ) ) ) ; argument . setTermTraverser ( this ) ; queue . offer ( argument ) ; /*log.fine("Created: " +
                        ("argument operator " + i + " on " + argument.toString(interner, true, false)));*/ } } } return queue . iterator ( ) ; }


Input: { @inheritDoc } [CODESPLIT] public void visit ( Term term ) { if ( isEnteringContext ( ) ) { SymbolKey key = currentSymbolTable . getSymbolKey ( currentPosition ) ; term . setSymbolKey ( key ) ; } if ( delegate != null ) { delegate . visit ( term ) ; } }


Input: { @inheritDoc } [CODESPLIT] public void visit ( Variable variable ) { if ( isEnteringContext ( ) ) { SymbolKey key = currentSymbolTable . getSymbolKey ( variable . getId ( ) ) ; variable . setSymbolKey ( key ) ; /*log.fine(variable.toString(interner, true, false) + " assigned " + key);*/ } else if ( isLeavingContext ( ) ) { variable . setTermTraverser ( null ) ; } if ( delegate != null ) { delegate . visit ( variable ) ; } }


Input: { [CODESPLIT] public void visit ( Predicate predicate ) { if ( isEnteringContext ( ) ) { super . visit ( predicate ) ; } else if ( isLeavingContext ( ) ) { predicate . setTermTraverser ( null ) ; } if ( delegate != null ) { delegate . visit ( predicate ) ; } }


Input: { [CODESPLIT] public void visit ( Clause clause ) { if ( isEnteringContext ( ) ) { super . visit ( clause ) ; } else if ( isLeavingContext ( ) ) { clause . setTermTraverser ( null ) ; } if ( delegate != null ) { delegate . visit ( clause ) ; } }


Input: { [CODESPLIT] public void visit ( Functor functor ) { if ( isEnteringContext ( ) ) { SymbolKey key = currentSymbolTable . getSymbolKey ( currentPosition ) ; functor . setSymbolKey ( key ) ; /*log.fine(functor.toString(interner, true, false) + " assigned " + key);*/ } else if ( isLeavingContext ( ) ) { functor . setTermTraverser ( null ) ; } if ( delegate != null ) { delegate . visit ( functor ) ; } }


Input: { [CODESPLIT] public void visit ( IntegerType literal ) { if ( isEnteringContext ( ) ) { SymbolKey key = currentSymbolTable . getSymbolKey ( currentPosition ) ; literal . setSymbolKey ( key ) ; } else if ( isLeavingContext ( ) ) { literal . setTermTraverser ( null ) ; } if ( delegate != null ) { delegate . visit ( literal ) ; } }


Input: Returns a distriubuted iterator that can provide elements of the list on demand over a remote connection . [CODESPLIT] 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 ) ; } }


Input: Calcalates the log base 2 of an integer . This code is tuned to uniformly distributed output values longer numbers are slightly favoured . [CODESPLIT] 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 ] ; } }


Input: Calcalates the log base 2 of an integer . This code is tuned to uniformly distributed input values longer numbers are favoured . [CODESPLIT] 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 ] ; } }


Input: Calcalates the log base 2 of an integer in O ( log ( N )) steps ; shorter numbers are favoured . [CODESPLIT] public static int intLogBase2v3 ( int value ) { int result = 0 ; if ( ( value & LOG2_V3_BRANCH_VALUES [ 4 ] ) > 0 ) { value >>= LOG2_V3_SHIFT_VALUES [ 4 ] ; result |= LOG2_V3_SHIFT_VALUES [ 4 ] ; } if ( ( value & LOG2_V3_BRANCH_VALUES [ 3 ] ) > 0 ) { value >>= LOG2_V3_SHIFT_VALUES [ 3 ] ; result |= LOG2_V3_SHIFT_VALUES [ 3 ] ; } if ( ( value & LOG2_V3_BRANCH_VALUES [ 2 ] ) > 0 ) { value >>= LOG2_V3_SHIFT_VALUES [ 2 ] ; result |= LOG2_V3_SHIFT_VALUES [ 2 ] ; } if ( ( value & LOG2_V3_BRANCH_VALUES [ 1 ] ) > 0 ) { value >>= LOG2_V3_SHIFT_VALUES [ 1 ] ; result |= LOG2_V3_SHIFT_VALUES [ 1 ] ; } if ( ( value & LOG2_V3_BRANCH_VALUES [ 0 ] ) > 0 ) { value >>= LOG2_V3_SHIFT_VALUES [ 0 ] ; result |= LOG2_V3_SHIFT_VALUES [ 0 ] ; } return result ; }


Input: Calcalates the log base 10 of an integer . This produces results faster for longer numbers . [CODESPLIT] public static int intLogBase10v2 ( int value ) { return ( value >= 1000000000 ) ? 9 : ( ( value >= 100000000 ) ? 8 : ( ( value >= 10000000 ) ? 7 : ( ( value >= 1000000 ) ? 6 : ( ( value >= 100000 ) ? 5 : ( ( value >= 10000 ) ? 4 : ( ( value >= 1000 ) ? 3 : ( ( value >= 100 ) ? 2 : ( ( value >= 10 ) ? 1 : 0 ) ) ) ) ) ) ) ) ; }


Input: Calcalates the log base 10 of an integer . This produces results faster for shorter numbers . [CODESPLIT] public static int intLogBase10v3 ( int value ) { return ( value < 10 ) ? 0 : ( ( value < 100 ) ? 1 : ( ( value < 1000 ) ? 2 : ( ( value < 10000 ) ? 3 : ( ( value < 100000 ) ? 4 : ( ( value < 1000000 ) ? 5 : ( ( value < 10000000 ) ? 6 : ( ( value < 100000000 ) ? 7 : ( ( value < 1000000000 ) ? 8 : 9 ) ) ) ) ) ) ) ) ; }


Input: Calcalates the log base 10 of an integer . This method favours shorter numbers . [CODESPLIT] public static int intLogBase10 ( long value ) { return ( value >= 1000000000000000000L ) ? 18 : ( ( value >= 100000000000000000L ) ? 17 : ( ( value >= 10000000000000000L ) ? 16 : ( ( value >= 1000000000000000L ) ? 15 : ( ( value >= 100000000000000L ) ? 14 : ( ( value >= 10000000000000L ) ? 13 : ( ( value >= 1000000000000L ) ? 12 : ( ( value >= 100000000000L ) ? 11 : ( ( value >= 10000000000L ) ? 10 : ( ( value >= 1000000000L ) ? 9 : ( ( value >= 100000000L ) ? 8 : ( ( value >= 10000000L ) ? 7 : ( ( value >= 1000000L ) ? 6 : ( ( value >= 100000L ) ? 5 : ( ( value >= 10000L ) ? 4 : ( ( value >= 1000L ) ? 3 : ( ( value >= 100L ) ? 2 : ( ( value >= 10L ) ? 1 : 0 ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ; }


Input: Calcalates the log base 10 of an integer . This method favours longer numbers or evenly distributed input . [CODESPLIT] public static int intLogBase10v2 ( long value ) { return ( value < 10 ) ? 0 : ( ( value < 100 ) ? 1 : ( ( value < 1000 ) ? 2 : ( ( value < 10000 ) ? 3 : ( ( value < 100000 ) ? 4 : ( ( value < 1000000 ) ? 5 : ( ( value < 10000000 ) ? 6 : ( ( value < 100000000 ) ? 7 : ( ( value < 1000000000L ) ? 8 : ( ( value < 10000000000L ) ? 9 : ( ( value < 100000000000L ) ? 10 : ( ( value < 1000000000000L ) ? 11 : ( ( value < 10000000000000L ) ? 12 : ( ( value < 100000000000000L ) ? 13 : ( ( value < 1000000000000000L ) ? 14 : ( ( value < 10000000000000000L ) ? 15 : ( ( value < 100000000000000000L ) ? 16 : ( ( value < 1000000000000000000L ) ? 17 : 18 ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ; }


Input: Calculates the number of ASCII characters that will be needed to represent a specifed signed 32 - bit integer . [CODESPLIT] 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 ; } }


Input: Calculates the number of ASCII characters that will be needed to represent a specifed signed 64 - bit integer . [CODESPLIT] 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 ; } }


Input: Calculates the number of ASCII characters that will be needed to represent a specified signed decimal number . [CODESPLIT] 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 ; }


Input: { [CODESPLIT] public Fader < Color > createFader ( Color startColor , Color endColor ) { return new FaderImpl ( startColor , endColor ) ; }


Input: { @inheritDoc } [CODESPLIT] public void changeColor ( C color ) { AttributeSet aset = new AttributeSet ( ) ; aset . put ( AttributeSet . BACKGROUND_COLOR , color ) ; grid . insertAttribute ( aset , col , row ) ; }


Input: { [CODESPLIT] public boolean proofStep ( ResolutionState state ) { Clause query = state . getCurrentClause ( ) ; // The query goals are placed onto the goal stack backwards so that their insertion order is reversed for an // intuitive left-to-right evaluation order. for ( int i = query . getBody ( ) . length - 1 ; i >= 0 ; i -- ) { BuiltInFunctor newGoal = state . getBuiltInTransform ( ) . apply ( query . getBody ( ) [ i ] ) ; state . getGoalStack ( ) . offer ( newGoal ) ; } return true ; }


Input: Sets a compiled head functor to this clause . [CODESPLIT] public void setHead ( Functor head , SizeableList < WAMInstruction > instructions ) { this . head = head ; addInstructions ( instructions ) ; }


Input: 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 . [CODESPLIT] 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 ; }


Input: Listens for events from back next finish and cancel inputs . If the event is finish the { @link #saveWork } method is triggered . If the event is cancel the { @link #discardWork } method is called . If the event is back or next then the { @link #prevPage } or { @link #nextPage } methods are called . [CODESPLIT] public void actionPerformed ( ActionEvent event ) { /*log.fine("void actionPerformed(ActionEvent): called");*/ /*log.fine("Action is " + event.getActionCommand());*/ // Check which action event was performed String action = event . getActionCommand ( ) ; // Check if the finish button was pressed if ( "Finish" . equals ( action ) ) { // Save the work in progress saveWorkFlow ( ) ; } // Check if the cancel button was pressed if ( "Cancel" . equals ( action ) ) { // Discard the work in progress discardWorkFlow ( ) ; } // Check if the next page button was pressed if ( "Next |>" . equals ( action ) ) { // Notify implementing class of transition to the next page nextPage ( ) ; } // Check if the prev page button was pressed if ( "<| Prev" . equals ( action ) ) { // Notify implementing class of transition to the previous page prevPage ( ) ; } }


Input: Sets the order in which the saveWork or dicardWork methods of the individual screens encountered in a work flow are called . On of the constants { @link #FORWARD_ORDERING } or { @link #REVERSE_ORDERING } should be passed as the value to this method to specify which ordering to use . [CODESPLIT] public void setCommitOrder ( String order ) { // Check that the specified order matches one of the ordering constants if ( ! order . equals ( FORWARD_ORDERING ) && ! order . equals ( REVERSE_ORDERING ) ) { return ; } // Check that the new ordering is different from the existing one so that some work needs to be done to change // it if ( order . equals ( FORWARD_ORDERING ) && ( accessedScreens instanceof LifoStack ) ) { // Copy the screens into a forward ordered stack accessedScreens = new FifoStack ( accessedScreens ) ; } else if ( order . equals ( REVERSE_ORDERING ) && ( accessedScreens instanceof LifoStack ) ) { // Copy the screens into a reverse ordered stack accessedScreens = new LifoStack ( accessedScreens ) ; } }


Input: Method called when the finish button is pressed . It works through all the screens in the order in which they were accessed ( or reverse order depending on the order set by the { [CODESPLIT] protected void saveWorkFlow ( ) { /*log.fine("void saveWorkFlow(): called");*/ // Cycle through all the accessed screens in the work flow while ( ! accessedScreens . isEmpty ( ) ) { WorkFlowScreenPanel nextScreen = ( WorkFlowScreenPanel ) accessedScreens . pop ( ) ; // Check if the screen has unsaved state and call its save work method if so if ( nextScreen . getState ( ) . getState ( ) . equals ( WorkFlowScreenState . NOT_SAVED ) ) { nextScreen . saveWork ( ) ; } } // Call the save work method for the entire work flow controller to finalize the work flow saveWork ( ) ; }


Input: Method called when the cancel button is pressed . It works through all the screens in the order in which they were accessed ( or reverse order depending on the order set by the { [CODESPLIT] protected void discardWorkFlow ( ) { /*log.fine("void discardWorkFlow(): called");*/ // Cycle through all the accessed screens in the work flow while ( ! accessedScreens . isEmpty ( ) ) { WorkFlowScreenPanel nextScreen = ( WorkFlowScreenPanel ) accessedScreens . pop ( ) ; // Check if the screen has unsaved state and call its discard work method if so if ( nextScreen . getState ( ) . getState ( ) . equals ( WorkFlowScreenState . NOT_SAVED ) ) { nextScreen . discardWork ( ) ; } } // Call the discard work method for the entire work flow controller to finalize the work flow discardWork ( ) ; }


Input: 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 . [CODESPLIT] 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 ( ) ; }


Input: Evaluates a logical predicate . [CODESPLIT] 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 ; }


Input:
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 . [CODESPLIT] 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 ) ; }


Input: Looks up a property value relative to the environment base class and modifier . The default environment will be checked for a matching property if defaults are being used . [CODESPLIT] public String getProperty ( Object base , String modifier , String key ) { return getProperty ( base . getClass ( ) . getName ( ) , modifier , key ) ; }


Input: Looks up a property value relative to the environment base class and modifier . The default environment will be checked for a matching property if defaults are being used . [CODESPLIT] public String getProperty ( String base , String modifier , String key ) { String result = null ; // Loop over the key orderings, from the most specific to the most general, until a matching value is found. for ( Iterator i = getKeyIterator ( base , modifier , key ) ; i . hasNext ( ) ; ) { String nextKey = ( String ) i . next ( ) ; result = super . getProperty ( nextKey ) ; if ( result != null ) { break ; } } return result ; }