Input: Pretty prints the current environment frame for debugging purposes . [CODESPLIT] protected String traceEnvFrame ( ) { return "env: [ ep = " + data . get ( ep ) + ", cp = " + data . get ( ep + 1 ) + ", n = " + data . get ( ep + 2 ) + "]" ; }


Input: Pretty prints the current choice point frame for debugging purposes . [CODESPLIT] protected String traceChoiceFrame ( ) { if ( bp == 0 ) { return "" ; } int n = data . get ( bp ) ; return "choice: [ n = " + data . get ( bp ) + ", ep = " + data . get ( bp + n + 1 ) + ", cp = " + data . get ( bp + n + 2 ) + ", bp = " + data . get ( bp + n + 3 ) + ", l = " + data . get ( bp + n + 4 ) + ", trp = " + data . get ( bp + n + 5 ) + ", hp = " + data . get ( bp + n + 6 ) + ", b0 = " + data . get ( bp + n + 7 ) ; }


Input: { [CODESPLIT] protected int deref ( int a ) { // tag, value <- STORE[a] int addr = a ; int tmp = data . get ( a ) ; derefTag = ( byte ) ( tmp >>> TSHIFT ) ; derefVal = tmp & AMASK ; // while tag = REF and value != a while ( ( derefTag == WAMInstruction . REF ) ) { // tag, value <- STORE[a] addr = derefVal ; tmp = data . get ( derefVal ) ; derefTag = ( byte ) ( tmp >>> TSHIFT ) ; tmp = tmp & AMASK ; // Break on free var. if ( derefVal == tmp ) { break ; } derefVal = tmp ; } return addr ; }


Input: Invokes an internal function . [CODESPLIT] private boolean callInternal ( int function , int arity , int numPerms ) { switch ( function ) { case CALL_1_ID : return internalCall_1 ( numPerms ) ; case EXECUTE_1_ID : return internalExecute_1 ( ) ; default : throw new IllegalStateException ( "Unknown internal function id: " + function ) ; } }


Input: Implements the call / 1 predicate . [CODESPLIT] private boolean internalCall_1 ( int numPerms ) { int pn = setupCall_1 ( ) ; if ( pn == - 1 ) { return false ; } // Make the call. // STACK[E + 2] <- numPerms data . put ( ep + 2 , numPerms ) ; // CP <- P + instruction_size(P) cp = ip + 7 ; /*trace.fine(ip + ": (CALL) " + pn + ", " + numPerms + " (cp = " + cp + ")]");*/ // B0 <- B b0 = bp ; // P <- @(p/n) ip = pn ; return true ; }


Input: Implements the execute variant of the call / 1 predicate . [CODESPLIT] private boolean internalExecute_1 ( ) { int pn = setupCall_1 ( ) ; if ( pn == - 1 ) { return false ; } // Make the call. /*trace.fine(ip + ": (EXECUTE) " + pn + " (cp = " + cp + ")]");*/ // B0 <- B b0 = bp ; // P <- @(p/n) ip = pn ; return true ; }


Input: Sets up the registers to make a call for implementing call / 1 . The first register should reference a structure to be turned into a predicate call . The arguments of this structure will be set up in the registers and the entry point of the predicate to call will be returned . [CODESPLIT] private int setupCall_1 ( ) { // Get X0. int addr = deref ( 0 ) ; byte tag = derefTag ; int val = derefVal ; // Check it points to a structure. int fn ; if ( tag == STR ) { fn = getHeap ( val ) ; } else if ( tag == CON ) { fn = val ; } else { /*trace.fine("call/1 not invoked against structure.");*/ return - 1 ; } // Look up the call point of the matching functor. int f = fn & 0x00ffffff ; WAMCallPoint callPoint = resolveCallPoint ( f ) ; if ( callPoint . entryPoint == - 1 ) { /*trace.fine("call/1 to unknown call point.");*/ return - 1 ; } int pn = callPoint . entryPoint ; // Set registers X0... to ref to args... FunctorName functorName = getDeinternedFunctorName ( f ) ; int arity = functorName . getArity ( ) ; for ( int i = 0 ; i < arity ; i ++ ) { data . put ( i , refTo ( val + 1 + i ) ) ; } return pn ; }


Input: Computes the start of the next stack frame . This depends on whether the most recent stack frame is an environment frame or a choice point frame as these have different sizes . The size of the most recent type of frame is computed and added to the current frame pointer to give the start of the next frame . [CODESPLIT] private int nextStackFrame ( ) { // if E > B // then newB <- E + STACK[E + 2] + 3 // else newB <- B + STACK[B] + 7 if ( ep == bp ) { return STACK_BASE ; } else if ( ep > bp ) { return ep + data . get ( ep + 2 ) + 3 ; } else { return bp + data . get ( bp ) + 8 ; } }


Input: Backtracks to the continuation label stored in the current choice point frame if there is one . Otherwise returns a fail to indicate that there are no more choice points so no backtracking can be done . [CODESPLIT] private boolean backtrack ( ) { // if B = bottom_of_stack if ( bp == 0 ) { //  then fail_and_exit_program return true ; } else { // B0 <- STACK[B + STACK[B} + 7] b0 = data . get ( bp + data . get ( bp ) + 7 ) ; // P <- STACK[B + STACK[B] + 4] ip = data . get ( bp + data . get ( bp ) + 4 ) ; return false ; } }


Input: Creates a binding of one variable onto another . One of the supplied addresses must be an unbound variable . If both are unbound variables the higher ( newer ) address is bound to the lower ( older ) one . [CODESPLIT] private void bind ( int a1 , int a2 ) { // <t1, _> <- STORE[a1] int t1 = ( byte ) ( data . get ( a1 ) >>> TSHIFT ) ; // <t2, _> <- STORE[a2] int t2 = ( byte ) ( data . get ( a2 ) >>> TSHIFT ) ; // if (t1 = REF) /\ ((t2 != REF) \/ (a2 < a1)) if ( ( t1 == WAMInstruction . REF ) && ( ( t2 != WAMInstruction . REF ) || ( a2 < a1 ) ) ) { //  STORE[a1] <- STORE[a2] //data.put(a1, refTo(a2)); data . put ( a1 , data . get ( a2 ) ) ; //  trail(a1) trail ( a1 ) ; } else if ( t2 == WAMInstruction . REF ) { //  STORE[a2] <- STORE[a1] //data.put(a2, refTo(a1)); data . put ( a2 , data . get ( a1 ) ) ; //  tail(a2) trail ( a2 ) ; } }


Input: Records the address of a binding onto the trail . The trail pointer is advanced by one as part of this operation . [CODESPLIT] private void trail ( int addr ) { // if (a < HB) \/ ((H < a) /\ (a < B)) if ( ( addr < hbp ) || ( ( hp < addr ) && ( addr < bp ) ) ) { //  TRAIL[TR] <- a data . put ( trp , addr ) ; //  TR <- TR + 1 trp ++ ; } }


Input: Undoes variable bindings that have been recorded on the trail . Addresses recorded on the trail are reset to REF to self . [CODESPLIT] private void unwindTrail ( int a1 , int a2 ) { // for i <- a1 to a2 - 1 do for ( int addr = a1 ; addr < a2 ; addr ++ ) { //  STORE[TRAIL[i]] <- <REF, TRAIL[i]> int tmp = data . get ( addr ) ; data . put ( tmp , refTo ( tmp ) ) ; } }


Input: Tidies trail when a choice point is being discarded and a previous choice point it being made the current one . [CODESPLIT] private void tidyTrail ( ) { int i ; // Check that there is a current choice point to tidy down to, otherwise tidy down to the root of the trail. if ( bp == 0 ) { i = TRAIL_BASE ; } else { i = data . get ( bp + data . get ( bp ) + 5 ) ; } while ( i < trp ) { int addr = data . get ( i ) ; if ( ( addr < hbp ) || ( ( hp < addr ) && ( addr < bp ) ) ) { i ++ ; } else { data . put ( i , data . get ( trp - 1 ) ) ; trp -- ; } } }


Input: Attempts to unify structures or references on the heap given two references to them . Structures are matched element by element free references become bound . [CODESPLIT] private boolean unify ( int a1 , int a2 ) { // pdl.push(a1) // pdl.push(a2) uPush ( a1 ) ; uPush ( a2 ) ; // fail <- false boolean fail = false ; // while !empty(PDL) and not failed while ( ! uEmpty ( ) && ! fail ) { // d1 <- deref(pdl.pop()) // d2 <- deref(pdl.pop()) // t1, v1 <- STORE[d1] // t2, v2 <- STORE[d2] int d1 = deref ( uPop ( ) ) ; int t1 = derefTag ; int v1 = derefVal ; int d2 = deref ( uPop ( ) ) ; int t2 = derefTag ; int v2 = derefVal ; // if (d1 != d2) if ( d1 != d2 ) { // if (t1 = REF or t2 = REF) // bind(d1, d2) if ( ( t1 == WAMInstruction . REF ) ) { bind ( d1 , d2 ) ; } else if ( t2 == WAMInstruction . REF ) { bind ( d1 , d2 ) ; } else if ( t2 == WAMInstruction . STR ) { // f1/n1 <- STORE[v1] // f2/n2 <- STORE[v2] int fn1 = data . get ( v1 ) ; int fn2 = data . get ( v2 ) ; byte n1 = ( byte ) ( fn1 >>> 24 ) ; // if f1 = f2 and n1 = n2 if ( fn1 == fn2 ) { // for i <- 1 to n1 for ( int i = 1 ; i <= n1 ; i ++ ) { // pdl.push(v1 + i) // pdl.push(v2 + i) uPush ( v1 + i ) ; uPush ( v2 + i ) ; } } else { // fail <- true fail = true ; } } else if ( t2 == WAMInstruction . CON ) { if ( ( t1 != WAMInstruction . CON ) || ( v1 != v2 ) ) { fail = true ; } } else if ( t2 == WAMInstruction . LIS ) { if ( t1 != WAMInstruction . LIS ) { fail = true ; } else { uPush ( v1 ) ; uPush ( v2 ) ; uPush ( v1 + 1 ) ; uPush ( v2 + 1 ) ; } } } } return ! fail ; }


Input: A simplified unification algorithm for unifying against a constant . [CODESPLIT] private boolean unifyConst ( int fn , int addr ) { boolean success ; int deref = deref ( addr ) ; int tag = derefTag ; int val = derefVal ; // case STORE[addr] of switch ( tag ) { case REF : { // <REF, _> : // STORE[addr] <- <CON, c> data . put ( deref , constantCell ( fn ) ) ; // trail(addr) trail ( deref ) ; success = true ; break ; } case CON : { // <CON, c'> : // fail <- (c != c'); success = val == fn ; break ; } default : { // other: fail <- true; success = false ; } } return success ; }


Input: Pretty prints a variable allocation slot for tracing purposes . [CODESPLIT] private String printSlot ( int xi , int mode ) { return ( ( mode == STACK_ADDR ) ? "Y" : "X" ) + ( ( mode == STACK_ADDR ) ? ( xi - ep - 3 ) : xi ) ; }


Input: Generates a random starting position . [CODESPLIT] public static EightPuzzleState getRandomStartState ( ) { EightPuzzleState newState ; // Turn the goal string into a list of characters. List < Character > charList = stringToCharList ( GOAL_STRING ) ; // Generate random puzzles until a solvable one is found. do { // Shuffle the list. Collections . shuffle ( charList ) ; // Turn the shuffled list into a proper eight puzzle state object. newState = charListToState ( charList ) ; // Check that the puzzle is solvable and if not then repeat the shuffling process. } while ( ! isSolvable ( newState ) ) ; return newState ; }


Input: To check for solvability the empty tile is moved to its goal position and then the number of swaps needed to put the other tiles in position is counted . For an odd number of rows on a square puzzle there must be an even number of swaps for an even number of rows an odd number of swaps . [CODESPLIT] public static boolean isSolvable ( EightPuzzleState state ) { // Take a copy of the puzzle to check. This is done because this puzzle will be updated in-place and the // original is to be preserved. EightPuzzleState checkState ; try { checkState = ( EightPuzzleState ) state . clone ( ) ; } catch ( CloneNotSupportedException e ) { throw new IllegalStateException ( "Puzzle state could not be cloned." , e ) ; } // Create the goal state to check against when swapping tiles into position. EightPuzzleState goalState = getGoalState ( ) ; // Count the number of illegal swaps needed to put the puzzle in order. int illegalSwaps = 0 ; // Loop over the whole board, left to right, to to bottom for ( int j = 0 ; j < 3 ; j ++ ) { for ( int i = 0 ; i < 3 ; i ++ ) { // Find out from the goal state what tile should be at this position. char t = goalState . getTileAt ( i , j ) ; // Swap the tile into its goal position keeping count of the total number of illegal swaps. illegalSwaps += checkState . swapTileToLocationCountingIllegal ( t , i , j ) ; } } // Check if the number of illegal swaps is even in which case the puzzle is solvable, or odd in which case it // is not solvable. return ( illegalSwaps % 2 ) == 0 ; }


Input: Applies a move to generate a new board position . This creates a new state object and updates its board position . The board position in this object is not changed . [CODESPLIT] public EightPuzzleState getChildStateForOperator ( Operator op ) { // Create a copy of the existing board state EightPuzzleState newState ; try { newState = ( EightPuzzleState ) clone ( ) ; } catch ( CloneNotSupportedException e ) { throw new IllegalStateException ( "Puzzle state could not be cloned." , e ) ; } // Update the new board state using the in-place operator application newState . updateWithOperator ( op ) ; return newState ; }


Input: Supplies the valid moves for a board position . [CODESPLIT] public Iterator < Operator < String > > validOperators ( boolean reverse ) { // Used to hold a list of valid moves List < Operator < String >> moves = new ArrayList < Operator < String > > ( 4 ) ; // Check if the up move is valid if ( emptyY != 0 ) { moves . add ( new OperatorImpl < String > ( "U" ) ) ; } // Check if the down move is valid if ( emptyY != 2 ) { moves . add ( new OperatorImpl < String > ( "D" ) ) ; } // Check if the left move is valid if ( emptyX != 0 ) { moves . add ( new OperatorImpl < String > ( "L" ) ) ; } // Check if the right move is valid if ( emptyX != 2 ) { moves . add ( new OperatorImpl < String > ( "R" ) ) ; } return moves . iterator ( ) ; }


Input: Pretty prints the board as 3 lines of characters with a space for the empty square . [CODESPLIT] public String prettyPrint ( ) { String result = "" ; for ( int j = 0 ; j < 3 ; j ++ ) { result += new String ( board [ j ] ) + "\n" ; } result = result . replace ( ' ' , ' ' ) ; return result ; }


Input:
Repeatedly swaps a tile with its neighbours until it reaches the specified location . If the tile is swapped with the empty tile then this is a legal move . If the tile is swapped with another non - empty tile then this is an illegal move and the total number of illegal moves is counted . [CODESPLIT] protected int swapTileToLocationCountingIllegal ( char t , int x , int y ) { // Used to hold the count of illegal swaps int illegal = 0 ; // Find out where the tile to move is int tileX = getXForTile ( t ) ; int tileY = getYForTile ( t ) ; // Shift the tile into the correct column by repeatedly moving it left or right. while ( tileX != x ) { if ( ( tileX - x ) > 0 ) { if ( swapTiles ( tileX , tileY , tileX - 1 , tileY ) ) { illegal ++ ; } tileX -- ; } else { if ( swapTiles ( tileX , tileY , tileX + 1 , tileY ) ) { illegal ++ ; } tileX ++ ; } } // Shift the tile into the correct row by repeatedly moving it up or down. while ( tileY != y ) { // Commented out because tiles never swap down the board during the solvability test because tiles are // swapped into place left to right, top to bottom. The top row is always filled first so tiles cannot be // swapped down into it. Then the next row is filled but ones from the row above are never swapped down // into it because they are alrady in place and never move again and so on. /* if (tileY - y > 0)
             *{*/ if ( swapTiles ( tileX , tileY , tileX , tileY - 1 ) ) { illegal ++ ; } tileY -- ; /*}
             * else { if (swapTiles(tileX, tileY, tileX, tileY + 1)) illegal++; tileY++;}*/ } return illegal ; }


Input: Applies a move to the board position . This changes the board position stored in this object . This is different from the { @link #getChildStateForOperator } method which updates the board position in a new object . [CODESPLIT] protected void updateWithOperator ( Operator op ) { // Get the operator as a character by taking the first character of the operator string char opc = ( ( String ) op . getOp ( ) ) . charAt ( 0 ) ; // Move the empty tile according to the specified operation switch ( opc ) { // Swap the empty tile with the one above it. case ' ' : { swapTiles ( emptyX , emptyY , emptyX , emptyY - 1 ) ; break ; } // Swap the empty tile with the one below it. case ' ' : { swapTiles ( emptyX , emptyY , emptyX , emptyY + 1 ) ; break ; } // Swap the empty tile with the one to the left of it. case ' ' : { swapTiles ( emptyX , emptyY , emptyX - 1 , emptyY ) ; break ; } // Swap the empty tile with the one to the right of it. case ' ' : { swapTiles ( emptyX , emptyY , emptyX + 1 , emptyY ) ; break ; } default : { throw new IllegalStateException ( "Unkown operator: " + opc + "." ) ; } } }


Input: Swaps the two tiles at the specified coordinates . One of the tiles may be the empty tile and the empty tile position will be correctly updated . If neither of the tiles is empty then this is an illegal swap in which case the method returns true . [CODESPLIT] protected boolean swapTiles ( int x1 , int y1 , int x2 , int y2 ) { // Used to indicate that one of the swapped tiles was the empty tile boolean swappedEmpty = false ; // Get the tile at the first position char tile1 = board [ y1 ] [ x1 ] ; // Store the tile from the second position at the first position char tile2 = board [ y2 ] [ x2 ] ; board [ y1 ] [ x1 ] = tile2 ; // Store the first tile in the second position board [ y2 ] [ x2 ] = tile1 ; // Check if the first tile was the empty tile and update the empty tile coordinates if so if ( tile1 == ' ' ) { emptyX = x2 ; emptyY = y2 ; swappedEmpty = true ; } // Else check if the second tile was the empty tile and update the empty tile coordinates if so else if ( tile2 == ' ' ) { emptyX = x1 ; emptyY = y1 ; swappedEmpty = true ; } return ! swappedEmpty ; }


Input: Turns a string representation of the board into a list of characters . [CODESPLIT] private static List < Character > stringToCharList ( String boardString ) { // Turn the goal state into a list of characters char [ ] chars = new char [ 9 ] ; boardString . getChars ( 0 , 9 , chars , 0 ) ; List < Character > charList = new ArrayList < Character > ( ) ; for ( int l = 0 ; l < 9 ; l ++ ) { charList . add ( chars [ l ] ) ; } return charList ; }


Input: Turns a list of characters representation of the board into a proper state . [CODESPLIT] private static EightPuzzleState charListToState ( List < Character > charList ) { // Create a new empty puzzle state EightPuzzleState newState = new EightPuzzleState ( ) ; // Loop over the board inserting the characters into it from the character list Iterator < Character > k = charList . iterator ( ) ; for ( int j = 0 ; j < 3 ; j ++ ) { for ( int i = 0 ; i < 3 ; i ++ ) { char nextChar = k . next ( ) ; // Check if this is the empty tile and if so then take note of its position if ( nextChar == ' ' ) { newState . emptyX = i ; newState . emptyY = j ; } newState . board [ j ] [ i ] = nextChar ; } } return newState ; }


Input: { [CODESPLIT] public void publish ( LogRecord record ) { org . apache . log4j . Logger log4j = getTargetLogger ( record . getLoggerName ( ) ) ; Priority priority = toLog4j ( record . getLevel ( ) ) ; if ( ! priority . equals ( org . apache . log4j . Level . OFF ) ) { log4j . log ( priority , toLog4jMessage ( record ) , record . getThrown ( ) ) ; } }


Input: Transforms a java . util . logging . LogRecord to a message printable on Log4J . [CODESPLIT] private String toLog4jMessage ( LogRecord record ) { String message = record . getMessage ( ) ; // Format message Object [ ] parameters = record . getParameters ( ) ; if ( ( parameters != null ) && ( parameters . length != 0 ) ) { // Check for the first few parameters ? if ( ( message . indexOf ( "{0}" ) >= 0 ) || ( message . indexOf ( "{1}" ) >= 0 ) || ( message . indexOf ( "{2}" ) >= 0 ) || ( message . indexOf ( "{3}" ) >= 0 ) ) { message = MessageFormat . format ( message , parameters ) ; } } return message ; }


Input: Converts java . util . logging levels to Log4J logging levels . [CODESPLIT] private org . apache . log4j . Level toLog4j ( Level level ) { if ( Level . SEVERE == level ) { return org . apache . log4j . Level . ERROR ; } else if ( Level . WARNING == level ) { return org . apache . log4j . Level . WARN ; } else if ( Level . INFO == level ) { return org . apache . log4j . Level . INFO ; } else if ( Level . FINE == level ) { return org . apache . log4j . Level . DEBUG ; } else if ( Level . FINER == level ) { return org . apache . log4j . Level . TRACE ; } else if ( Level . OFF == level ) { return org . apache . log4j . Level . OFF ; } return org . apache . log4j . Level . OFF ; }


Input: { [CODESPLIT] public boolean offer ( E o ) { if ( transactional ) { // Delegate the offer operation to the wrapped queue. txMethod . requestWriteOperation ( new EnqueueRecord ( o ) ) ; // return success; return true ; } else { boolean success = queue . offer ( o ) ; // Update the queue size if the offer was succesfull. if ( success ) { incrementSizeAndCount ( o ) ; } return success ; } }


Input: { [CODESPLIT] public E poll ( ) { Object owner ; if ( transactional ) { owner = TxManager . getCurrentSession ( ) ; } else { owner = null ; } // Attempt to acquire an available element from the queue for the current transaction. return pollAccept ( owner ) ; }


Input: { [CODESPLIT] public E pollAccept ( Object owner ) { if ( transactional ) { E element = null ; RequeueElementWrapper < E > record = null ; // Find an element on the requeue that is free, or has already been acquired by the owner but not accepted. // Mark the element as acquired by the owner as necessary. if ( ! requeue . isEmpty ( ) ) { for ( RequeueElementWrapper < E > nextRecord : requeue ) { if ( AcquireState . Free . equals ( nextRecord . state ) ) { record = nextRecord ; record . state = AcquireState . Acquired ; record . owner = owner ; element = record . element ; break ; } else if ( AcquireState . Acquired . equals ( nextRecord . state ) && owner . equals ( nextRecord . owner ) ) { record = nextRecord ; element = record . element ; break ; } } } // If an element cannot be found on the requeue, poll an element from the main queue, and place it onto the // requeue. if ( record == null ) { element = queue . poll ( ) ; } // If no element at all can be found return null. if ( element == null ) { return element ; } // Check that an element was actually available on the queue before creating a new acquired record for it // on the requeue. if ( record == null ) { record = requeue ( element , owner , AcquireState . Acquired ) ; } // Accept the element and create a transaction operation to remove it upon commit or unnaccept it upon // rollback. record . state = AcquireState . Accepted ; txMethod . requestWriteOperation ( new AcceptRecord ( record ) ) ; return record . element ; } else { E element ; // Find an element on the requeue that is free. Remove it and return it. if ( ! requeue . isEmpty ( ) ) { for ( RequeueElementWrapper < E > nextRecord : requeue ) { if ( AcquireState . Free . equals ( nextRecord . state ) ) { requeue . remove ( nextRecord ) ; requeuedElementMap . remove ( nextRecord . element ) ; return nextRecord . element ; } } } // Or poll an element from the main queue and return it. element = queue . poll ( ) ; if ( element != null ) { decrementSizeAndCount ( element ) ; } return element ; } }


Input: { [CODESPLIT] public E pollAcquire ( Object owner ) { E element ; // Find an element on the requeue that is free and return it. if ( ! requeue . isEmpty ( ) ) { for ( RequeueElementWrapper < E > nextRecord : requeue ) { if ( AcquireState . Free . equals ( nextRecord . state ) ) { nextRecord . state = AcquireState . Acquired ; nextRecord . owner = owner ; return nextRecord . element ; } } } // Nothing could be found on the requeue, so attempt to poll an element off the main queue and acquire // it on the requeue. element = queue . poll ( ) ; if ( element != null ) { requeue ( element , owner , AcquireState . Acquired ) ; } return element ; }


Input: { [CODESPLIT] public boolean acquire ( Object owner , Object o ) { // Look up the element wrapper record for the element to be accepted. RequeueElementWrapper < E > record = requeuedElementMap . get ( o ) ; // Check if the element is currently free, and acquire it if so. if ( AcquireState . Free . equals ( record . state ) ) { record . state = AcquireState . Acquired ; record . owner = owner ; return true ; } return false ; }


Input: { [CODESPLIT] public void release ( Object owner , Object o ) { // Look up the element wrapper record for the element to be released, and release it. RequeueElementWrapper < E > record = requeuedElementMap . get ( o ) ; if ( record != null ) { record . state = AcquireState . Free ; record . owner = null ; } }


Input: { [CODESPLIT] public void accept ( Object owner , Object o ) { // Look up the element wrapper record for the element to be accepted. RequeueElementWrapper < E > record = requeuedElementMap . get ( o ) ; if ( record != null ) { // If running in a transaction, create an accept operation to accept the item only upon commit of the // transaction. if ( transactional ) { record . state = AcquireState . Accepted ; txMethod . requestWriteOperation ( new AcceptRecord ( record ) ) ; } else { requeuedElementMap . remove ( o ) ; requeue . remove ( record ) ; } } }


Input: { [CODESPLIT] public E take ( ) throws InterruptedException { if ( ! isBlockingQueue ) { throw new UnsupportedOperationException ( "This operation is only supported on blocking queues." ) ; } return ( ( java . util . concurrent . BlockingQueue < E > ) queue ) . take ( ) ; }


Input: { [CODESPLIT] public int drainTo ( Collection < ? super E > c ) { if ( ! isBlockingQueue ) { throw new UnsupportedOperationException ( "This operation is only supported on blocking queues." ) ; } return ( ( java . util . concurrent . BlockingQueue < E > ) queue ) . drainTo ( c ) ; }


Input: { [CODESPLIT] public boolean offer ( E o , long timeout , TimeUnit unit ) throws InterruptedException { if ( ! isBlockingQueue ) { throw new UnsupportedOperationException ( "This operation is only supported on blocking queues." ) ; } return ( ( java . util . concurrent . BlockingQueue < E > ) queue ) . offer ( o , timeout , unit ) ; }


Input: { [CODESPLIT] public void put ( E o ) throws InterruptedException { if ( ! isBlockingQueue ) { throw new UnsupportedOperationException ( "This operation is only supported on blocking queues." ) ; } ( ( java . util . concurrent . BlockingQueue < E > ) queue ) . put ( o ) ; }


Input: { [CODESPLIT] public int remainingCapacity ( ) { if ( ! isBlockingQueue ) { throw new UnsupportedOperationException ( "This operation is only supported on blocking queues." ) ; } return ( ( java . util . concurrent . BlockingQueue < E > ) queue ) . remainingCapacity ( ) ; }


Input: Places an element onto the requeue buffer . [CODESPLIT] private void requeue ( E element ) { RequeueElementWrapper < E > record = new RequeueElementWrapper < E > ( element ) ; requeue . add ( record ) ; requeuedElementMap . put ( element , record ) ; }


Input: Places an element onto the requeue buffer in the acquired state by the specified owner . [CODESPLIT] private RequeueElementWrapper < E > requeue ( E element , Object owner , AcquireState acquired ) { RequeueElementWrapper < E > record = new RequeueElementWrapper < E > ( element ) ; record . state = acquired ; record . owner = owner ; requeue . add ( record ) ; requeuedElementMap . put ( element , record ) ; return record ; }


Input: Atomically adds to the size and count if the queue is running in atomic counting mode or sizeable mode and the element is sizeable . [CODESPLIT] private void incrementSizeAndCount ( E record ) { // Update the count for atomically counted queues. if ( atomicallyCounted ) { count . incrementAndGet ( ) ; } // Update the size for sizeable elements and sizeable queues. if ( sizeable && ( record instanceof Sizeable ) ) { dataSize . addAndGet ( ( ( Sizeable ) record ) . sizeof ( ) ) ; } else if ( sizeable ) { dataSize . incrementAndGet ( ) ; } }


Input: Atomically subtracts from the size and count if the queue is running in atomic counting mode or sizeable mode and the element is sizeable . [CODESPLIT] private void decrementSizeAndCount ( E record ) { // Update the count for atomically counted queues. if ( atomicallyCounted ) { count . decrementAndGet ( ) ; } // Update the size for sizeable elements and sizeable queues. if ( sizeable && ( record instanceof Sizeable ) ) { long recordSize = - ( ( Sizeable ) record ) . sizeof ( ) ; long oldSize = dataSize . getAndAdd ( recordSize ) ; long newSize = oldSize + recordSize ; signalOnSizeThresholdCrossing ( oldSize , newSize ) ; } else if ( sizeable ) { long oldSize = dataSize . getAndDecrement ( ) ; long newSize = oldSize - 1 ; signalOnSizeThresholdCrossing ( oldSize , newSize ) ; } }


Input: Signals the signallable resource if the size crosses a threshold boundary in a downward direction . [CODESPLIT] private void signalOnSizeThresholdCrossing ( long oldSize , long newSize ) { if ( signalable != null ) { if ( ( oldSize >= lowWaterSizeThreshold ) && ( newSize < lowWaterSizeThreshold ) ) { signalable . signalAll ( ) ; } else if ( ( oldSize >= highWaterSizeThreshold ) && ( newSize < highWaterSizeThreshold ) ) { signalable . signal ( ) ; } } }


Input: Retrieves the named object . If name is empty returns a new instance of this context ( which represents the same naming context as this context but its environment may be modified independently and it may be accessed concurrently ) . [CODESPLIT] public Object lookup ( String name ) throws NamingException { if ( "" . equals ( name ) ) { // Asking to look up this context itself.  Create and return // a new instance with its own independent environment. return ( new SimpleContext ( myEnv ) ) ; } Object answer = bindings . get ( name ) ; if ( answer == null ) { throw new NameNotFoundException ( name + " not found" ) ; } return answer ; }


Input: Binds a name to an object . All intermediate contexts and the target context ( that named by all but terminal atomic component of the name ) must already exist . [CODESPLIT] public void bind ( String name , Object obj ) throws NamingException { if ( "" . equals ( name ) ) { throw new InvalidNameException ( "Cannot bind empty name" ) ; } if ( bindings . get ( name ) != null ) { throw new NameAlreadyBoundException ( "Use rebind to override" ) ; } bindings . put ( name , obj ) ; }


Input: Binds a name to an object . All intermediate contexts and the target context ( that named by all but terminal atomic component of the name ) must already exist . [CODESPLIT] public void bind ( Name name , Object obj ) throws NamingException { // Flat namespace; no federation; just call string version bind ( name . toString ( ) , obj ) ; }


Input: Binds a name to an object overwriting any existing binding . All intermediate contexts and the target context ( that named by all but terminal atomic component of the name ) must already exist . [CODESPLIT] public void rebind ( String name , Object obj ) throws NamingException { if ( "" . equals ( name ) ) { throw new InvalidNameException ( "Cannot bind empty name" ) ; } bindings . put ( name , obj ) ; }


Input: Unbinds the named object . Removes the terminal atomic name in name from the target context -- that named by all but the terminal atomic part of name . [CODESPLIT] public void unbind ( String name ) throws NamingException { if ( "" . equals ( name ) ) { throw new InvalidNameException ( "Cannot unbind empty name" ) ; } bindings . remove ( name ) ; }


Input: Binds a new name to the object bound to an old name and unbinds the old name . Both names are relative to this context . Any attributes associated with the old name become associated with the new name . Intermediate contexts of the old name are not changed . [CODESPLIT] public void rename ( String oldname , String newname ) throws NamingException { if ( "" . equals ( oldname ) || "" . equals ( newname ) ) { throw new InvalidNameException ( "Cannot rename empty name" ) ; } // Check if new name exists if ( bindings . get ( newname ) != null ) { throw new NameAlreadyBoundException ( newname + " is already bound" ) ; } // Check if old name is bound Object oldBinding = bindings . remove ( oldname ) ; if ( oldBinding == null ) { throw new NameNotFoundException ( oldname + " not bound" ) ; } bindings . put ( newname , oldBinding ) ; }


Input: Binds a new name to the object bound to an old name and unbinds the old name . Both names are relative to this context . Any attributes associated with the old name become associated with the new name . Intermediate contexts of the old name are not changed . [CODESPLIT] public void rename ( Name oldname , Name newname ) throws NamingException { // Flat namespace; no federation; just call string version rename ( oldname . toString ( ) , newname . toString ( ) ) ; }


Input: Enumerates the names bound in the named context along with the class names of objects bound to them . The contents of any subcontexts are not included . If a binding is added to or removed from this context its effect on an enumeration previously returned is undefined . [CODESPLIT] public NamingEnumeration list ( String name ) throws NamingException { if ( "" . equals ( name ) ) { // listing this context return new FlatNames ( bindings . keys ( ) ) ; } // Perhaps `name' names a context Object target = lookup ( name ) ; if ( target instanceof Context ) { return ( ( Context ) target ) . list ( "" ) ; } throw new NotContextException ( name + " cannot be listed" ) ; }


Input: Enumerates the names bound in the named context along with the objects bound to them . The contents of any subcontexts are not included . [CODESPLIT] public NamingEnumeration listBindings ( String name ) throws NamingException { if ( "" . equals ( name ) ) { // listing this context return new FlatBindings ( bindings . keys ( ) ) ; } // Perhaps `name' names a context Object target = lookup ( name ) ; if ( target instanceof Context ) { return ( ( Context ) target ) . listBindings ( "" ) ; } throw new NotContextException ( name + " cannot be listed" ) ; }


Input: Composes the name of this context with a name relative to this context . Given a name ( name ) relative to this context and the name ( prefix ) of this context relative to one of its ancestors this method returns the composition of the two names using the syntax appropriate for the naming system ( s ) involved . That is if name names an object relative to this context the result is the name of the same object but relative to the ancestor context . None of the names may be null . [CODESPLIT] public String composeName ( String name , String prefix ) throws NamingException { Name result = composeName ( new CompositeName ( name ) , new CompositeName ( prefix ) ) ; return result . toString ( ) ; }


Input: Adds a new environment property to the environment of this context . If the property already exists its value is overwritten . See class description for more details on environment properties . [CODESPLIT] public Object addToEnvironment ( String propName , Object propVal ) { if ( myEnv == null ) { myEnv = new Hashtable ( 5 , 0.75f ) ; } return myEnv . put ( propName , propVal ) ; }


Input: Removes an environment property from the environment of this context . See class description for more details on environment properties . [CODESPLIT] public Object removeFromEnvironment ( String propName ) { if ( myEnv == null ) { return null ; } return myEnv . remove ( propName ) ; }


Input: Repeatedly runs the garbage collector and finalization method of the JVM runtime system until the used memory count becomes stable or 500 iterations occur whichever happens soonest . If other threads are active then this method is not likely to work as the used memory count will continually be changing . [CODESPLIT] private static void runGCTillStable ( ) { // Possibly add another iteration in here to run this whole method 3 or 4 times. long usedMem1 = usedMemory ( ) ; long usedMem2 = Long . MAX_VALUE ; // Repeatedly garbage collection until the used memory count becomes stable, or 500 iterations occur. for ( int i = 0 ; ( usedMem1 < usedMem2 ) && ( i < 500 ) ; i ++ ) { // Force finalisation of all object pending finalisation. RUNTIME . runFinalization ( ) ; // Return unused memory to the heap. RUNTIME . gc ( ) ; // Allow other threads to run. Thread . currentThread ( ) . yield ( ) ; // Keep the old used memory count from the last iteration and get a fresh reading. usedMem2 = usedMem1 ; usedMem1 = usedMemory ( ) ; } }


Input: This is the high - level rule at some scope ( either the root document or within a rule set / mixin ) . Future : Imports [CODESPLIT] Rule Scope ( ) { return Sequence ( push ( new ScopeNode ( ) ) , ZeroOrMore ( FirstOf ( Declaration ( ) , MediaQuery ( ) , RuleSet ( ) , MixinReference ( ) , Sequence ( push ( new WhiteSpaceCollectionNode ( ) ) , Sp1Nodes ( ) ) ) , peek ( 1 ) . addChild ( pop ( ) ) ) ) ; }


Input: media type name Optional ( and ( Css property ) ) [CODESPLIT] Rule MediaType ( ) { return Sequence ( push ( new MediaTypeNode ( ) ) , MediaTypeName ( ) , peek ( 1 ) . addChild ( pop ( ) ) , FirstOf ( Sequence ( MediaTypeRestriction ( ) , peek ( 1 ) . addChild ( pop ( ) ) ) , Optional ( Ws0 ( ) , push ( new SpacingNode ( " " ) ) , peek ( 1 ) . addChild ( pop ( ) ) ) ) , peek ( 1 ) . addChild ( pop ( ) ) ) ; }


Input: Sequence ( Whitespace and Whitespace ( Css Property ) ) [CODESPLIT] Rule MediaTypeRestriction ( ) { return Sequence ( push ( new MediaTypeRestriction ( ) ) , Ws0 ( ) , "and" , Ws0 ( ) , ' ' , Sequence ( Ident ( ) , peek ( ) . addChild ( new SimpleNode ( match ( ) ) ) , ' ' , peek ( ) . addChild ( new SimpleNode ( ":" ) ) , Optional ( Ws0 ( ) ) , peek ( ) . addChild ( new SpacingNode ( " " ) ) , ExpressionPhrase ( ) ) , ' ' , peek ( 1 ) . addChild ( pop ( ) ) ) ; }


Input: only Whitespace [CODESPLIT] Rule OnlyIndicator ( ) { return Sequence ( "only" , peek ( ) . addChild ( new SimpleNode ( match ( ) ) ) , peek ( ) . addChild ( new SimpleNode ( " " ) ) , Ws0 ( ) ) ; }


Input: ( Selectors { Ws0 / Class Ws0 Parameters Ws0 { Ws0 ) Scope Ws0 } Ws0 [CODESPLIT] Rule RuleSet ( ) { return Sequence ( FirstOf ( // Standard CSS rule set Sequence ( SelectorGroup ( ) , push ( new RuleSetNode ( pop ( ) ) ) , ' ' , Scope ( ) , peek ( 1 ) . addChild ( pop ( ) ) , Ws0 ( ) ) , // Mixin rule set, with possible arguments Sequence ( ClassSelectorGroup ( ) , push ( new RuleSetNode ( pop ( ) ) ) , Ws0 ( ) , Parameters ( ) , Ws0 ( ) , ' ' , Scope ( ) , peek ( 1 ) . addChild ( pop ( ) ) , peek ( 1 ) . addChild ( pop ( ) ) , Ws0 ( ) ) ) , ' ' , Ws0Nodes ( ) ) ; }


Input: ( Parameter Ws0 ( Ws0 Parameter ) * ) [CODESPLIT] Rule Parameters ( ) { return Sequence ( ' ' , Parameter ( ) , push ( new ParametersNode ( pop ( ) ) ) , Ws0 ( ) , ZeroOrMore ( ' ' , Ws0 ( ) , Parameter ( ) , peek ( 1 ) . addChild ( pop ( ) ) ) , ' ' , push ( new ScopeNode ( pop ( ) ) ) ) ; }


Input: Variable Ws0 : Ws0 ExpressionPhrase [CODESPLIT] Rule Parameter ( ) { return Sequence ( Variable ( ) , push ( new VariableDefinitionNode ( match ( ) ) ) , peek ( ) . setVisible ( ! isParserTranslationEnabled ( ) ) , Ws0 ( ) , ' ' , Ws0 ( ) , ExpressionPhrase ( ) , peek ( 1 ) . addChild ( new ExpressionGroupNode ( pop ( ) ) ) ) ; }


Input: SelectorGroup ; Ws0 / Class Arguments ; Ws0 [CODESPLIT] @ MemoMismatches Rule MixinReference ( ) { Var < String > name = new Var < String > ( ) ; return FirstOf ( // No arguments, reference an existing rule set's properties Sequence ( SelectorGroup ( ) , ' ' , resolveMixinReference ( NodeTreeUtils . getFirstChild ( ( InternalNode ) pop ( ) , SelectorNode . class ) . toString ( ) , null ) , Ws0Nodes ( ) ) , // Call a mixin, passing along some arguments Sequence ( Class ( ) , name . set ( match ( ) ) , Arguments ( ) , Ws0 ( ) , ' ' , resolveMixinReference ( name . get ( ) , ( ArgumentsNode ) pop ( ) ) , Ws0Nodes ( ) ) ) ; }


Input: Selector Ws0 ( Ws0 Selector ) * Ws0 [CODESPLIT] @ MemoMismatches Rule SelectorGroup ( ) { return Sequence ( Selector ( ) , push ( new SelectorGroupNode ( pop ( ) ) ) , Ws0Nodes ( ) , ZeroOrMore ( ' ' , Ws0Nodes ( ) , Selector ( ) , peek ( 1 ) . addChild ( pop ( ) ) ) , Ws0Nodes ( ) ) ; }


Input: SimpleSelector ( Combinator SimpleSelector ) * [CODESPLIT] Rule Selector ( ) { Var < SelectorSegmentNode > selectorSegmentNode = new Var < SelectorSegmentNode > ( ) ; return Sequence ( push ( new SelectorNode ( ) ) , // First selector segment may have a combinator (with nested rule sets) Optional ( SymbolCombinator ( ) ) , selectorSegmentNode . set ( new SelectorSegmentNode ( match ( ) ) ) , SimpleSelector ( selectorSegmentNode ) , selectorSegmentNode . get ( ) . setSimpleSelector ( match ( ) ) , peek ( ) . addChild ( selectorSegmentNode . getAndClear ( ) ) , // Additional selector segments must have a combinator ZeroOrMore ( Combinator ( ) , selectorSegmentNode . set ( new SelectorSegmentNode ( match ( ) ) ) , SimpleSelector ( selectorSegmentNode ) , selectorSegmentNode . get ( ) . setSimpleSelector ( match ( ) ) , peek ( ) . addChild ( selectorSegmentNode . getAndClear ( ) ) ) ) ; }


Input: ( Ident / Variable ) Ws0 : Ws0 ExpressionPhrase ( Ws0 Ws0 ExpressionPhrase ) * Sp0 ( ; / Ws0 & } ) / Ident Ws0 : Ws0 ; [CODESPLIT] Rule Declaration ( ) { return FirstOf ( Sequence ( FirstOf ( Sequence ( PropertyName ( ) , push ( new PropertyNode ( match ( ) ) ) ) , Sequence ( Variable ( ) , push ( new VariableDefinitionNode ( match ( ) ) ) , peek ( ) . setVisible ( ! isParserTranslationEnabled ( ) ) ) ) , Ws0 ( ) , ' ' , Ws0 ( ) , push ( new ExpressionGroupNode ( ) ) , ExpressionPhrase ( ) , peek ( 1 ) . addChild ( pop ( ) ) , ZeroOrMore ( Ws0 ( ) , ' ' , Ws0Nodes ( ) , ExpressionPhrase ( ) , peek ( 1 ) . addChild ( pop ( ) ) ) , Sp0 ( ) , FirstOf ( ' ' , Sequence ( Ws0 ( ) , Test ( ' ' ) ) ) , peek ( 1 ) . addChild ( pop ( ) ) ) , // Empty rules are ignored Sequence ( Ident ( ) , push ( new PlaceholderNode ( ) ) , Ws0 ( ) , ' ' , Ws0 ( ) , ' ' ) ) ; }


Input: Expression ( Operator Expression ) + Future : Operations / Expression ( Ws1 Expression ) * Important? [CODESPLIT] Rule ExpressionPhrase ( ) { // Space-separated expressions return Sequence ( Expression ( ) , push ( new ExpressionPhraseNode ( pop ( ) ) ) , ZeroOrMore ( Ws1 ( ) , Expression ( ) , peek ( 1 ) . addChild ( pop ( ) ) ) , Optional ( Ws0 ( ) , Important ( ) , peek ( 1 ) . addChild ( pop ( ) ) ) ) ; }


Input: Ident Arguments [CODESPLIT] Rule Function ( ) { return Sequence ( Ident ( ) , push ( new FunctionNode ( match ( ) ) ) , Arguments ( ) , peek ( 1 ) . addChild ( pop ( ) ) ) ; }


Input: ( Ws0 ExpressionPhrase Ws0 ( Ws0 ExpressionPhrase Ws0 ) * ) / ( Ws0 ) [CODESPLIT] Rule Arguments ( ) { return FirstOf ( Sequence ( Ws0 ( ) , ' ' , Ws0 ( ) , ExpressionPhrase ( ) , push ( new ArgumentsNode ( new ExpressionGroupNode ( pop ( ) ) ) ) , Ws0 ( ) , ZeroOrMore ( ' ' , Ws0 ( ) , ExpressionPhrase ( ) , peek ( 1 ) . addChild ( new ExpressionGroupNode ( pop ( ) ) ) , Ws0 ( ) ) , ' ' ) , Sequence ( Ws0 ( ) , ' ' , Ws0 ( ) , ' ' , push ( new ArgumentsNode ( ) ) ) ) ; }


Input: Ex : progid : DXImageTransform . Microsoft . gradient ( startColorstr = [CODESPLIT] Rule FilterFunction ( ) { return Sequence ( Sequence ( "progid:" , OneOrMore ( FirstOf ( ' ' , Ident ( ) ) ) ) , push ( new FunctionNode ( match ( ) ) ) , FilterArguments ( ) , peek ( 1 ) . addChild ( pop ( ) ) ) ; }


Input: ( Ws0 FilterArgument Ws0 ( Ws0 FilterArgument Ws0 ) * ) / ( Ws0 ) [CODESPLIT] Rule FilterArguments ( ) { return FirstOf ( Sequence ( ' ' , Ws0 ( ) , FilterArgument ( ) , push ( new ArgumentsNode ( pop ( ) ) ) , Ws0 ( ) , ZeroOrMore ( ' ' , Ws0 ( ) , FilterArgument ( ) , peek ( 1 ) . addChild ( pop ( ) ) , Ws0 ( ) ) , ' ' ) , Sequence ( ' ' , Ws0 ( ) , ' ' , push ( new ArgumentsNode ( ) ) ) ) ; }


Input: Ex : startColorstr = [CODESPLIT] Rule FilterArgument ( ) { return Sequence ( Ident ( ) , push ( new FilterArgumentNode ( match ( ) ) ) , Ws0 ( ) , ' ' , Ws0 ( ) , Value ( ) , peek ( 1 ) . addChild ( pop ( ) ) ) ; }


Input: Any token used as a value in an expression Future : Accessors [CODESPLIT] Rule Value ( ) { return FirstOf ( Keyword ( ) , Literal ( ) , Function ( ) , VariableReference ( ) , URL ( ) , Font ( ) , AlphaFilter ( ) , ExpressionFunction ( ) , FilterFunction ( ) ) ; }


Input: url ( ( String / [ - _%$ / . & = : ; # + ?Alphanumeric ] + ) ) [CODESPLIT] Rule URL ( ) { return Sequence ( Sequence ( "url(" , Ws0 ( ) , FirstOf ( String ( ) , OneOrMore ( FirstOf ( AnyOf ( "-_%$/.&=:;#+?" ) , Alphanumeric ( ) ) ) ) , Ws0 ( ) , ' ' ) , push ( new SimpleNode ( match ( ) ) ) ) ; }


Input: alpha ( Ws0 opacity Ws0 = Ws0 Digit1 Ws0 ) [CODESPLIT] Rule AlphaFilter ( ) { return Sequence ( Sequence ( "alpha(" , Ws0 ( ) , "opacity" , Ws0 ( ) , ' ' , Ws0 ( ) , Digit1 ( ) , Ws0 ( ) , ' ' ) , push ( new SimpleNode ( match ( ) ) ) ) ; }


Input: expression ( ( ! ( ) Ws0 [ ; } ] ) . ) * ) ; [CODESPLIT] Rule ExpressionFunction ( ) { return Sequence ( Sequence ( "expression(" , ZeroOrMore ( TestNot ( ' ' , Ws0 ( ) , AnyOf ( ";}" ) ) , ANY ) , ' ' ) , push ( new SimpleNode ( match ( ) ) ) ) ; }


Input: Ident &Delimiter [CODESPLIT] Rule Keyword ( ) { return Sequence ( Sequence ( Ident ( ) , Test ( Delimiter ( ) ) ) , push ( new SimpleNode ( match ( ) ) ) ) ; }


Input: Tokens that don t need to evaluated [CODESPLIT] Rule Literal ( ) { return Sequence ( FirstOf ( Color ( ) , MultiDimension ( ) , Dimension ( ) , String ( ) ) , push ( new SimpleNode ( match ( ) ) ) ) ; }


Input: Alpha [ - Alphanumeric ] * &Delimiter / String [CODESPLIT] Rule Font ( ) { return Sequence ( FirstOf ( Sequence ( Alpha ( ) , ZeroOrMore ( FirstOf ( ' ' , Alphanumeric ( ) ) ) , Test ( Delimiter ( ) ) ) , String ( ) ) , push ( new SimpleNode ( match ( ) ) ) ) ; }


Input: Ex : hello / hello [CODESPLIT] Rule String ( ) { return FirstOf ( Sequence ( ' ' , ZeroOrMore ( TestNot ( ' ' ) , ANY ) , ' ' ) , Sequence ( ' ' , ZeroOrMore ( TestNot ( ' ' ) , ANY ) , ' ' ) ) ; }


Input: - ? Digit * . Digit + / - ? Digit + [CODESPLIT] Rule Number ( ) { return FirstOf ( Sequence ( Optional ( ' ' ) , Digit0 ( ) , ' ' , Digit1 ( ) ) , Sequence ( Optional ( ' ' ) , Digit1 ( ) ) ) ; }


Input: Ex : 0099dd / 09d [CODESPLIT] Rule RGB ( ) { return FirstOf ( Sequence ( Hex ( ) , Hex ( ) , Hex ( ) , Hex ( ) , Hex ( ) , Hex ( ) ) , Sequence ( Hex ( ) , Hex ( ) , Hex ( ) ) ) ; }


Input: \ [ 0 - 9a - fA - F ] { 1 6 } wc? [CODESPLIT] Rule Unicode ( ) { return Sequence ( ' ' , Hex ( ) , Optional ( Hex ( ) , Optional ( Hex ( ) , Optional ( Hex ( ) , Optional ( Hex ( ) , Optional ( Hex ( ) ) ) ) ) ) , Optional ( Whitespace ( ) ) ) ; }


Input: unicode | \ [ ^ \ x0 - \ x1F ] [CODESPLIT] Rule Escape ( ) { return Sequence ( Test ( ' ' ) , // for performance FirstOf ( Unicode ( ) , Sequence ( ' ' , Sequence ( TestNot ( CharRange ( ( char ) 0 , ( char ) 31 ) ) , ANY ) ) ) ) ; }


Input: Locates the referenced mixin in one of the scope nodes on the stack . If found the mixin s scope is cloned and placed onto the stack in place of the mixin reference . Additionally any arguments are applied to the mixin s scope . [CODESPLIT] boolean resolveMixinReference ( String name , ArgumentsNode arguments ) { if ( ! isParserTranslationEnabled ( ) ) { return push ( new PlaceholderNode ( new SimpleNode ( name ) ) ) ; } // Walk down the stack, looking for a scope node that knows about a given rule set for ( Node node : getContext ( ) . getValueStack ( ) ) { if ( ! ( node instanceof ScopeNode ) ) { continue ; } ScopeNode scope = ( ScopeNode ) node ; RuleSetNode ruleSet = scope . getRuleSet ( name ) ; if ( ruleSet == null ) { continue ; } // Get the scope of the rule set we located and call it as a mixin ScopeNode ruleSetScope = NodeTreeUtils . getFirstChild ( ruleSet , ScopeNode . class ) . callMixin ( name , arguments ) ; return push ( ruleSetScope ) ; } // Record error location throw new UndefinedMixinException ( name ) ; }


Input: Looks for a variable definition that matches the reference in the scope nodes on the stack . If found a reference node that can repeat this lookup later is placed on the stack not the current value itself . This is done because the value may change if the variable reference is inside a mixin . [CODESPLIT] boolean pushVariableReference ( String name ) { if ( ! isParserTranslationEnabled ( ) ) { return push ( new SimpleNode ( name ) ) ; } // Walk down the stack, looking for a scope node that knows about a given variable for ( Node node : getContext ( ) . getValueStack ( ) ) { if ( ! ( node instanceof ScopeNode ) ) { continue ; } // Ensure that the variable exists ScopeNode scope = ( ScopeNode ) node ; if ( ! scope . isVariableDefined ( name ) ) { continue ; } return push ( new VariableReferenceNode ( name ) ) ; } // Record error location throw new UndefinedVariableException ( name ) ; }


Input: 记录完善的异常日志信息 ( 包括堆栈信息 ) [CODESPLIT] public static String recordStackTraceMsg ( Exception e ) { StringWriter stringWriter = new StringWriter ( ) ; PrintWriter writer = new PrintWriter ( stringWriter ) ; e . printStackTrace ( writer ) ; StringBuffer buffer = stringWriter . getBuffer ( ) ; return buffer . toString ( ) ; }


Input: Updates the maximum row height for a row of the data table . [CODESPLIT] public void setMaxRowHeight ( int row , int height ) { Integer previousValue = maxRowSizes . get ( row ) ; if ( previousValue == null ) { maxRowSizes . put ( row , height ) ; } else if ( previousValue < height ) { maxRowSizes . put ( row , height ) ; } }


Input: { [CODESPLIT] public String put ( Integer col , Integer row , String value ) { maxColumns = ( col > maxColumns ) ? col : maxColumns ; maxRows = ( row > maxRows ) ? row : maxRows ; updateMaxColumnWidth ( col , value . length ( ) ) ; String result = grid . put ( ( long ) col , ( long ) row , value ) ; updateListeners ( col , row ) ; return result ; }


Input: { [CODESPLIT] public String get ( Integer col , Integer row ) { return grid . get ( ( long ) col , ( long ) row ) ; }


Input: { [CODESPLIT] public String remove ( Integer col , Integer row ) { String result = grid . remove ( ( long ) col , ( long ) row ) ; updateListeners ( col , row ) ; return result ; }


Input: { [CODESPLIT] public int getMaxColumnSize ( int col ) { Integer result = maxColumnSizes . get ( col ) ; return ( result == null ) ? 0 : result ; }


Input: { [CODESPLIT] public void labelCell ( String label , int col , int row ) { cellLabels . put ( label , new Pair < Integer , Integer > ( col , row ) ) ; }


Input: Notifies all interested listeners of an update to this model . [CODESPLIT] protected void updateListeners ( int col , int row ) { TextTableEvent event = new TextTableEvent ( this , row , col ) ; for ( TextTableListener listener : listeners ) { listener . changedUpdate ( event ) ; } }


Input: Updates the maximum column width for a column of the data table . [CODESPLIT] private void updateMaxColumnWidth ( int column , int width ) { Integer previousValue = maxColumnSizes . get ( column ) ; if ( previousValue == null ) { maxColumnSizes . put ( column , width ) ; } else if ( previousValue < width ) { maxColumnSizes . put ( column , width ) ; } }


Input: Updates the current page or index offset of a paged list in the session scope . [CODESPLIT] public ActionForward executeWithErrorHandling ( ActionMapping mapping , ActionForm form , HttpServletRequest request , HttpServletResponse response , ActionErrors errors ) throws Exception { // Get a reference to the session. HttpSession session = request . getSession ( false ) ; // Extract the page form. DynaActionForm pageForm = ( DynaActionForm ) form ; log . fine ( "pageForm = " + pageForm ) ; // Get the paged list object from the session. String listingVarName = pageForm . getString ( VAR_NAME_PARAM ) ; log . fine ( "listingVarName = " + listingVarName ) ; PagedList pagedList = ( PagedList ) session . getAttribute ( listingVarName ) ; // Set its current page. pagedList . setCurrentPage ( ( Integer ) pageForm . get ( NUMBER_PARAM ) ) ; // Set its index offset if one is specified. Integer index = ( Integer ) pageForm . get ( INDEX_PARAM ) ; if ( index != null ) { pagedList . setCurrentIndex ( index ) ; } // Forward to the success location. return mapping . findForward ( SUCCESS_FORWARD ) ; }


Input: { @inheritDoc } [CODESPLIT] public void compile ( Sentence < Clause > clauseSentence ) throws SourceCodeException { Clause clause = clauseSentence . getT ( ) ; PrologCompiledClause result = new PrologCompiledClause ( clause . getHead ( ) , clause . getBody ( ) ) ; // Create stack frame slots for all variables in a program. if ( ! clause . isQuery ( ) ) { StackVariableTransform stackVariableTransform = new StackVariableTransform ( 0 , result ) ; result = ( PrologCompiledClause ) result . acceptTransformer ( stackVariableTransform ) ; // Set the required stack frame size on the compiled clause. result . setStackSize ( stackVariableTransform . offset ) ; } // Apply the built-in transformation to map any built-ins to their implementations. TermTransformer builtInTransformation = new BuiltInExpressionTransform ( interner ) ; result = ( PrologCompiledClause ) result . acceptTransformer ( builtInTransformation ) ; // Return the compiled version of the clause. if ( clause . isQuery ( ) ) { observer . onQueryCompilation ( result ) ; } else { observer . onCompilation ( result ) ; } }


Input: Applies a built - in replacement transformation to functors . If the functor matches built - in a { @link BuiltInFunctor } is created with a mapping to the functors built - in implementation and the functors arguments are copied into this new functor . If the functor does not match a built - in it is returned unmodified . [CODESPLIT] public Functor transform ( Functor functor ) { FunctorName functorName = interner . getFunctorFunctorName ( functor ) ; if ( builtInExpressions . containsKey ( functorName ) ) { Class < ? extends Functor > builtInExpressionClass = builtInExpressions . get ( functorName ) ; return ReflectionUtils . newInstance ( ReflectionUtils . getConstructor ( builtInExpressionClass , new Class [ ] { Integer . TYPE , Term [ ] . class } ) , new Object [ ] { functor . getName ( ) , functor . getArguments ( ) } ) ; } else { return functor ; } }


Input: Returns a new node based on a successor of this node . This new node will also be a HeuristicSearchNode . [CODESPLIT] public HeuristicSearchNode < O , T > makeNode ( Successor successor ) throws SearchNotExhaustiveException { HeuristicSearchNode < O , T > node = ( HeuristicSearchNode < O , T > ) super . makeNode ( successor ) ; // Make sure the new node has a reference to the heuristic evaluator node . heuristic = this . heuristic ; // Compute h for the new node node . computeH ( ) ; return node ; }


Input: Processes the action providing default error handling . Implementation should override this method to provide their own error handling if the default is not to be used . [CODESPLIT] public ActionForward execute ( ActionMapping mapping , ActionForm form , HttpServletRequest request , HttpServletResponse response ) throws IOException , ServletException { log . fine ( "ActionForward perform(ActionMapping, ActionForm, HttpServletRequest, HttpServletResponse): called" ) ; // Build an ActionErrors object to hold any errors that occurr ActionErrors errors = new ActionErrors ( ) ; // Create reference to the session HttpSession session = request . getSession ( ) ; // Use a try block to catch any errors that may occur try { return executeWithErrorHandling ( mapping , form , request , response , errors ) ; } // Catch all exceptions here. This will forward to the error page in the event of // any exception that falls through to this top level handler. // Don't catch Throwable here as Errors should fall through to the JVM top level and will result in // termination of the application. catch ( Exception t ) { log . log ( Level . WARNING , "Caught a Throwable" , t ) ; // Don't Forward the error to the error handler to interpret it as a Struts error as the exception will // automatically be translated by the error page. // @todo Could add code here to check if there is a 'error' forward page defined. If there is then call // the error handler to translate the throwable into Struts errors and then forward to the 'error' page. // This would mean that the error page defined in web.xml would be the default unless an action explicitly // defined an alternative 'error' forward. // handleErrors(t, errors); // Save all the error messages in the request so that they will be displayed // request.setAttribute(Action.ERROR_KEY, errors); // Rethrow the error as a ServletException here to cause forwarding to error page defined in web.xml throw new WrappedStrutsServletException ( t ) ; } }


Input: { [CODESPLIT] public void compile ( Sentence < Clause > sentence ) throws SourceCodeException { Clause clause = sentence . getT ( ) ; substituteBuiltIns ( clause ) ; initialiseSymbolTable ( clause ) ; topLevelCheck ( clause ) ; if ( observer != null ) { if ( clause . isQuery ( ) ) { observer . onQueryCompilation ( sentence ) ; } else { observer . onCompilation ( sentence ) ; } } }


Input: Substitutes built - ins within a clause with their built - in definitions . [CODESPLIT] private void substituteBuiltIns ( Term clause ) { TermWalker walk = TermWalkers . positionalWalker ( new BuiltInTransformVisitor ( interner , symbolTable , null , builtInTransform ) ) ; walk . walk ( clause ) ; }


Input: Runs a symbol key traverser over the clause to be compiled to ensure that all of its terms and sub - terms have their symbol keys initialised . [CODESPLIT] private void initialiseSymbolTable ( Term clause ) { // Run the symbol key traverser over the clause, to ensure that all terms have their symbol keys correctly // set up. SymbolKeyTraverser symbolKeyTraverser = new SymbolKeyTraverser ( interner , symbolTable , null ) ; symbolKeyTraverser . setContextChangeVisitor ( symbolKeyTraverser ) ; TermWalker symWalker = new TermWalker ( new DepthFirstBacktrackingSearch < Term , Term > ( ) , symbolKeyTraverser , symbolKeyTraverser ) ; symWalker . walk ( clause ) ; }


Input: Finds and marks all functors within the clause that are considered to be top - level . [CODESPLIT] private void topLevelCheck ( Term clause ) { TermWalker walk = TermWalkers . positionalWalker ( new TopLevelCheckVisitor ( interner , symbolTable , null ) ) ; walk . walk ( clause ) ; }


Input: { [CODESPLIT] public SizeableLinkedList < WAMInstruction > compileBodyCall ( Functor expression , boolean isFirstBody , boolean isLastBody , boolean chainRule , int permVarsRemaining ) { SizeableLinkedList < WAMInstruction > instructions = new SizeableLinkedList < WAMInstruction > ( ) ; if ( isFirstBody ) { instructions . add ( new WAMInstruction ( NeckCut ) ) ; } else { Integer cutLevelVarAllocation = ( Integer ) defaultBuiltIn . getSymbolTable ( ) . get ( CutLevelVariable . CUT_LEVEL_VARIABLE . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_ALLOCATION ) ; instructions . add ( new WAMInstruction ( Cut , ( byte ) ( cutLevelVarAllocation & 0xff ) ) ) ; } return instructions ; }


Input: Pretty prints a term relative to the symbol namings provided by the specified interner . [CODESPLIT] private String listToString ( VariableAndFunctorInterner interner , boolean isFirst , boolean printVarName , boolean printBindings ) { String result = "" ; if ( isFirst ) { result += "[" ; } result += arguments [ 0 ] . toString ( interner , printVarName , printBindings ) ; Term consArgument = arguments [ 1 ] . getValue ( ) ; if ( consArgument instanceof Cons ) { result += ", " + ( ( Cons ) consArgument ) . listToString ( interner , false , printVarName , printBindings ) ; } if ( isFirst ) { result += "]" ; } return result ; }


Input: { [CODESPLIT] public void clear ( ) { // Clea all fields and records from the table. fieldMap = new LinkedHashMap < L , CircularArrayMap < E > > ( ) ; hashFunction = new SequentialCuckooFunction < CompositeKey < K > > ( ) ; }


Input: { [CODESPLIT] public boolean containsKey ( K primaryKey , L secondaryKey ) { // Check that the field exists in the table. CircularArrayMap < E > field = fieldMap . get ( secondaryKey ) ; if ( field == null ) { return false ; } // Check that the symbol exists in the table. CompositeKey < K > compositeKey = new CompositeKey < K > ( parentSequenceKey , primaryKey ) ; SymbolTableImpl < K , L , E > nextParentScope = parentScope ; while ( true ) { if ( hashFunction . containsKey ( compositeKey ) ) { break ; } if ( nextParentScope != null ) { compositeKey = new CompositeKey ( nextParentScope . parentSequenceKey , primaryKey ) ; nextParentScope = nextParentScope . parentScope ; } else { return false ; } } // Calculate the symbols index in the table, and use it to check if a value for that field exists. E value = field . get ( hashFunction . apply ( compositeKey ) ) ; return value != null ; }


Input: { [CODESPLIT] public E put ( K primaryKey , L secondaryKey , E value ) { // Create the field column for the secondary key, if it does not already exist. CircularArrayMap < E > field = fieldMap . get ( secondaryKey ) ; if ( field == null ) { field = new CircularArrayMap < E > ( DEFAULT_INITIAL_FIELD_SIZE ) ; fieldMap . put ( secondaryKey , field ) ; } // Create the mapping for the symbol if it does not already exist. Integer index = hashFunction . apply ( new CompositeKey < K > ( parentSequenceKey , primaryKey ) ) ; // Insert the new value for the field into the field map. E oldValue = field . put ( index , value ) ; count ++ ; return oldValue ; }


Input: { [CODESPLIT] public E remove ( K primaryKey , L secondaryKey ) { CompositeKey < K > compositeKey = new CompositeKey < K > ( parentSequenceKey , primaryKey ) ; // Check that the symbol exists in the table, and return null if not. if ( ! hashFunction . containsKey ( compositeKey ) ) { return null ; } // Check that the field for the secondary key exists, and return null if not. CircularArrayMap < E > field = fieldMap . get ( secondaryKey ) ; if ( field == null ) { return null ; } // Calculate the symbols index in the table, and use it to fetch remove a value for the field if one exists. E oldValue = field . remove ( hashFunction . apply ( compositeKey ) ) ; // Check if the fields size has been reduced to zero, in which case purge that whole field from the symbol // table. if ( field . isEmpty ( ) ) { fieldMap . remove ( secondaryKey ) ; } // Check if an item was really removed from the table, and decrement the size count if so. if ( oldValue != null ) { count -- ; } return oldValue ; }


Input: { [CODESPLIT] public SymbolTable < K , L , E > enterScope ( K key ) { // Create an entry in the sequence function for the key, if one does not already exist. int scopeSequenceKey = hashFunction . apply ( new CompositeKey < K > ( parentSequenceKey , key ) ) ; // Create a new child table for the symbol within this table at depth one greater than this. return new SymbolTableImpl < K , L , E > ( this , fieldMap , hashFunction , depth , scopeSequenceKey ) ; }


Input: { [CODESPLIT] public SymbolKey getSymbolKey ( K key ) { // Create an entry in the sequence function for the key, if one does not already exist. int scopeSequenceKey = hashFunction . apply ( new CompositeKey < K > ( parentSequenceKey , key ) ) ; return new SymbolKeyImpl ( scopeSequenceKey ) ; }


Input: { [CODESPLIT] public E get ( SymbolKey key , L secondaryKey ) { // Extract the sequence key from the symbol key. int sequenceKey = ( ( SymbolKeyImpl ) key ) . sequenceKey ; // Check that the field for the secondary key exists, and return null if not. CircularArrayMap < E > field = fieldMap . get ( secondaryKey ) ; if ( field == null ) { return null ; } // Look up the value directly by its sequence key. return field . get ( sequenceKey ) ; }


Input: { [CODESPLIT] public E put ( SymbolKey key , L secondaryKey , E value ) { // Extract the sequence key from the symbol key. int sequenceKey = ( ( SymbolKeyImpl ) key ) . sequenceKey ; // Create the field column for the secondary key, if it does not already exist. CircularArrayMap < E > field = fieldMap . get ( secondaryKey ) ; if ( field == null ) { field = new CircularArrayMap < E > ( DEFAULT_INITIAL_FIELD_SIZE ) ; fieldMap . put ( secondaryKey , field ) ; } // Insert the new value for the field into the field map. E oldValue = field . put ( sequenceKey , value ) ; count ++ ; return oldValue ; }


Input: { [CODESPLIT] public void clearUpToLowMark ( L secondaryKey ) { CircularArrayMap < E > field = fieldMap . get ( secondaryKey ) ; if ( field != null ) { field . clearUpToLowMark ( ) ; } }


Input: ---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Override public void setValue ( String value ) { checkArgument ( ! UNCHECKED_VALUE . equals ( value ) , "Cannot uncheck radio control" ) ; getForm ( ) . elements ( ) . select ( byControlGroup ( ) ) . removeAttr ( "checked" ) ; super . setValue ( value ) ; }


Input: { @inheritDoc } [CODESPLIT] public void open ( ) { // Set up colors. componentFactory . setColorScheme ( new DarkColorScheme ( componentFactory . getColorFactory ( ) ) ) ; // Build the main window frame. mainWindow = componentFactory . createMainWindow ( ) ; mainWindow . showMainWindow ( ) ; // Create and initialize the register monitor. registerMonitorController = new RegisterMonitorController ( componentFactory , mainWindow ) ; registerMonitorController . open ( ) ; // Create and initialize the memory layout monitor. memoryLayoutMonitorController = new MemoryLayoutMonitorController ( componentFactory , mainWindow ) ; memoryLayoutMonitorController . open ( ) ; // Create and initialize the byte code view and breakpoint monitor. codeStepController = new CodeStepController ( componentFactory , mainWindow ) ; codeStepController . open ( ) ; // Build the top-level machine monitor, hooking it up to the child components. RegisterSetMonitor registerMonitor = registerMonitorController . getRegisterMonitor ( ) ; MemoryLayoutMonitor layoutMonitor = memoryLayoutMonitorController . getLayoutMonitor ( ) ; BreakpointMonitor breakpointMonitor = codeStepController . getBreakpointMonitor ( ) ; ByteCodeMonitor byteCodeMonitor = codeStepController . getByteCodeMonitor ( ) ; machineMonitor = new MachineMonitor ( registerMonitor , layoutMonitor , breakpointMonitor , byteCodeMonitor ) ; }


Input: Evaluates the arithmetic comparison on its two numeric arguments . [CODESPLIT] protected boolean evaluate ( NumericType firstNumber , NumericType secondNumber ) { // If either of the arguments is a real number, then use real number arithmetic, otherwise use integer arithmetic. if ( firstNumber . isInteger ( ) && secondNumber . isInteger ( ) ) { return firstNumber . intValue ( ) < secondNumber . intValue ( ) ; } else { return firstNumber . doubleValue ( ) < secondNumber . doubleValue ( ) ; } }


Input: Makes a transaction from the Initial state to the Running state or no transition if the current state is not Initial . [CODESPLIT] public void running ( ) { try { stateLock . writeLock ( ) . lock ( ) ; if ( state == State . Initial ) { state = State . Running ; stateChange . signalAll ( ) ; } } finally { stateLock . writeLock ( ) . unlock ( ) ; } }


Input: Makes a transaction from the Running state to the Shutdown state or no transition if the current state is not Running . [CODESPLIT] public void terminating ( ) { try { stateLock . writeLock ( ) . lock ( ) ; if ( state == State . Running ) { state = State . Shutdown ; stateChange . signalAll ( ) ; } } finally { stateLock . writeLock ( ) . unlock ( ) ; } }


Input: Makes a transaction from the Running or Shutdown state to the Terminated state or no transition if the current state is not Running or Shutdown . [CODESPLIT] public void terminated ( ) { try { stateLock . writeLock ( ) . lock ( ) ; if ( ( state == State . Shutdown ) || ( state == State . Running ) ) { state = State . Terminated ; stateChange . signalAll ( ) ; } } finally { stateLock . writeLock ( ) . unlock ( ) ; } }


Input: { [CODESPLIT] public boolean awaitTermination ( long timeout , TimeUnit unit ) throws InterruptedException { try { stateLock . writeLock ( ) . lock ( ) ; while ( state != State . Terminated ) { if ( ! stateChange . await ( timeout , unit ) ) { return false ; } } } finally { stateLock . writeLock ( ) . unlock ( ) ; } return true ; }


Input: { [CODESPLIT] public void addListener ( L listener ) { // Ensure update to the list, and rebuilding the active array happens atomically. synchronized ( listenersLock ) { listeners . add ( listener ) ; activeListeners = new ArrayList < L > ( listeners ) ; } }


Input: { [CODESPLIT] public void removeListener ( L listener ) { // Ensure update to the list, and rebuilding the active array happens atomically. synchronized ( listenersLock ) { listeners . remove ( listener ) ; activeListeners = new ArrayList < L > ( listeners ) ; } }


Input: { [CODESPLIT] public void createContinuationStates ( ResolutionState state ) { BuiltInFunctor nextGoal = state . getGoalStack ( ) . peek ( ) ; state . createContinuationStatesForGoal ( nextGoal ) ; }


Input: Inserts the specified element into this heap . [CODESPLIT] public boolean offer ( E o ) { // Make a new node out of the new data element. Node newNode = new Node ( o ) ; // Check if there is already a minimum element. if ( minNode != null ) { // There is already a minimum element, so add this new element to its right. newNode . next = minNode . next ; newNode . prev = minNode ; minNode . next . prev = newNode ; minNode . next = newNode ; // Compare the new element with the minimum and update the minimum if neccessary. updateMinimum ( newNode ) ; } // There is not already a minimum element. else { // Update the new element previous and next references to refer to itself so that it forms a doubly linked // list with only one element. This leaves the data structure in a suitable condition for adding more // elements. newNode . next = newNode ; newNode . prev = newNode ; // Set the minimum element to be the new data element. minNode = newNode ; } // Increment the count of data elements in this collection. size ++ ; // Return true to indicate that the new data element was accepted into the heap. return true ; }


Input:
Retrieves and removes the ( head ) minimum element of this heap or null if this heap is empty . [CODESPLIT] public E poll ( ) { // Check if there is only one element in the heap. if ( size == 1 ) { E result = minNode . element ; // Set the minimum to null. minNode = null ; // Decrease the count of elements in the heap. size -- ; return result ; } // Check that there is a minimum element to return. else if ( minNode != null ) { // Get the minimum value that is to be returned. E result = minNode . element ; // Promote the minimum nodes children into the root list but don't update their parent references. Updating // their parent references will be done later. if ( minNode . degree > 0 ) { insertNodes ( minNode , minNode . child ) ; } // Cut the minimum node out of the root list and update the minimum to be old minimums next node. This // node may not really be the minimum but it is taken to be the initial candidate for a new minimum. The // real minimum will be scanned for later. minNode . next . prev = minNode . prev ; minNode . prev . next = minNode . next ; minNode = minNode . next ; // The consolidation process will merge all the binomial trees of the same order until there are none // of duplicate size left. As each binomial tree of order k, Bk, holds 2^k nodes the biggest tree // possible for a heap of n nodes will be log to the base 2 of the next biggest power of 2 above or // equal to n. The next section of code creates an array with this many elements, indexed by the order // of the binomial tree, that is used to keep track of what tree orders currently exist during the // consolidation process. Node [ ] tree = ( Node [ ] ) Array . newInstance ( minNode . getClass ( ) , ceilingLog2 ( size - 1 ) + 1 ) ; // Loop through the root list, setting parent references to null and consolidating the remainder of the heap // into binomial trees. The loop begins at the next node after the min node and finishes on the min node // itself. This means that the min node is always the very last in the root list to be examined and // consolidated ensuring that it cannot have been removed from the root list before the loop gets to it. The // terminal min node is explicitly referenced because the consolidation process will update the min node // during the loop. Node nextNode = null ; Node nextNextNode = minNode . next ; Node terminalNode = minNode ; do { // Move on to the next node. nextNode = nextNextNode ; // Work out what the next next node will be at the start of the loop as manipulations durings // the loop may override the next node reference of the current next node. nextNextNode = nextNode . next ; // Update parent references to null. nextNode . parent = null ; // Update the minimum if the current root list element is smaller than the current best candidate. updateMinimum ( nextNode ) ; // Consolidate the remainder of the heap into binomial trees by merging duplicate trees of equal size. // Loop until no tree with the same size as the current one exists. int degree = nextNode . degree ; Node parentNode = nextNode ; while ( tree [ degree ] != null ) { // Clear the binomial tree of this size from the tree array as it is about to be merged with the // current node and a new tree of twice the size created. Node mergeNode = tree [ degree ] ; tree [ degree ] = null ; // Compare the roots of the two trees to be merged to decide which is the smaller and should form // the single root of the merged tree. if ( compare ( mergeNode , parentNode ) < 0 ) { // Swap the two nodes. Node temp = mergeNode ; mergeNode = parentNode ; parentNode = temp ; } // Cut the tree rooted by the larger root node from the root list. mergeNode . next . prev = mergeNode . prev ; mergeNode . prev . next = mergeNode . next ; mergeNode . next = mergeNode ; mergeNode . prev = mergeNode ; // Paste the tree rooted by the larger root node into the tree with the smaller root node. mergeNode . parent = parentNode ; // Check if the smaller node (the parent) already has some children. if ( parentNode . child != null ) { // Stitch the larger node into the circular doubly linked list of children. insertNodes ( parentNode . child , mergeNode ) ; // Update all the parent references of the newly added children. } // The smaller node does not already have children. else { // Set the larger node (of degree 1) as its first child. parentNode . child = mergeNode ; // Make sure the child node forms a doubly linked list with itself. mergeNode . next = mergeNode ; mergeNode . prev = mergeNode ; } // Bump up by one the order of the smaller root node to which the other tree of equal size was // added. parentNode . degree ++ ; // Continue the scan for duplicate trees on the next larger degree. degree ++ ; } tree [ degree ] = parentNode ; } while ( nextNode != terminalNode ) ; /*
             * String out = "At End: ["; for (int i = 0; i < tree.length; i++) out += (i == tree.length - 1) ? tree[i] :
             * tree[i] + ", "; out += "]"; log.info(out);
             */ // Decrease the count of elements in the heap. size -- ; // Return the minimum element. return result ; } // There is no minimum element so return null. else { return null ; } }


Input: Calculates the smallest integer value m such that m^2 > = n . The ceiling log2 of n . [CODESPLIT] private static int ceilingLog2 ( int n ) { int oa ; int i ; int b ; oa = n ; b = 32 / 2 ; i = 0 ; while ( b != 0 ) { i = ( i << 1 ) ; if ( n >= ( 1 << b ) ) { n /= ( 1 << b ) ; i = i | 1 ; } else { n &= ( 1 << b ) - 1 ; } b /= 2 ; } if ( ( 1 << i ) == oa ) { return i ; } else { return i + 1 ; } }


Input: Compares the specified node with the minimum and updates the minimum if neccessary . If a comparator was used to create this heap then this comparator is used to perform the comparison . If no comparator was set then the natural ordering of the element type is used . The element must implement the Comparable interface to support a natural ordering . If it does not there will be a class cast exception thrown . [CODESPLIT] private void updateMinimum ( Node node ) { // Check if a comparator was set. if ( entryComparator != null ) { // Use the comparator to compare the candidate new minimum with the current one and check if the new one // should be set. if ( entryComparator . compare ( node . element , minNode . element ) < 0 ) { // Update the minimum node. minNode = node ; } } // No comparator was set so use the natural ordering. else { // Cast the candidate new minimum element into a Comparable and compare it with the existing minimum // to check if the new one should be set. if ( ( ( Comparable ) node . element ) . compareTo ( minNode . element ) < 0 ) { // Update the minimum node. minNode = node ; } } }


Input: Compares two heap nodes . The comparison performed is dependant on whether a comparator has been set or the natural ordering is to be used . [CODESPLIT] private int compare ( Node node1 , Node node2 ) { // Check if a comparator was set. if ( entryComparator != null ) { // Use the comparator to compare. return entryComparator . compare ( node1 . element , node2 . element ) ; } // No comparator was set so use the natural ordering. else { // Cast one of the elements into a Comparable and compare it with the other. return ( ( Comparable ) node1 . element ) . compareTo ( node2 . element ) ; } }


Input: Inserts a single node or a circular doubly linked list of nodes into a list next to the specified node . I does not matter if the specified nodes are singletons or part of a chain as they will be correctly linked in in either case so long as their prev and next references form a loop with themselves . [CODESPLIT] private void insertNodes ( Node node , Node newNode ) { // Keep a reference to the next node in the node's chain as this will be overwritten when attaching the node // or chain into the root list. Node oldNodeNext = newNode . next ; // Break open the node's chain and attach it into the root list. newNode . next . prev = node ; newNode . next = node . next ; // Break open the root list chain and attach it to the new node or chain. node . next . prev = newNode ; node . next = oldNodeNext ; }


Input: Pauses any calling thread until { [CODESPLIT] public void pause ( ) { try { lock . lock ( ) ; try { released . await ( ) ; } catch ( InterruptedException e ) { // Exception set to null as compensation action of returning immediately with current thread interrupted // is taken. e = null ; Thread . currentThread ( ) . interrupt ( ) ; return ; } } finally { lock . unlock ( ) ; } }


Input: Restarts the sweep alogirithm . Useful after a kill has stopped it . [CODESPLIT] public void restart ( ) { // Clear the sweep thread kill flag. sweepThreadKillFlag = false ; // Start the sweep thread running with low priority. cacheSweepThread = new Thread ( ) { public void run ( ) { sweep ( ) ; } } ; cacheSweepThread . setPriority ( Thread . MIN_PRIORITY ) ; cacheSweepThread . start ( ) ; }


Input: Returns the value to which this map maps the specified key . Returns <tt > null< / tt > if the map contains no mapping for this key . A return value of <tt > null< / tt > does not <i > necessarily< / i > indicate that the map contains no mapping for the key ; it s also possible that the map explicitly maps the key to <tt > null< / tt > . The <tt > containsKey< / tt > operation may be used to distinguish these two cases . [CODESPLIT] public Object get ( Object key ) { // Synchronize on the cache to ensure its integrity in a multi-threaded environment. synchronized ( cache ) { // Try to extract the matching element as an ElementMonitor, ElementMonitor monitor = ( ElementMonitor ) cache . get ( key ) ; // If the element is not null then return its value, else null. // Also upgrade the timestamp of the matching element to the present to show that it has been recently // accessed. if ( monitor != null ) { // Upgrade the timestamp. long t = System . currentTimeMillis ( ) ; monitor . lastTouched = t ; // Return the element. return monitor . element ; } else { return null ; } } }


Input: Associates the specified value with the specified key in this map ( optional operation ) . If the map previously contained a mapping for this key the old value is replaced by the specified value . ( A map <tt > m< / tt > is said to contain a mapping for a key <tt > k< / tt > if and only if { @link #containsKey ( Object ) m . containsKey ( k ) } would return <tt > true< / tt > . )) [CODESPLIT] public Object put ( Object key , Object value ) { // Synchronize on the cache to ensure its integrity in a multi-threaded environment. synchronized ( cache ) { // Create a new ElementMonitor in the cache for the new element. // Timestamp the new element with the present time. long t = System . currentTimeMillis ( ) ; // Extract the element value out of the replaced element monitor if any. ElementMonitor replaced = ( ElementMonitor ) cache . put ( key , new ElementMonitor ( value , t ) ) ; if ( replaced != null ) { return replaced . element ; } else { return null ; } } }


Input: Removes the mapping for this key from this map if it is present ( optional operation ) . More formally if this map contains a mapping from key <tt > k< / tt > to value <tt > v< / tt > such that <code > ( key == null ? k == null : key . equals ( k )) < / code > that mapping is removed . ( The map can contain at most one such mapping . ) [CODESPLIT] public Object remove ( Object key ) { // Synchronize on the cache to ensure its integrity in a multi-threaded environment. synchronized ( cache ) { // Remove the element from the marked heap (if it exists in the heap) and from the cache. marked . remove ( key ) ; return cache . remove ( key ) ; } }


Input: Copies all of the mappings from the specified map to this map ( optional operation ) . The effect of this call is equivalent to that of calling { @link #put ( Object Object ) put ( k v ) } on this map once for each mapping from key <tt > k< / tt > to value <tt > v< / tt > in the specified map . The behavior of this operation is unspecified if the specified map is modified while the operation is in progress . [CODESPLIT] public void putAll ( Map t ) { // Synchronize on the cache to ensure its integrity in a multi-threaded environment. synchronized ( cache ) { // Iterate over all elements in the map to add, placing each of them into an ElementMonitor before // putting them into the cache. for ( Object nextKey : t . keySet ( ) ) { Object nextValue = t . get ( nextKey ) ; // Delegate to the put method to wrap the new item in an ElementMonitor. cache . put ( nextKey , nextValue ) ; } } }


Input: Garbage collects the cache sweeping out any elements that have timed out . This method should really only be invoked in a seperate thread as it does not return ( at least not until the { @link #sweepThreadKillFlag } is set ) . [CODESPLIT] private void sweep ( ) { /*log.fine("private void sweep(): called");*/ // Loop until the thread is terminated. while ( true ) { // Take a marked copy of the cache to examine for timed out elements. // Synchronize on the cache to ensure its integrity in a multi-threaded environment. synchronized ( cache ) { /*log.fine("\tMarking " + cache.size() + " objects.");*/ // Take a copy of everything in the cache into the marked heap. marked . putAll ( cache ) ; } // Use synchronized block to own this objects monitor so that it can be waited on. // This is needed so that the kill method, and other methods, can wake this thread up. synchronized ( this ) { // Use a try block as the thread may be woken up during the pause time between sweeps. try { // Halt the thread between sweeps, configured by the sweepTime property. wait ( sweepTime ) ; } catch ( InterruptedException e ) { // Ignore this, interuption conditions will be tested later. } } // TODO: Should really check that sweepTime has expired. // Check the sweep thread kill flag to see if the sweep algorithm has been stopped. if ( sweepThreadKillFlag ) { return ; } // Create a counter to count the number of elements removed from the cache. int i = 0 ; // Create a map to copy the marked heap into. This is done because the following code must iterate // over the marked heap whilst modifying it. A copy is used to generate all the keys to iterate over so // that the iterator is not disturbed by its underlying data structure being simultaneously modified. Map copy = new HashMap ( ) ; // Synchronize on the cache to ensure its integrity in a multi-threaded environment. synchronized ( cache ) { // Put everything in the marked cache into the copy. copy . putAll ( marked ) ; } // Loop over the copy of the marked heap looking for timed out elements. for ( Object nextKey : copy . keySet ( ) ) { // Get the key of the next element from the copy of the marked heap. // Extract the current element from the copy of the marked heap as an ElementMonitor object. ElementMonitor nextMonitor = ( ElementMonitor ) copy . get ( nextKey ) ; // Get the current time in milliseconds. long t = System . currentTimeMillis ( ) ; // Check if the current element has not been accessed for a while, configured by the // sweepExpiryTime property. if ( ( t - nextMonitor . lastTouched ) > sweepExpiryTime ) { // Synchronize on the cache to ensure its integrity in a multi-threaded environment. synchronized ( cache ) { // Remove the out of date element from the marked heap and from the cache. marked . remove ( nextKey ) ; cache . remove ( nextKey ) ; /*log.fine("Element removed from the cache " + nextKey);*/ // Increment the count of invalidated elements. i ++ ; } } } /*log.fine(i + " objects removed.");*/ } }


Input: ---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void getNameReturnsName ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( "" + "<form name='f'>" + "<input type='text' name='x'/>" + "</form>" + "" ) ) ; String actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getForm ( "f" ) . getControlGroup ( "x" ) . getName ( ) ; assertThat ( "form control group name" , actual , is ( "x" ) ) ; }


Input: ---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void getControlsReturnsControl ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( "" + "<form name='f'>" + "<input type='text' name='x'/>" + "</form>" + "" ) ) ; List < Control > actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getForm ( "f" ) . getControlGroup ( "x" ) . getControls ( ) ; assertThat ( "form control group control" , actual , contains ( control ( "x" ) ) ) ; }


Input:
Provides an iterator over a search method that returns successive search solutions on demand . [CODESPLIT] public static < T > Iterator < T > allSolutions ( SearchMethod < T > method ) { //return new Filterator<SearchNode<O, T>, T>(allSolutionNodes(method), new ExtractSearchNode<O, T>()); // Take a final reference to the search method to use from within the inner class. final SearchMethod < T > search = method ; return new SequenceIterator < T > ( ) { /**
                 * Generates the next element in the search.
                 *
                 * @return The next solution from the search if one is available, or <tt>null</tt> if the search is
                 *         complete.
                 */ public T nextInSequence ( ) { try { return search . search ( ) ; } catch ( SearchNotExhaustiveException e ) { // SearchNotExhaustiveException means that the search has completed within its designed parameters // without exhausting the search space. Consequently there are no more solutions to find, // the exception can be ignored and the sequence correctly terminated. e = null ; return null ; } } } ; }


Input: Finds the set of all goals of a search . [CODESPLIT] public static < T > Set < T > setOf ( SearchMethod < T > method ) { Set < T > result = new HashSet < T > ( ) ; findAll ( result , method ) ; return result ; }


Input: Finds a bag of all goals of a search . [CODESPLIT] public static < T > Collection < T > bagOf ( SearchMethod < T > method ) { Collection < T > result = new ArrayList < T > ( ) ; findAll ( result , method ) ; return result ; }


Input:
Provides an iterator over a search method that returns successive search solutions on demand . [CODESPLIT] public static < O , T extends Traversable < O > > Iterator < SearchNode < O , T > > allSolutionPaths ( QueueBasedSearchMethod < O , T > method ) { // Take a final reference to the search method to use from within the inner class. final QueueBasedSearchMethod < O , T > search = method ; return new SequenceIterator < SearchNode < O , T > > ( ) { /**
                 * Generates the next element in the search.
                 *
                 * @return The next solution from the search if one is available, or <tt>null</tt> if the search is
                 *         complete.
                 */ public SearchNode < O , T > nextInSequence ( ) { try { return search . findGoalPath ( ) ; } catch ( SearchNotExhaustiveException e ) { // SearchNotExhaustiveException means that the search has completed within its designed parameters // without exhausting the search space. Consequently there are no more solutions to find, // the exception can be ignored and the sequence correctly terminated. e = null ; return null ; } } } ; }


Input: Finals all solutions to a search and inserts them into the specified collection . [CODESPLIT] private static < T > void findAll ( Collection < T > result , SearchMethod < T > method ) { for ( Iterator < T > i = allSolutions ( method ) ; i . hasNext ( ) ; ) { T nextSoltn = i . next ( ) ; result . add ( nextSoltn ) ; } }


Input: { @inheritDoc } [CODESPLIT] public void open ( ) { // Build a text grid panel in the central position. grid = componentFactory . createTextGrid ( ) ; mainWindow . showCentrePane ( componentFactory . createTextGridPanel ( grid ) ) ; paneController = mainWindow . getCentreController ( ) ; paneController . showVerticalScrollBar ( ) ; // Build a table model on the text grid, to display the code in. table = ( EnhancedTextTable ) grid . createTable ( 0 , 0 , 20 , 20 ) ; breakpointMonitor = new BreakpointMonitorImpl ( ) ; byteCodeMonitor = new ByteCodeMonitor ( table ) ; // Attach listeners for user events on the table. grid . addTextGridSelectionListener ( new SelectionHandler ( ) ) ; // Register some keyboard shortcuts to control the code stepping. KeyShortcutMap shortcutMap = componentFactory . getKeyShortcutMap ( ) ; mainWindow . setKeyShortcut ( shortcutMap . getStep ( ) , "step" , new Step ( ) ) ; mainWindow . setKeyShortcut ( shortcutMap . getStepOver ( ) , "step_over" , new StepOver ( ) ) ; mainWindow . setKeyShortcut ( shortcutMap . getResume ( ) , "resume" , new Resume ( ) ) ; }


Input: Generates the next element in the sequence . [CODESPLIT] public T nextInSequence ( ) { T result = null ; // Loop until a filtered element is found, or the source iterator is exhausted. while ( source . hasNext ( ) ) { S next = source . next ( ) ; result = mapping . apply ( next ) ; if ( result != null ) { break ; } } return result ; }


Input: { [CODESPLIT] public ByteBuffer getCodeBuffer ( CallPoint callPoint ) { ByteBuffer buffer = ByteBuffer . wrap ( code , callPoint . entryPoint , callPoint . length ) ; buffer . order ( ByteOrder . LITTLE_ENDIAN ) ; return buffer ; }


Input: { [CODESPLIT] public SizeableLinkedList < WAMInstruction > compileBodyArguments ( Functor expression , boolean isFirstBody , FunctorName clauseName , int bodyNumber ) { // Build the argument to call in the usual way. return defaultBuiltIn . compileBodyArguments ( expression , isFirstBody , clauseName , bodyNumber ) ; }


Input: { [CODESPLIT] public SizeableLinkedList < WAMInstruction > compileBodyCall ( Functor expression , boolean isFirstBody , boolean isLastBody , boolean chainRule , int permVarsRemaining ) { // Used to build up the results in. SizeableLinkedList < WAMInstruction > instructions = new SizeableLinkedList < WAMInstruction > ( ) ; // Generate the call or tail-call instructions, followed by the call address, which is f_n of the // called program. if ( isLastBody ) { // Deallocate the stack frame at the end of the clause, but prior to calling the last // body predicate. // This is not required for chain rules, as they do not need a stack frame. if ( ! chainRule ) { instructions . add ( new WAMInstruction ( WAMInstruction . WAMInstructionSet . Deallocate ) ) ; } instructions . add ( new WAMInstruction ( WAMInstruction . WAMInstructionSet . CallInternal , ( byte ) ( permVarsRemaining & 0xff ) , new FunctorName ( "execute" , 1 ) ) ) ; } else { instructions . add ( new WAMInstruction ( WAMInstruction . WAMInstructionSet . CallInternal , ( byte ) ( permVarsRemaining & 0xff ) , new FunctorName ( "call" , 1 ) ) ) ; } return instructions ; }


Input:
Restores the properties currently in this memento to the specified object . [CODESPLIT] public static void restoreValues ( Object ob , Map < String , Object > values ) throws NoSuchFieldException { /*log.fine("public void restore(Object ob): called");*/ /*log.fine("Object to restore to has the type: " + ob.getClass());*/ // Get the class of th object to restore to. Class obClass = ob . getClass ( ) ; // Loop over all the stored properties. for ( String propName : values . keySet ( ) ) { // Get the cached property from this mementos store. Object nextValue = values . get ( propName ) ; /*log.fine("Next property to restore is: " + propName);*/ /*log.fine("Next value to restore is: " + nextValue);*/ // Used to hold the value to set. Object paramValue ; // Used to hold the type of the value to set. Class paramType ; // Check if the value store is a null. if ( nextValue == null ) { paramValue = null ; paramType = null ; } // Check if the value to store is a multi type data object. else if ( nextValue instanceof TypeConverter . MultiTypeData ) { /*log.fine("The value to restore is a multi typed data object.");*/ TypeConverter . MultiTypeData multiValue = ( TypeConverter . MultiTypeData ) nextValue ; // Get the types (classes) of all the possible 'setter' methods for the property. Set < Class > setterTypes = ReflectionUtils . findMatchingSetters ( ob . getClass ( ) , propName ) ; /*log.fine("setterTypes = " + setterTypes);*/ // Use the type converter to get the best matching type with the multi data. paramType = TypeConverter . bestMatchingConversion ( multiValue , setterTypes ) ; // Convert the multi data to an object of the appropriate type. paramValue = TypeConverter . convert ( multiValue , paramType ) ; } // The value to store is not a multi type. else { /*log.fine("The value to restore is a simply typed data object.");*/ // Get the type and value of the plain type to set. paramValue = nextValue ; paramType = nextValue . getClass ( ) ; } /*log.fine("paramValue = " + paramValue);*/ /*log.fine("paramType = " + paramType);*/ // Call the setter method with the new property value, checking first that the property has a matching // 'setter' method. Method setterMethod ; try { // Convert the first letter of the property name to upper case to match against the upper case version // of it that will be in the setter method name. For example the property test will have a setter method // called setTest. String upperPropertyName = Character . toUpperCase ( propName . charAt ( 0 ) ) + propName . substring ( 1 ) ; // Try to find an appropriate setter method on the object to call. setterMethod = obClass . getMethod ( "set" + upperPropertyName , paramType ) ; // Call the setter method with the new property value. Object [ ] params = new Object [ ] { paramValue } ; setterMethod . invoke ( ob , params ) ; } catch ( NoSuchMethodException e ) { // Do nothing as properties may have getters but no setter for read only properties. /*log.log(java.util.logging.Level.FINE, "A setter method could not be found for " + propName + ".", e);*/ /*
                // The object does not have a matching setter method for the type.
                NoSuchFieldException nsfe = new NoSuchFieldException("The object does not have a matching setter " +
                                                                     "method 'set" + propName + "'.");
                nsfe.initCause(e);
                throw nsfe;
                */ } catch ( IllegalAccessException e ) { /*log.log(java.util.logging.Level.FINE, "IllegalAccessException during call to setter method.", e);*/ } catch ( InvocationTargetException e ) { /*log.log(java.util.logging.Level.FINE, "InvocationTargetException during call to setter method.", e);*/ } } }


Input: Gets the value of the named property of the specified class . [CODESPLIT] public Object get ( Class cls , String property ) throws NoSuchFieldException { // Check that the field exists. if ( ! values . containsKey ( property ) ) { throw new NoSuchFieldException ( "The property, " + property + ", does not exist on the underlying class." ) ; } // Try to find a matching property cached in this memento. return values . get ( property ) ; }


Input: Sets the value of the named property as a multi type object . [CODESPLIT] public void put ( Class cls , String property , TypeConverter . MultiTypeData value ) { /*log.fine("public void put(String property, TypeConverter.MultiTypeData value): called");*/ /*log.fine("property  = " + property);*/ /*log.fine("value = " + value);*/ // Store the multi typed data under the specified property name. values . put ( property , value ) ; }


Input: Places the specified value into the memento based on the property s declaring class and name . [CODESPLIT] public void put ( Class cls , String property , Object value ) { // Store the new data under the specified property name. values . put ( property , value ) ; }


Input: Captures the fields of the associated object . [CODESPLIT] private void capture ( boolean ignoreNull ) { // Get the class of the object to build a memento for. Class cls = ob . getClass ( ) ; // Iterate through all the public methods of the class including all super-interfaces and super-classes. Method [ ] methods = cls . getMethods ( ) ; for ( Method nextMethod : methods ) { // Get the next method. /*log.fine("nextMethod = " + nextMethod.getName());*/ // Check if the method is a 'getter' method, is public and takes no arguments. String methodName = nextMethod . getName ( ) ; if ( methodName . startsWith ( "get" ) && ( methodName . length ( ) >= 4 ) && Character . isUpperCase ( methodName . charAt ( 3 ) ) && Modifier . isPublic ( nextMethod . getModifiers ( ) ) && ( nextMethod . getParameterTypes ( ) . length == 0 ) ) { String propName = Character . toLowerCase ( methodName . charAt ( 3 ) ) + methodName . substring ( 4 ) ; /*log.fine(methodName + " is a valid getter method for the property " + propName + ".");*/ try { // Call the 'getter' method to extract the properties value. Object [ ] params = new Object [ ] { } ; Object value = nextMethod . invoke ( ob , params ) ; /*log.fine("The result of calling the getter method is: " + value);*/ // Store the property value for the object. if ( ! ignoreNull || ( value != null ) ) { values . put ( propName , value ) ; } } catch ( IllegalAccessException e ) { /*log.log(java.util.logging.Level.FINE, "IllegalAccessException during call to getter method.", e);*/ throw new IllegalStateException ( e ) ; } catch ( InvocationTargetException e ) { /*log.log(java.util.logging.Level.FINE, "InvocationTargetException during call to getter method.", e);*/ throw new IllegalStateException ( e ) ; } } // Should also check if the method is a 'setter' method, is public and takes exactly one argument. } }