Input:
Looks up an array property value relative to the environment callers class and method . The default environment will be checked for a matching array property if defaults are being used . In order to work out the callers class and method this method throws an exception and then searches one level up its stack frames . [CODESPLIT] public String [ ] getProperties ( String key ) { // Try to get the callers class name and method name by throwing an exception an searching the stack frames. String className = null ; String methodName = null ; /* Java 1.4 onwards only.
           try {
             throw new Exception();
           } catch (Exception e) {
             StackTraceElement[] stack = e.getStackTrace();
             // Check that the stack trace contains at least two elements, one for this method and one for the caller.
             if (stack.length >= 2) {
               className = stack[1].getClassName();
               methodName = stack[1].getMethodName();
             }
           }*/ return getProperties ( className , methodName , key ) ; }


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


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


Input: For a given environment base modifier and key and setting of the use of default environments feature this generates an iterator that walks over the order in which to try and access properties . [CODESPLIT] protected Iterator getKeyIterator ( final String base , final String modifier , final String key ) { return new Iterator ( ) { // The key ordering count always begins at the start of the ORDER array. private int i ; public boolean hasNext ( ) { return ( useDefaults ? ( ( i < ORDER . length ) && ( ORDER [ i ] > ENVIRONMENT_DEFAULTS_CUTOFF ) ) : ( i < ORDER . length ) ) ; } public Object next ( ) { // Check that there is a next element and return null if not. if ( ! hasNext ( ) ) { return null ; } // Get the next ordering count. int o = ORDER [ i ] ; // Do bit matching on the count to choose which elements to include in the key. String result = ( ( ( o & E ) != 0 ) ? ( environment + "." ) : "" ) + ( ( ( o & B ) != 0 ) ? ( base + "." ) : "" ) + ( ( ( o & M ) != 0 ) ? ( modifier + "." ) : "" ) + key ; // Increment the iterator to get the next key on the next call. i ++ ; return result ; } public void remove ( ) { // This method is not supported. throw new UnsupportedOperationException ( "remove() is not supported on this key order iterator as " + "the ordering cannot be changed" ) ; } } ; }


Input: Scans all the properties in the parent Properties object and creates arrays for any array property definitions . [CODESPLIT] protected void createArrayProperties ( ) { // Scan through all defined properties. for ( Object o : keySet ( ) ) { String key = ( String ) o ; String value = super . getProperty ( key ) ; // Split the property key into everything before the last '.' and after it. int lastDotIndex = key . lastIndexOf ( ' ' ) ; String keyEnding = key . substring ( lastDotIndex + 1 , key . length ( ) ) ; String keyStart = key . substring ( 0 , ( lastDotIndex == - 1 ) ? 0 : lastDotIndex ) ; // Check if the property key ends in an integer, in which case it is an array property. int index = 0 ; try { index = Integer . parseInt ( keyEnding ) ; } catch ( NumberFormatException e ) { // The ending is not an integer so its not an array. // Exception can be ignored as it means this property is not an array. e = null ; continue ; } // Check if an array property already exists for this base name and create one if not. ArrayList propArray = ( ArrayList ) arrayProperties . get ( keyStart ) ; if ( propArray == null ) { propArray = new ArrayList ( ) ; arrayProperties . put ( keyStart , propArray ) ; } // Add the new property value to the array property for the index. propArray . set ( index , value ) ; } }


Input: { [CODESPLIT] public Term build ( ) { Term result ; if ( ! isCompound ( ) ) { result = getFunctor ( ) ; } else { if ( getFunctor ( ) . isAtom ( ) ) { List < Term > args = getArgs ( ) ; int arity = args . size ( ) ; Functor functor = ( Functor ) getFunctor ( ) ; int name = interner . internFunctorName ( interner . getFunctorName ( functor . getName ( ) ) , arity ) ; result = new Functor ( name , args . toArray ( new Term [ arity ] ) ) ; } else { throw new IllegalStateException ( "Invalid functor type." ) ; } } return result ; }


Input: Specifies the throttling rate in operations per second . This must be called with with a value the inverse of which is a measurement in nano seconds such that the number of nano seconds do not overflow a long integer . The value must also be larger than zero . [CODESPLIT] public void setRate ( float hertz ) { // Check that the argument is above zero. if ( hertz <= 0.0f ) { throw new IllegalArgumentException ( "The throttle rate must be above zero." ) ; } // Calculate the cycle time. cycleTimeNanos = ( long ) ( 1000000000f / hertz ) ; // Reset the first pass flag. firstCall = false ; firstCheckCall = false ; }


Input: This method can only be called at the rate set by the { @link #setRate } method if it is called faster than this it will inject short pauses to restrict the call rate to that rate . [CODESPLIT] public void throttle ( ) throws InterruptedException { // Don't introduce any pause on the first call. if ( ! firstCall ) { // Check if there is any time left in the cycle since the last throttle call to this method and introduce a // short pause to fill that time if there is. long remainingTimeNanos = timeToThrottleNanos ( ) ; while ( remainingTimeNanos > 0 ) { long milliPause = remainingTimeNanos / 1000000 ; int nanoPause = ( int ) ( remainingTimeNanos % 1000000 ) ; Thread . sleep ( milliPause , nanoPause ) ; remainingTimeNanos = timeToThrottleNanos ( ) ; } } else { firstCall = false ; } }


Input: Checks but does not enforce the throttle rate . When this method is called it checks if a length of time greater than that equal to the inverse of the throttling rate has passed since it was last called and returned <tt > true< / tt > . If the length of time still to elapse to the next throttle allow point is zero or less this method will return a negative value if there is still time to pass until the throttle allow point this method will return a positive value indicating the amount of time still to pass . A thread can wait for that period of time before rechecking the throttle condition . [CODESPLIT] public long timeToThrottleNanos ( ) { long now = System . nanoTime ( ) ; long remainingNanos = ( cycleTimeNanos + lastCheckTimeNanos ) - now ; if ( ( remainingNanos <= 0 ) ) { firstCheckCall = false ; lastCheckTimeNanos = now ; return remainingNanos ; } else if ( firstCheckCall ) { firstCheckCall = false ; lastCheckTimeNanos = now ; return 0 ; } else { return remainingNanos ; } }


Input: { [CODESPLIT] public void setProperty ( String name , Object value ) { // Set the type of the new property in the state type mapping. componentType . addPropertyType ( name , TypeHelper . getTypeFromObject ( value ) ) ; // Add the new property to the property map. properties . put ( name , value ) ; }


Input: Evaluates the arithmetic operator on its numeric argument . [CODESPLIT] protected NumericType evaluate ( NumericType firstNumber ) { // If the argument is a real number, then use real number arithmetic, otherwise use integer arithmetic. if ( firstNumber . isInteger ( ) ) { return new IntLiteral ( - firstNumber . intValue ( ) ) ; } else { return new DoubleLiteral ( - firstNumber . doubleValue ( ) ) ; } }


Input: This methods attempts to load the properties from a file or URL referenced by the system property with the same name as the properties resource name from a resource on the classpath with the same name as the properties resource name or from a properties file name relative to the current working directory . It tries these methods sequentially one after the other until one succeeds . [CODESPLIT] protected void findProperties ( ) { /*log.fine("findProperties: called");*/ // Try to load the properties from a file referenced by the system property matching // the properties file name. properties = getPropertiesUsingSystemProperty ( ) ; if ( properties != null ) { /*log.fine("loaded properties using the system property");*/ // The properties were succesfully located and loaded return ; } /*log.fine("failed to get properties from the system properties");*/ // Try to load the properties from a resource on the classpath using the current // class loader properties = getPropertiesUsingClasspath ( ) ; if ( properties != null ) { /*log.fine("loaded properties from the class path");*/ // The properties were succesfully located and loaded return ; } /*log.fine("failed to get properties from the classpath");*/ // Try to load the properties from a file relative to the current working directory properties = getPropertiesUsingCWD ( ) ; if ( properties != null ) { /*log.fine("loaded properties from the current working directory");*/ // The properties were succesfully located and loaded return ; } /*log.fine("failed to get properties from the current working directory");*/ }


Input: Tries to load the properties from the file or URL named by the system property with name mathching the properties resource name . [CODESPLIT] protected Properties getPropertiesUsingSystemProperty ( ) { /*log.fine("getPropertiesUsingSystemProperty: called");*/ // Get the path to the file from the system properties /*log.fine("getPropertiesResourceName() = " + getPropertiesResourceName());*/ String path = System . getProperty ( getPropertiesResourceName ( ) ) ; /*log.fine("properties resource name = " + getPropertiesResourceName());*/ /*log.fine("path = " + path);*/ // Use PropertiesHelper to try to load the properties from the path try { return PropertiesHelper . getProperties ( path ) ; } catch ( IOException e ) { /*log.fine("Could not load properties from path " + path);*/ // Failure of this method is noted, so exception is ignored. e = null ; } return null ; }


Input: Tries to load the properties from the classpath using the classloader for this class . [CODESPLIT] protected Properties getPropertiesUsingClasspath ( ) { /*log.fine("getPropertiesUsingClasspath: called");*/ // Try to open the properties resource name as an input stream from the classpath InputStream is = this . getClass ( ) . getClassLoader ( ) . getResourceAsStream ( getPropertiesResourceName ( ) ) ; // Use PropertiesHelper to try to load the properties from the input stream if one was succesfully created if ( is != null ) { try { return PropertiesHelper . getProperties ( is ) ; } catch ( IOException e ) { /*log.fine("Could not load properties from classpath");*/ // Failure of this method is noted, so exception is ignored. e = null ; } } return null ; }


Input: Tries to load the properties as a file or URL matching the properties resource name . File names will be taken relative to the current working directory . [CODESPLIT] protected Properties getPropertiesUsingCWD ( ) { /*log.fine("getPropertiesUsingCWD: called");*/ // Use PropertiesHelper to try to load the properties from a file or URl try { return PropertiesHelper . getProperties ( getPropertiesResourceName ( ) ) ; } catch ( IOException e ) { /*log.fine("Could not load properties from file or URL " + getPropertiesResourceName());*/ // Failure of this method is noted, so exception is ignored. e = null ; } return null ; }


Input: Applies the built - in transform during a post - fix visit of a term . [CODESPLIT] protected void leaveFunctor ( Functor functor ) { int pos = traverser . getPosition ( ) ; if ( ! traverser . isInHead ( ) && ( pos >= 0 ) ) { Functor transformed = builtInTransform . apply ( functor ) ; if ( functor != transformed ) { /*log.fine("Transformed: " + functor + " to " + transformed.getClass());*/ BuiltInFunctor builtInFunctor = ( BuiltInFunctor ) transformed ; Term parentTerm = traverser . getParentContext ( ) . getTerm ( ) ; if ( parentTerm instanceof Clause ) { Clause parentClause = ( Clause ) parentTerm ; parentClause . getBody ( ) [ pos ] = builtInFunctor ; } else if ( parentTerm instanceof Functor ) { Functor parentFunctor = ( Functor ) parentTerm ; parentFunctor . getArguments ( ) [ pos ] = builtInFunctor ; } } } }


Input: Gets the actual value of a term which is either the term itself or in the case of variables the value that is currently assigned to the variable . When the variable is free the variable term itself is returned . [CODESPLIT] public Term getValue ( ) { Term result = this ; Term assignment = this . substitution ; // If the variable is assigned, loops down the chain of assignments until no more can be found. Whatever term // is found at the end of the chain of assignments is the value of this variable. while ( assignment != null ) { result = assignment ; if ( ! assignment . isVar ( ) ) { break ; } else { assignment = ( ( Variable ) assignment ) . substitution ; } } return result ; }


Input: Binds this variable to the specified value . [CODESPLIT] public void setSubstitution ( Term term ) { Term termToBindTo = term ; // When binding against a variable, always bind to its storage cell and not the variable itself. if ( termToBindTo instanceof Variable ) { Variable variableToBindTo = ( Variable ) term ; termToBindTo = variableToBindTo . getStorageCell ( variableToBindTo ) ; } substitution = termToBindTo ; }


Input: { [CODESPLIT] public void accept ( TermVisitor visitor ) { if ( visitor instanceof VariableVisitor ) { ( ( VariableVisitor ) visitor ) . visit ( this ) ; } else { super . accept ( visitor ) ; } }


Input: { [CODESPLIT] public Variable acceptTransformer ( TermTransformer transformer ) { if ( transformer instanceof VariableTransformer ) { return ( ( VariableTransformer ) transformer ) . transform ( this ) ; } else { return ( Variable ) super . acceptTransformer ( transformer ) ; } }


Input: Compares this term for structural equality with another . Two terms are structurally equal if they are the same functor with the same arguments or are the same unbound variable or the bound values of the left or right variable operands are structurally equal . Structural equality is a stronger equality than unification and unlike unification it does not produce any variable bindings . Two unified terms will always be structurally equal . [CODESPLIT] public boolean structuralEquals ( Term term ) { Term comparator = term . getValue ( ) ; Term value = getValue ( ) ; // Check if this is an unbound variable in which case the comparator must be the same variable. if ( value == this ) { return this . equals ( comparator ) ; } else { return value . structuralEquals ( comparator ) ; } }


Input: { [CODESPLIT] public CharSequence subSequence ( int start , int end ) { return new ASCIIByteBufferString ( data , offset + start , end - start ) ; }


Input: { @inheritDoc } [CODESPLIT] public int compareTo ( ASCIIString comparator ) { int n = Math . min ( length , comparator . length ( ) ) ; for ( int i = 0 ; i < n ; i ++ ) { byte b1 = get ( i ) ; byte b2 = comparator . get ( i ) ; if ( b1 == b2 ) { continue ; } if ( b1 < b2 ) { return - 1 ; } return 1 ; } return length - comparator . length ( ) ; }


Input: Computes and caches in the { [CODESPLIT] private void computeStringValue ( ) { char [ ] chars = new char [ length ] ; for ( int i = 0 ; i < length ; i ++ ) { chars [ i ] = ( char ) data . get ( i + offset ) ; } stringValue = new String ( chars ) ; }


Input: Computes and caches in the { [CODESPLIT] private void computeHashCode ( ) { hashCode = 0 ; for ( int i = 0 ; i < length ; i ++ ) { hashCode = ( 31 * hashCode ) + data . get ( i + offset ) ; } }


Input: Creates the correct type of queue for this search . This search uses a priority queue ordered by heuristic value . [CODESPLIT] public Queue < SearchNode < O , T > > createQueue ( ) { return new PriorityQueue < SearchNode < O , T > > ( 11 , new GreedyComparator ( ) ) ; }


Input: Drop the connection to the remote host and release the underlying connector thread if it has been created . [CODESPLIT] public void cleanUp ( ) { if ( oos != null ) { try { oos . close ( ) ; } catch ( IOException e ) { LogLog . error ( "Could not close oos." , e ) ; } oos = null ; } if ( connector != null ) { // LogLog.debug("Interrupting the connector."); connector . interrupted = true ; connector = null ; // allow gc } }


Input: Appends a logging event to the remote event reciever . [CODESPLIT] public void append ( LoggingEvent event ) { if ( event == null ) { return ; } if ( address == null ) { errorHandler . error ( "No remote host is set for SocketAppender named \"" + this . name + "\"." ) ; return ; } if ( oos != null ) { try { if ( locationInfo ) { event . getLocationInformation ( ) ; } oos . writeObject ( event ) ; // LogLog.debug("=========Flushing."); oos . flush ( ) ; if ( ++ counter >= RESET_FREQUENCY ) { counter = 0 ; // Failing to reset the object output stream every now and // then creates a serious memory leak. // System.err.println("Doing oos.reset()"); oos . reset ( ) ; } } catch ( IOException e ) { oos = null ; LogLog . warn ( "Detected problem with connection: " + e ) ; if ( reconnectionDelay > 0 ) { fireConnector ( ) ; } } } }


Input:
Connects to remote server at <code > address< / code > and <code > port< / code > . [CODESPLIT] void connect ( InetAddress address , int port ) { if ( this . address == null ) { return ; } try { // First, close the previous connection if any. cleanUp ( ) ; Socket socket = new Socket ( ) ; SocketAddress socketAddr = new InetSocketAddress ( address , port ) ; socket . connect ( socketAddr , 10 ) ; oos = new ObjectOutputStream ( socket . getOutputStream ( ) ) ; } catch ( IOException e ) { // Silently fail and do not retry later. // Exception noted so can be ignored. e = null ; /*
             * String msg = "Could not connect to remote log4j server at [" +address.getHostName()+"].";
             * if(reconnectionDelay > 0) { msg += " We will try again later."; fireConnector(); // fire the connector
             * thread } LogLog.error(msg, e); */ } }


Input: Starts a new connector thread to do? [CODESPLIT] void fireConnector ( ) { if ( connector == null ) { LogLog . debug ( "Starting a new connector thread." ) ; connector = new Connector ( ) ; connector . setDaemon ( true ) ; connector . setPriority ( Thread . MIN_PRIORITY ) ; connector . start ( ) ; } }


Input: { [CODESPLIT] public void visit ( Predicate predicate ) { for ( AllTermsVisitor printer : printers ) { printer . visit ( predicate ) ; } super . visit ( predicate ) ; }


Input: { [CODESPLIT] public void visit ( Clause clause ) { for ( AllTermsVisitor printer : printers ) { printer . visit ( clause ) ; } super . visit ( clause ) ; }


Input: { [CODESPLIT] public void visit ( Functor functor ) { for ( AllTermsVisitor printer : printers ) { printer . visit ( functor ) ; } super . visit ( functor ) ; }


Input: { [CODESPLIT] public void visit ( Variable variable ) { for ( AllTermsVisitor printer : printers ) { printer . visit ( variable ) ; } super . visit ( variable ) ; }


Input: Sets up the stack of column printers . [CODESPLIT] protected void initializePrinters ( ) { int maxColumns = 0 ; printers . add ( new SourceClausePrinter ( interner , symbolTable , traverser , maxColumns ++ , printTable ) ) ; printers . add ( new PositionPrinter ( interner , symbolTable , traverser , maxColumns ++ , printTable ) ) ; printers . add ( new UnoptimizedLabelPrinter ( interner , symbolTable , traverser , maxColumns ++ , printTable ) ) ; printers . add ( new UnoptimizedByteCodePrinter ( interner , symbolTable , traverser , maxColumns ++ , printTable ) ) ; printers . add ( new LabelPrinter ( interner , symbolTable , traverser , maxColumns ++ , printTable ) ) ; printers . add ( new ByteCodePrinter ( interner , symbolTable , traverser , maxColumns ++ , printTable ) ) ; }


Input: Assembles the accumulated output in all rows and columns into a table . The table is appended onto { [CODESPLIT] protected void printTable ( ) { for ( int i = 0 ; i < printTable . getRowCount ( ) ; i ++ ) { for ( int j = 0 ; j < printTable . getColumnCount ( ) ; j ++ ) { String valueToPrint = printTable . get ( j , i ) ; valueToPrint = ( valueToPrint == null ) ? "" : valueToPrint ; result . append ( valueToPrint ) ; Integer maxColumnSize = printTable . getMaxColumnSize ( j ) ; int padding = ( ( maxColumnSize == null ) ? 0 : maxColumnSize ) - valueToPrint . length ( ) ; padding = ( padding < 0 ) ? 0 : padding ; for ( int s = 0 ; s < padding ; s ++ ) { result . append ( " " ) ; } result . append ( " % " ) ; } result . append ( "\n" ) ; } }


Input:
---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void getItemsWhenItemReturnsItem ( ) throws MalformedURLException { server ( ) . enqueue ( new MockResponse ( ) . setBody ( "" + "
" + "" ) ) ; List < MicrodataItem > actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getItems ( "http://x" ) ; assertThat ( "items" , actual , contains ( item ( "http://y" ) ) ) ; }


Input: ---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void getLinkWhenAnchorReturnsLink ( ) throws MalformedURLException { server ( ) . enqueue ( new MockResponse ( ) . setBody ( "" + "" + "" ) ) ; Link actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getLink ( "x" ) ; assertThat ( "link" , actual , is ( link ( "x" , "http://y/" ) ) ) ; }


Input: ---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void getFormReturnsForm ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( "" + "<form name='x'/>" + "" ) ) ; Form actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getForm ( "x" ) ; assertThat ( "form" , actual . getName ( ) , is ( "x" ) ) ; }


Input: ---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void unwrapWithUnknownTypeThrowsException ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( "<html><body/></html>" ) ) ; MicrodataDocument document = newBrowser ( ) . get ( url ( server ( ) ) ) ; thrown ( ) . expect ( IllegalArgumentException . class ) ; thrown ( ) . expectMessage ( "Cannot unwrap to: class java.lang.Void" ) ; document . unwrap ( Void . class ) ; }


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


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


Input: ---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void setControlValueSetsValue ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( "" + "<form name='f'>" + "<input type='text' name='x' value='y'/>" + "</form>" + "" ) ) ; Form form = newBrowser ( ) . get ( url ( server ( ) ) ) . getForm ( "f" ) ; form . setControlValue ( "x" , "y" ) ; assertThat ( "form control value" , form . getControlValue ( "x" ) , is ( "y" ) ) ; }


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


Input: ---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void submitWhenSubmitInputSubmitsRequest ( ) throws InterruptedException { server ( ) . enqueue ( new MockResponse ( ) . setBody ( "" + "<form name='f' action='/x'>" + "<input type='submit'/>" + "</form>" + "" ) ) ; server ( ) . enqueue ( new MockResponse ( ) ) ; newBrowser ( ) . get ( url ( server ( ) ) ) . getForm ( "f" ) . submit ( ) ; server ( ) . takeRequest ( ) ; assertThat ( "request" , takeRequest ( server ( ) ) . getPath ( ) , is ( "/x" ) ) ; }


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


Input: { [CODESPLIT] protected void enterFunctor ( Functor functor ) { String showContextAs = interner . getFunctorName ( functor ) + ( functor . isAtom ( ) ? "" : "(" ) ; int delta = showContextAs . length ( ) ; addLineToRow ( indent + showContextAs ) ; nextRow ( ) ; indent = indenter . generateTraceIndent ( delta ) ; }


Input: { [CODESPLIT] protected void leaveFunctor ( Functor functor ) { String toAppend = indent ; boolean addData = false ; if ( functor . isCompound ( ) ) { toAppend += ")" ; addData = true ; } if ( ! traverser . isInHead ( ) && ! traverser . isLastBodyFunctor ( ) && traverser . isTopLevel ( ) ) { toAppend += "," ; addData = true ; } if ( traverser . isInHead ( ) && traverser . isTopLevel ( ) ) { toAppend += " :-" ; addData = true ; } if ( addData ) { addLineToRow ( toAppend ) ; nextRow ( ) ; } indent = indenter . generateTraceIndent ( - indenter . getLastDelta ( ) ) ; }


Input: { [CODESPLIT] protected void enterVariable ( Variable variable ) { String showContextAs = interner . getVariableName ( variable ) ; int delta = showContextAs . length ( ) ; addLineToRow ( indent + showContextAs ) ; nextRow ( ) ; indent = indenter . generateTraceIndent ( delta ) ; }


Input: ---------------------------------------------------------------------------------------------------------------- [CODESPLIT] private static String getCheckedValue ( Control control ) { if ( control instanceof CheckableControl ) { return ( ( CheckableControl ) control ) . getCheckedValue ( ) ; } return control . getValue ( ) ; }


Input: { [CODESPLIT] public SizeableLinkedList < WAMInstruction > compileBodyCall ( Functor expression , boolean isFirstBody , boolean isLastBody , boolean chainRule , int permVarsRemaining ) { SizeableLinkedList < WAMInstruction > result = new SizeableLinkedList < WAMInstruction > ( ) ; if ( isLastBody ) { if ( ! chainRule ) { result . add ( new WAMInstruction ( WAMInstruction . WAMInstructionSet . Deallocate ) ) ; } result . add ( new WAMInstruction ( WAMInstruction . WAMInstructionSet . Proceed ) ) ; } return result ; }


Input: When operating in transactional mode causes any changes since the last commit to be made visible to the search method . [CODESPLIT] public void commit ( ) { TxId txId = null ; // Check if in a higher transactional mode than none, otherwise commit does nothing. if ( ! getIsolationLevel ( ) . equals ( IsolationLevel . None ) ) { // Extract the current transaction id. txId = TxManager . getTxIdFromThread ( ) ; // Wait until the global write lock can be acquired by this transaction. try { acquireGlobalWriteLock ( txId ) ; } catch ( InterruptedException e ) { // The commit was interrupted, so cannot succeed. throw new IllegalStateException ( "Interrupted whilst commit is waiting for global write lock." , e ) ; } // Check that this transaction has made changes to be committed. List < TxOperation > alterations = txWrites . get ( txId ) ; try { if ( alterations != null ) { // Loop through all the writes that the transaction wants to apply to the resource. for ( TxOperation nextAlteration : alterations ) { // Apply the change and update the term resource. nextAlteration . execute ( ) ; } // Clear the write behind cache for this transaction as its work has been completed. txWrites . remove ( txId ) ; } } finally { // Release the global write lock. releaseGlobalWriteLock ( ) ; } } }


Input: When operation in transactional mode causes any changes since the last commit to be dropped and never made visible to the search method . [CODESPLIT] public void rollback ( ) { TxId txId = null ; // Check if in a higher transactional mode than none, otherwise commit does nothing. if ( ! getIsolationLevel ( ) . equals ( IsolationLevel . None ) ) { // Extract the current transaction id. txId = TxManager . getTxIdFromThread ( ) ; // Check that this transaction has made changes to be rolled back. List < TxOperation > alterations = txWrites . get ( txId ) ; if ( alterations != null ) { // Loop through all the writes that the transaction wants to apply to the resource. for ( TxOperation nextAlteration : alterations ) { // Cancel the operation. nextAlteration . cancel ( false ) ; } } // Discard all the changes that the transaction was going to make. txWrites . remove ( txId ) ; } }


Input: Requests an operation that alters the transactional resource . This may be blocked until an appropriate lock can be acquired delayed until commit time or actioned upon a copy of the data structure private to a transaction branch . [CODESPLIT] public void requestWriteOperation ( TxOperation op ) { // Check if in a higher transactional mode than none and capture the transaction id if so. TxId txId = null ; if ( getIsolationLevel ( ) . compareTo ( IsolationLevel . None ) > 0 ) { // Extract the current transaction id. txId = TxManager . getTxIdFromThread ( ) ; // Ensure that this resource is enlisted with the current session. enlistWithSession ( ) ; } // For non-transactional isolation levels, apply the requested operation immediately. if ( getIsolationLevel ( ) . equals ( IsolationLevel . None ) ) { op . execute ( ) ; } // Add the operation to the transaction write-behind cache for the transaction id, if using transactional // isolation, to defer the operation untill commit time. else { addCachedOperation ( txId , op ) ; } }


Input: Adds a transactional operation to the transactional write - behind cache for the specified transaction . If no cache exists for the specified transaction id a new one is created . [CODESPLIT] private void addCachedOperation ( TxId txId , TxOperation cachedWriteOperation ) { List < TxOperation > writeCache = txWrites . get ( txId ) ; if ( writeCache == null ) { writeCache = new ArrayList < TxOperation > ( ) ; txWrites . put ( txId , writeCache ) ; } writeCache . add ( cachedWriteOperation ) ; }


Input: Waits until the global write lock can be acquired by the specified transaction . [CODESPLIT] private void acquireGlobalWriteLock ( TxId txId ) throws InterruptedException { // Get the global write lock to ensure only one thread at a time can execute this code. globalLock . writeLock ( ) . lock ( ) ; // Use a try block so that the corresponding finally block guarantees release of the thread lock. try { // Check that this transaction does not already own the lock. if ( ! txId . equals ( globalWriteLockTxId ) ) { // Wait until the write lock becomes free. while ( globalWriteLockTxId != null ) { globalWriteLockFree . await ( ) ; } // Assign the global write lock to this transaction. globalWriteLockTxId = txId ; } } finally { // Ensure that the thread lock is released once assignment of the write lock to the transaction is complete. globalLock . writeLock ( ) . unlock ( ) ; } }


Input: Releases the global write lock from being assigned to a transaction . [CODESPLIT] private void releaseGlobalWriteLock ( ) { // Get the global write lock to ensure only one thread at a time can execute this code. globalLock . writeLock ( ) . lock ( ) ; // Use a try block so that the corresponding finally block guarantees release of the thread lock. try { // Release the global write lock, assigning it to no transaction. globalWriteLockTxId = null ; // Signal that the write lock is now free. globalWriteLockFree . signal ( ) ; } // Ensure that the thread lock is released once assignment of the write lock to the transaction is complete. finally { globalLock . writeLock ( ) . unlock ( ) ; } }


Input: Enlists this transactional resource with the current session . If no session exists this will fail . [CODESPLIT] private void enlistWithSession ( ) { TxSession session = TxSessionImpl . getCurrentSession ( ) ; // Ensure that this resource is being used within a session. if ( session == null ) { throw new IllegalStateException ( "Cannot access transactional resource outside of a session." ) ; } // Ensure that this resource is enlisted with the session. session . enlist ( this ) ; }


Input: Locates nested MediaQueryNode inside RuleSetNode separates RuleSetNode and MediaQueryNode [CODESPLIT] @ Override public boolean enter ( RuleSetNode ruleSetNode ) { ScopeNode scopeNode = NodeTreeUtils . getFirstChild ( ruleSetNode , ScopeNode . class ) ; SelectorGroupNode selectorGroupNode = NodeTreeUtils . getFirstChild ( ruleSetNode , SelectorGroupNode . class ) ; if ( selectorGroupNode == null ) { return true ; } List < SelectorNode > selectorNodes = NodeTreeUtils . getChildren ( selectorGroupNode , SelectorNode . class ) ; if ( selectorNodes . size ( ) < 0 ) { return true ; } List < MediaQueryNode > mediaQueryNodes = NodeTreeUtils . getAndRemoveChildren ( scopeNode , MediaQueryNode . class ) ; for ( MediaQueryNode mediaQueryNode : mediaQueryNodes ) { ScopeNode mediaScopeNode = NodeTreeUtils . getFirstChild ( mediaQueryNode , ScopeNode . class ) ; List < RuleSetNode > nestedRuleSets = NodeTreeUtils . getAndRemoveChildren ( mediaScopeNode , RuleSetNode . class ) ; // if scope node for media query has anything more but whitespaces and rule sets than wrap it with rule set with the same selector group as outer rule set has if ( mediaScopeNode . getChildren ( ) . size ( ) > NodeTreeUtils . getChildren ( mediaScopeNode , WhiteSpaceCollectionNode . class ) . size ( ) ) { RuleSetNode newRuleSetNode = new RuleSetNode ( ) ; ScopeNode newScopeNode = new ScopeNode ( ) ; newRuleSetNode . addChild ( selectorGroupNode . clone ( ) ) ; newRuleSetNode . addChild ( newScopeNode ) ; NodeTreeUtils . moveChildren ( mediaScopeNode , newScopeNode ) ; mediaScopeNode . clearChildren ( ) ; mediaScopeNode . addChild ( newRuleSetNode ) ; } // adding outer selectors to every nested selectors for ( RuleSetNode nestedRuleSet : nestedRuleSets ) { List < SelectorGroupNode > nestedSelectorGroupNodes = NodeTreeUtils . getChildren ( nestedRuleSet , SelectorGroupNode . class ) ; for ( SelectorGroupNode nestedSelectorGroupNode : nestedSelectorGroupNodes ) { List < SelectorNode > nestedSelectorNodes = NodeTreeUtils . getAndRemoveChildren ( nestedSelectorGroupNode , SelectorNode . class ) ; NodeTreeUtils . getAndRemoveChildren ( nestedSelectorGroupNode , SpacingNode . class ) ; for ( SelectorNode selectorNode : selectorNodes ) { for ( SelectorNode nestedSelectorNode : nestedSelectorNodes ) { if ( nestedSelectorNode . getChildren ( ) . get ( 0 ) != null ) { if ( nestedSelectorNode . getChildren ( ) . get ( 0 ) instanceof SelectorSegmentNode ) { SelectorSegmentNode selectorSegmentNode = ( SelectorSegmentNode ) nestedSelectorNode . getChildren ( ) . get ( 0 ) ; selectorSegmentNode . setCombinator ( " " ) ; } } for ( int j = selectorNode . getChildren ( ) . size ( ) - 1 ; j >= 0 ; j -- ) { if ( selectorNode . getChildren ( ) . get ( j ) instanceof SelectorSegmentNode ) { SelectorSegmentNode selectorSegmentNode = ( SelectorSegmentNode ) selectorNode . getChildren ( ) . get ( j ) . clone ( ) ; nestedSelectorNode . addChild ( 0 , selectorSegmentNode ) ; } } nestedSelectorGroupNode . addChild ( nestedSelectorNode ) ; nestedSelectorGroupNode . addChild ( new SpacingNode ( " " ) ) ; } } } mediaScopeNode . addChild ( nestedRuleSet ) ; } if ( ruleSetNode . getParent ( ) != null ) { ruleSetNode . getParent ( ) . addChild ( new SpacingNode ( "\n" ) ) ; ruleSetNode . getParent ( ) . addChild ( mediaQueryNode ) ; } } return true ; }


Input: Inserts the specified element into this queue if possible . When using queues that may impose insertion restrictions ( for example capacity bounds ) method <tt > offer< / tt > is generally preferable to method { @link java . util . Collection#add } which can fail to insert an element only by throwing an exception . [CODESPLIT] public boolean offer ( E e ) { if ( e == null ) { throw new IllegalArgumentException ( "The 'e' parameter may not be null." ) ; } ReentrantLock lock = this . lock ; lock . lock ( ) ; try { return insert ( e , false ) ; } finally { lock . unlock ( ) ; } }


Input: Inserts the specified element into this queue waiting if necessary up to the specified wait time for space to become available . [CODESPLIT] public boolean offer ( E e , long timeout , TimeUnit unit ) throws InterruptedException { if ( e == null ) { throw new IllegalArgumentException ( "The 'e' parameter may not be null." ) ; } ReentrantLock lock = this . lock ; lock . lockInterruptibly ( ) ; long nanos = unit . toNanos ( timeout ) ; try { do { if ( insert ( e , false ) ) { return true ; } try { nanos = notFull . awaitNanos ( nanos ) ; } catch ( InterruptedException ie ) { // Wake up another thread waiting on notFull, as the condition may be true, but this thread // was interrupted so cannot make use of it. notFull . signal ( ) ; throw ie ; } } while ( nanos > 0 ) ; return false ; } finally { lock . unlock ( ) ; } }


Input: Retrieves and removes the head of this queue or <tt > null< / tt > if this queue is empty . [CODESPLIT] public E poll ( ) { ReentrantLock lock = this . lock ; lock . lock ( ) ; try { if ( count == 0 ) { return null ; } return extract ( true , true ) . getElement ( ) ; } finally { lock . unlock ( ) ; } }


Input: Retrieves and removes the head of this queue waiting if necessary up to the specified wait time if no elements are present on this queue . [CODESPLIT] public E poll ( long timeout , TimeUnit unit ) throws InterruptedException { ReentrantLock lock = this . lock ; lock . lockInterruptibly ( ) ; try { long nanos = unit . toNanos ( timeout ) ; do { if ( count != 0 ) { return extract ( true , true ) . getElement ( ) ; } try { nanos = notEmpty . awaitNanos ( nanos ) ; } catch ( InterruptedException ie ) { notEmpty . signal ( ) ; // propagate to non-interrupted thread throw ie ; } } while ( nanos > 0 ) ; return null ; } finally { lock . unlock ( ) ; } }


Input: Retrieves but does not remove the head of this queue returning <tt > null< / tt > if this queue is empty . [CODESPLIT] public E peek ( ) { ReentrantLock lock = this . lock ; lock . lock ( ) ; try { return peekAtBufferHead ( ) ; } finally { lock . unlock ( ) ; } }


Input: Adds the specified element to this queue waiting if necessary for space to become available . [CODESPLIT] public void put ( E e ) throws InterruptedException { try { tryPut ( e ) ; } catch ( SynchException ex ) { // This exception is deliberately ignored. See the method comment for information about this. ex = null ; } }


Input: Tries a synchronous put into the queue . If a consumer encounters an exception condition whilst processing the data that is put then this is returned to the caller wrapped inside a { @link SynchException } . [CODESPLIT] public void tryPut ( E e ) throws InterruptedException , SynchException { if ( e == null ) { throw new IllegalArgumentException ( "The 'e' parameter may not be null." ) ; } // final Queue<E> items = this.buffer; ReentrantLock lock = this . lock ; lock . lockInterruptibly ( ) ; try { while ( getBufferRemainingCapacity ( ) == 0 ) { // Release the lock and wait until the queue is not full. notFull . await ( ) ; } } catch ( InterruptedException ie ) { notFull . signal ( ) ; // propagate to non-interrupted thread throw ie ; } // There is room in the queue so insert must succeed. Insert into the queu, release the lock and block // the producer until its data is taken. insert ( e , true ) ; }


Input: Retrieves and removes the head of this queue waiting if no elements are present on this queue . Any producer that has its data element taken by this call will be immediately unblocked . To keep the producer blocked whilst taking just a single item use the { @link #drainTo ( java . util . Collection< SynchRecord <E >> int boolean ) } method . There is no take method to do that because there is not usually any advantage in a synchronous hand off design that consumes data one item at a time . It is normal to consume data in chunks to ammortize consumption latencies accross many producers where possible . [CODESPLIT] public E take ( ) throws InterruptedException { ReentrantLock lock = this . lock ; lock . lockInterruptibly ( ) ; try { try { while ( count == 0 ) { // Release the lock and wait until the queue becomes non-empty. notEmpty . await ( ) ; } } catch ( InterruptedException ie ) { notEmpty . signal ( ) ; // propagate to non-interrupted thread throw ie ; } // There is data in the queue so extraction must succeed. Notify any waiting threads that the queue is // not full, and unblock the producer that owns the data item that is taken. return extract ( true , true ) . getElement ( ) ; } finally { lock . unlock ( ) ; } }


Input: Removes at most the given number of available elements from this queue and adds them into the given collection . A failure encountered while attempting to <tt > add< / tt > elements to collection <tt > c< / tt > may result in elements being in neither either or both collections when the associated exception is thrown . Attempts to drain a queue to itself result in <tt > IllegalArgumentException< / tt > . Further the behavior of this operation is undefined if the specified collection is modified while the operation is in progress . [CODESPLIT] public int drainTo ( Collection < ? super E > collection , int maxElements ) { if ( collection == null ) { throw new IllegalArgumentException ( "The 'collection' parameter may not be null." ) ; } if ( collection == this ) { throw new IllegalArgumentException ( "The 'collection' parameter may not be this object." ) ; } // final Queue<E> items = this.buffer; ReentrantLock lock = this . lock ; lock . lock ( ) ; try { int n = 0 ; for ( int max = ( ( maxElements >= count ) || ( maxElements < 0 ) ) ? count : maxElements ; n < max ; n ++ ) { // Take items from the queue, do unblock the producers, but don't send not full signals yet. collection . add ( extract ( true , false ) . getElement ( ) ) ; } if ( n > 0 ) { // count -= n; notFull . signalAll ( ) ; } return n ; } finally { lock . unlock ( ) ; } }


Input: Takes all available data items from the queue or blocks until some become available . The returned items are wrapped in a { @link SynchRecord } which provides an interface to requeue them or send errors to their producers where the producers are still blocked . [CODESPLIT] public SynchRef drainTo ( Collection < SynchRecord < E > > c , boolean unblock ) { return drainTo ( c , - 1 , unblock ) ; }


Input: Takes up to maxElements available data items from the queue or blocks until some become available . The returned items are wrapped in a { @link SynchRecord } which provides an interface to requeue them or send errors to their producers where the producers are still blocked . [CODESPLIT] public SynchRef drainTo ( Collection < SynchRecord < E > > collection , int maxElements , boolean unblock ) { if ( collection == null ) { throw new IllegalArgumentException ( "The 'collection' parameter may not be null." ) ; } if ( collection == this ) { throw new IllegalArgumentException ( "The 'collection' parameter may not be this object." ) ; } // final Queue<E> items = this.buffer; ReentrantLock lock = this . lock ; lock . lock ( ) ; try { int n = 0 ; for ( int max = ( ( maxElements >= count ) || ( maxElements < 0 ) ) ? count : maxElements ; n < max ; n ++ ) { // Extract the next record from the queue, don't signal the not full condition yet and release // producers depending on whether the caller wants to or not. collection . add ( extract ( false , unblock ) ) ; } if ( n > 0 ) { // count -= n; notFull . signalAll ( ) ; } return new SynchRefImpl ( n , collection ) ; } finally { lock . unlock ( ) ; } }


Input: Insert element into the queue then possibly signal that the queue is not empty and block the producer on the element until permission to procede is given . [CODESPLIT] protected boolean insert ( E element , boolean unlockAndBlock ) { // Create a new record for the data item. SynchRecordImpl < E > record = new SynchRecordImpl < E > ( element ) ; boolean result = buffer . offer ( record ) ; if ( result ) { count ++ ; // Tell any waiting consumers that the queue is not empty. notEmpty . signal ( ) ; if ( unlockAndBlock ) { // Allow other threads to read/write the queue. lock . unlock ( ) ; // Wait until a consumer takes this data item. record . waitForConsumer ( ) ; } return true ; } else { return false ; } }


Input: Removes an element from the buffer and optionally unblocks the producer of the element if it is waiting and optionally signals that the { @link #notFull } condition may now be true . [CODESPLIT] protected SynchRecordImpl < E > extract ( boolean unblock , boolean signal ) { SynchRecordImpl < E > result = buffer . remove ( ) ; count -- ; if ( signal ) { notFull . signal ( ) ; } if ( unblock ) { result . releaseImmediately ( ) ; } return result ; }


Input: Fetches the next element from this iterator . [CODESPLIT] public Object next ( ) { try { Object ob = source . next ( ) ; return ob ; } catch ( RemoteException e ) { throw new IllegalStateException ( e ) ; } }


Input: Helper method for setting system properties to defaults when they are not already set . [CODESPLIT] public static boolean setSysPropertyIfNull ( String propname , boolean value ) { return Boolean . parseBoolean ( setSysPropertyIfNull ( propname , Boolean . toString ( value ) ) ) ; }


Input: Helper method for setting system properties to defaults when they are not already set . [CODESPLIT] public static short setSysPropertyIfNull ( String propname , short value ) { return Short . parseShort ( setSysPropertyIfNull ( propname , Short . toString ( value ) ) ) ; }


Input: Helper method for setting system properties to defaults when they are not already set . [CODESPLIT] public static int setSysPropertyIfNull ( String propname , int value ) { return Integer . parseInt ( setSysPropertyIfNull ( propname , Integer . toString ( value ) ) ) ; }


Input: Helper method for setting system properties to defaults when they are not already set . [CODESPLIT] public static long setSysPropertyIfNull ( String propname , long value ) { return Long . parseLong ( setSysPropertyIfNull ( propname , Long . toString ( value ) ) ) ; }


Input: Helper method for setting system properties to defaults when they are not already set . [CODESPLIT] public static float setSysPropertyIfNull ( String propname , float value ) { return Float . parseFloat ( setSysPropertyIfNull ( propname , Float . toString ( value ) ) ) ; }


Input: Helper method for setting system properties to defaults when they are not already set . [CODESPLIT] public static double setSysPropertyIfNull ( String propname , double value ) { return Double . parseDouble ( setSysPropertyIfNull ( propname , Double . toString ( value ) ) ) ; }


Input: Helper method for setting system properties to defaults when they are not already set . [CODESPLIT] public static String setSysPropertyIfNull ( String propname , String value ) { String property = System . getProperty ( propname ) ; if ( property == null ) { System . setProperty ( propname , value ) ; return value ; } else { return property ; } }


Input: Helper method for setting properties to defaults when they are not already set . [CODESPLIT] public boolean setPropertyIfNull ( String propname , boolean value ) { return Boolean . parseBoolean ( setPropertyIfNull ( propname , Boolean . toString ( value ) ) ) ; }


Input: Helper method for setting properties to defaults when they are not already set . [CODESPLIT] public short setPropertyIfNull ( String propname , short value ) { return Short . parseShort ( setPropertyIfNull ( propname , Short . toString ( value ) ) ) ; }


Input: Helper method for setting properties to defaults when they are not already set . [CODESPLIT] public int setPropertyIfNull ( String propname , int value ) { return Integer . parseInt ( setPropertyIfNull ( propname , Integer . toString ( value ) ) ) ; }


Input: Helper method for setting properties to defaults when they are not already set . [CODESPLIT] public long setPropertyIfNull ( String propname , long value ) { return Long . parseLong ( setPropertyIfNull ( propname , Long . toString ( value ) ) ) ; }


Input: Helper method for setting properties to defaults when they are not already set . [CODESPLIT] public float setPropertyIfNull ( String propname , float value ) { return Float . parseFloat ( setPropertyIfNull ( propname , Float . toString ( value ) ) ) ; }


Input: Helper method for setting properties to defaults when they are not already set . [CODESPLIT] public double setPropertyIfNull ( String propname , double value ) { return Double . parseDouble ( setPropertyIfNull ( propname , Double . toString ( value ) ) ) ; }


Input: Helper method for setting properties to defaults when they are not already set . [CODESPLIT] public String setPropertyIfNull ( String propname , String value ) { String property = super . getProperty ( propname ) ; if ( property == null ) { super . setProperty ( propname , value ) ; return value ; } else { return property ; } }


Input: Helper method for setting properties . [CODESPLIT] public boolean setProperty ( String propname , boolean value ) { setProperty ( propname , Boolean . toString ( value ) ) ; return value ; }


Input: Helper method for setting properties . [CODESPLIT] public short setProperty ( String propname , short value ) { setProperty ( propname , Short . toString ( value ) ) ; return value ; }


Input: Helper method for setting properties . [CODESPLIT] public int setProperty ( String propname , int value ) { setProperty ( propname , Integer . toString ( value ) ) ; return value ; }


Input: Helper method for setting properties . [CODESPLIT] public long setProperty ( String propname , long value ) { setProperty ( propname , Long . toString ( value ) ) ; return value ; }


Input: Helper method for setting properties . [CODESPLIT] public float setProperty ( String propname , float value ) { setProperty ( propname , Float . toString ( value ) ) ; return value ; }


Input: Helper method for setting properties . [CODESPLIT] public double setProperty ( String propname , double value ) { setProperty ( propname , Double . toString ( value ) ) ; return value ; }


Input: Parses a property as a boolean . [CODESPLIT] public boolean getPropertyAsBoolean ( String propName ) { String prop = getProperty ( propName ) ; return ( prop != null ) && Boolean . parseBoolean ( prop ) ; }


Input: Parses a property as an integer . [CODESPLIT] public Integer getPropertyAsInteger ( String propName ) { String prop = getProperty ( propName ) ; return ( prop != null ) ? Integer . valueOf ( prop ) : null ; }


Input: Parses a property as a long . [CODESPLIT] public Long getPropertyAsLong ( String propName ) { String prop = getProperty ( propName ) ; return ( prop != null ) ? Long . valueOf ( prop ) : null ; }


Input: Creates a clone of this scope to be attached to the tree at the site of a mixin reference . If an ArgumentsNode is passed each of its values override those defined by the mixin s parameters . [CODESPLIT] public ScopeNode callMixin ( String name , ArgumentsNode arguments ) { List < ExpressionGroupNode > argumentList = ( arguments != null ) ? NodeTreeUtils . getChildren ( arguments , ExpressionGroupNode . class ) : Collections . < ExpressionGroupNode > emptyList ( ) ; if ( argumentList . size ( ) > _parameterDefinitions . size ( ) ) { throw new IllegalMixinArgumentException ( name , _parameterDefinitions . size ( ) ) ; } // Clone scope and filter out any white space ScopeNode mixinScope = clone ( ) ; NodeTreeUtils . filterLineBreaks ( mixinScope ) ; // If arguments were passed, apply them for ( int i = 0 ; i < argumentList . size ( ) ; i ++ ) { ExpressionGroupNode argument = argumentList . get ( i ) ; // Replace the value of the definition VariableDefinitionNode parameter = mixinScope . _parameterDefinitions . get ( i ) ; parameter . clearChildren ( ) ; parameter . addChild ( argument ) ; } // Mark this scope's containing rule set as invisible since it has been used as a mixin getParent ( ) . setVisible ( false ) ; return mixinScope ; }


Input:
Some nodes are captured in additional structures to aid later resolution . [CODESPLIT] private void setAdditionVisitor ( ) { setAdditionVisitor ( new InclusiveNodeVisitor ( ) { /**
             * Add parameter set as a child for printing input, but also add each defined value to the variable map.
             */ @ Override public boolean add ( ParametersNode node ) { for ( VariableDefinitionNode variable : NodeTreeUtils . getChildren ( node , VariableDefinitionNode . class ) ) { _parameterDefinitions . add ( variable ) ; add ( variable ) ; } return super . add ( node ) ; } /**
             * Store the rule set's scope by selector group
             */ @ Override public boolean add ( RuleSetNode node ) { SelectorGroupNode selectorGroup = NodeTreeUtils . getFirstChild ( node , SelectorGroupNode . class ) ; for ( SelectorNode selectorNode : NodeTreeUtils . getChildren ( selectorGroup , SelectorNode . class ) ) { StringBuilder sb = new StringBuilder ( ) ; for ( Node selectorChild : selectorNode . getChildren ( ) ) { sb . append ( selectorChild . toString ( ) ) ; } String selector = sb . toString ( ) ; // Mixins lock on first definition if ( ! _selectorToRuleSetMap . containsKey ( selector ) ) { _selectorToRuleSetMap . put ( selector , node ) ; } } return super . add ( node ) ; } /**
             * Absorb all children of the given scope. This assumes that cloning is not necessary.
             */ @ Override public boolean add ( ScopeNode node ) { NodeTreeUtils . moveChildren ( node , ScopeNode . this ) ; return false ; // Don't add the original scope itself } /**
             * Store variable definitions in a map by name
             */ @ Override public boolean add ( VariableDefinitionNode node ) { String name = node . getName ( ) ; // "Variables" lock on first definition if ( ! _variableNameToValueMap . containsKey ( name ) ) { _variableNameToValueMap . put ( name , NodeTreeUtils . getFirstChild ( node , ExpressionGroupNode . class ) ) ; } return super . add ( node ) ; } /**
             * Store property nodes by name. If there are multiple properties for a given name, only retain the last one.
             */ @ Override public boolean add ( PropertyNode node ) { String name = node . getName ( ) ; // If this is the IE-specific "filter" property, always add it if ( name . equals ( FILTER_PROPERTY ) ) { return super . add ( node ) ; } // If the value of this property node is a vendor-specific keyword, always add it if ( node . getChildren ( ) . get ( 0 ) . toString ( ) . startsWith ( "-" ) ) { return super . add ( node ) ; } // Check if this property has been seen before if ( _propertyNameToNodeMap . containsKey ( name ) ) { PropertyNode oldPropertyNode = _propertyNameToNodeMap . get ( name ) ; int oldPropertyIndex = getChildren ( ) . indexOf ( oldPropertyNode ) ; if ( oldPropertyNode . isVisible ( ) ) { // Hide the unneeded property oldPropertyNode . setVisible ( false ) ; // Attempt to hide one surrounding white space node if ( ! hideWhiteSpaceNode ( oldPropertyIndex - 1 ) ) { hideWhiteSpaceNode ( oldPropertyIndex + 1 ) ; } } } // Store the property as the latest for this name _propertyNameToNodeMap . put ( name , node ) ; return super . add ( node ) ; } } ) ; }


Input: Recreate internal state before children are cloned . [CODESPLIT] @ Override protected void cloneChildren ( InternalNode node ) { ScopeNode scope = ( ScopeNode ) node ; // Reset internal state scope . _variableNameToValueMap = new HashMap < String , ExpressionGroupNode > ( ) ; scope . _selectorToRuleSetMap = new HashMap < String , RuleSetNode > ( ) ; scope . _parameterDefinitions = new ArrayList < VariableDefinitionNode > ( ) ; scope . _propertyNameToNodeMap = new HashMap < String , PropertyNode > ( ) ; scope . setAdditionVisitor ( ) ; super . cloneChildren ( node ) ; }


Input: ---------------------------------------------------------------------------------------------------------------- [CODESPLIT] private Connection getConnection ( ) { URL href = getHref ( ) ; checkArgument ( href != null , "Invalid URL: " + element . attr ( "href" ) ) ; return Jsoup . connect ( href . toString ( ) ) . method ( Method . GET ) . cookies ( document . getCookies ( ) ) ; }


Input: { [CODESPLIT] public SearchNode < O , T > search ( QueueSearchState < O , T > initSearch , Collection < T > startStates , int maxSteps , int searchSteps ) throws SearchNotExhaustiveException { // Initialize the queue with the start states set up in search nodes if this has not already been done. // This will only be done on the first call to this method, as enqueueStartStates sets a flag when it is // done. Subsequent searches continue from where the previous search left off. Have to call reset on // the search method to really start the search again from the start states. Queue < SearchNode < O , T > > queue = initSearch . enqueueStartStates ( startStates ) ; // Get the goal predicate configured as part of the enqueueing start states process. UnaryPredicate goalPredicate = initSearch . getGoalPredicate ( ) ; // Backtrack the most recent goal state, if one has been established. if ( mostRecentGoalNode != null ) { backtrack ( mostRecentGoalNode ) ; // Clear the most recent goal, now that it has been backtracked if required. mostRecentGoalNode = null ; } // Keep running until the queue becomes empty or a goal state is found. while ( ! queue . isEmpty ( ) ) { // Extract or peek at the head element from the queue. SearchNode headNode = queue . remove ( ) ; // Apply the current nodes operator to establish its shared state. Reversable reversableState = ( ReTraversable ) headNode . getState ( ) ; reversableState . applyOperator ( ) ; // Expand the successors into the queue whether the current node is a goal state or not. // This prepares the queue for subsequent searches, ensuring that goal states do not block // subsequent goal states that exist beyond them. headNode . unexaminedSuccessorCount = headNode . expandSuccessors ( queue , reverseEnqueue ) ; // As the head node is about to be goal tested, reduce the unexamined successor count of its predecessor. if ( headNode . getParent ( ) != null ) { headNode . getParent ( ) . unexaminedSuccessorCount -- ; } // Check if the current node is a goal state. if ( goalPredicate . evaluate ( headNode . getState ( ) ) ) { // Remember this goal node so that subsequent searches remember to backtrack over it. mostRecentGoalNode = headNode ; return headNode ; } // Backtrack over all fully exhausted nodes from the current position, as required. backtrack ( headNode ) ; // Check if there is a maximum number of steps limit and increase the step count and check the limit if so. if ( maxSteps > 0 ) { searchSteps ++ ; // Update the search state with the number of steps taken so far. initSearch . setStepsTaken ( searchSteps ) ; if ( searchSteps >= maxSteps ) { // The maximum number of steps has been reached, however if the queue is now empty then the search // has just completed within the maximum. Check if the queue is empty and return null if so. if ( queue . isEmpty ( ) ) { return null ; } // Quit without a solution as the max number of steps has been reached but because there are still // more states in the queue then raise a search failure exception. else { throw new SearchNotExhaustiveException ( "Maximum number of steps reached." , null ) ; } } } } // No goal state was found so return null return null ; }


Input: Back - tracks from the specified node moving succesively upwards through the chain of parent nodes until a node is encountered that has unexamined successors . This method implements the backtracking searches reverse direction . By checking for the presence of unexamined successors this method only backtracks where necessary . [CODESPLIT] protected void backtrack ( SearchNode checkNode ) { while ( ( checkNode != null ) && ( checkNode . unexaminedSuccessorCount == 0 ) ) { Reversable undoState = ( ReTraversable ) checkNode . getState ( ) ; undoState . undoOperator ( ) ; checkNode = checkNode . getParent ( ) ; } }


Input: { [CODESPLIT] public void emmitCode ( WAMCompiledPredicate predicate ) throws LinkageException { // Keep track of the offset into which the code was loaded. int entryPoint = codeBuffer . position ( ) ; int length = ( int ) predicate . sizeof ( ) ; // If the code is for a program clause, store the programs entry point in the call table. WAMCallPoint callPoint = setCodeAddress ( predicate . getName ( ) , entryPoint , length ) ; // Emmit code for the clause into this machine. predicate . emmitCode ( codeBuffer , this , callPoint ) ; // Notify the native machine of the addition of new code. codeAdded ( codeBuffer , entryPoint , length ) ; // Notify any attached DPI monitor of the addition of new code. if ( monitor != null ) { monitor . onCodeUpdate ( this , entryPoint , length ) ; } }


Input: { [CODESPLIT] public void emmitCode ( WAMCompiledQuery query ) throws LinkageException { // Keep track of the offset into which the code was loaded. int entryPoint = codeBuffer . position ( ) ; int length = ( int ) query . sizeof ( ) ; // If the code is for a program clause, store the programs entry point in the call table. WAMCallPoint callPoint = new WAMCallPoint ( entryPoint , length , - 1 ) ; // Emmit code for the clause into this machine. query . emmitCode ( codeBuffer , this , callPoint ) ; // Notify the native machine of the addition of new code. codeAdded ( codeBuffer , entryPoint , length ) ; // Notify any attached DPI monitor of the addition of new code. if ( monitor != null ) { monitor . onCodeUpdate ( this , entryPoint , length ) ; } }


Input: Extracts the raw byte code from the machine for a given call table entry . [CODESPLIT] public byte [ ] retrieveCode ( WAMCallPoint callPoint ) { byte [ ] result = new byte [ callPoint . length ] ; codeBuffer . get ( result , callPoint . entryPoint , callPoint . length ) ; return result ; }


Input: { [CODESPLIT] public ByteBuffer getCodeBuffer ( int start , int length ) { // Take a read only slice onto an appropriate section of the code buffer. ByteBuffer readOnlyBuffer = codeBuffer . asReadOnlyBuffer ( ) ; readOnlyBuffer . position ( start ) ; readOnlyBuffer . limit ( start + length ) ; return readOnlyBuffer ; }


Input: Runs a query and for every non - anonymous variable in the query decodes its binding value from the heap and returns it in a set of variable bindings . [CODESPLIT] protected Set < Variable > executeAndExtractBindings ( WAMCompiledQuery query ) { // Execute the query and program. The starting point for the execution is the first functor in the query // body, this will follow on to the subsequent functors and make calls to functors in the compiled programs. boolean success = execute ( query . getCallPoint ( ) ) ; // Used to collect the results in. Set < Variable > results = null ; // Collect the results only if the resolution was successfull. if ( success ) { results = new HashSet < Variable > ( ) ; // The same variable context is used accross all of the results, for common use of variables in the // results. Map < Integer , Variable > varContext = new HashMap < Integer , Variable > ( ) ; // For each of the free variables in the query, extract its value from the location on the heap pointed to // by the register that holds the variable. /*log.fine("query.getVarNames().size() =  " + query.getVarNames().size());*/ for ( byte reg : query . getVarNames ( ) . keySet ( ) ) { int varName = query . getVarNames ( ) . get ( reg ) ; if ( query . getNonAnonymousFreeVariables ( ) . contains ( varName ) ) { int addr = derefStack ( reg ) ; Term term = decodeHeap ( addr , varContext ) ; results . add ( new Variable ( varName , term , false ) ) ; } } } return results ; }


Input:
Decodes a term from the raw byte representation on the machines heap into an abstract syntax tree . [CODESPLIT] protected Term decodeHeap ( int start , Map < Integer , Variable > variableContext ) { /*log.fine("private Term decodeHeap(int start = " + start + ", Map<Integer, Variable> variableContext = " +
            variableContext + "): called");*/ // Used to hold the decoded argument in. Term result = null ; // Dereference the initial heap pointer. int addr = deref ( start ) ; byte tag = getDerefTag ( ) ; int val = getDerefVal ( ) ; /*log.fine("addr = " + addr);*/ /*log.fine("tag = " + tag);*/ /*log.fine("val = " + val);*/ switch ( tag ) { case REF : { // Check if a variable for the address has already been created in this context, and use it if so. Variable var = variableContext . get ( val ) ; if ( var == null ) { var = new Variable ( varNameId . decrementAndGet ( ) , null , false ) ; variableContext . put ( val , var ) ; } result = var ; break ; } case STR : { // Decode f/n from the STR data. int fn = getHeap ( val ) ; int f = fn & 0x00ffffff ; /*log.fine("fn = " + fn);*/ /*log.fine("f = " + f);*/ // Look up and initialize this functor name from the symbol table. FunctorName functorName = getDeinternedFunctorName ( f ) ; // Fill in this functors name and arity and allocate storage space for its arguments. int arity = functorName . getArity ( ) ; Term [ ] arguments = new Term [ arity ] ; // Loop over all of the functors arguments, recursively decoding them. for ( int i = 0 ; i < arity ; i ++ ) { arguments [ i ] = decodeHeap ( val + 1 + i , variableContext ) ; } // Create a new functor to hold the decoded data. result = new Functor ( f , arguments ) ; break ; } case WAMInstruction . CON : { //Decode f/n from the CON data. int f = val & 0x3fffffff ; /*log.fine("f = " + f);*/ // Create a new functor to hold the decoded data. result = new Functor ( f , null ) ; break ; } case WAMInstruction . LIS : { FunctorName functorName = new FunctorName ( "cons" , 2 ) ; int f = internFunctorName ( functorName ) ; // Fill in this functors name and arity and allocate storage space for its arguments. int arity = functorName . getArity ( ) ; Term [ ] arguments = new Term [ arity ] ; // Loop over all of the functors arguments, recursively decoding them. for ( int i = 0 ; i < arity ; i ++ ) { arguments [ i ] = decodeHeap ( val + i , variableContext ) ; } // Create a new functor to hold the decoded data. result = new Functor ( f , arguments ) ; break ; } default : throw new IllegalStateException ( "Encountered unknown tag type on the heap." ) ; } return result ; }


Input: Captures an objects state in this memento . [CODESPLIT] public void capture ( ) { // Get the class of the object to build a memento for. Class cls = ob . getClass ( ) ; // Iterate through the classes whole inheritence chain. while ( ! cls . equals ( Object . class ) ) { // Get the classes fields. Field [ ] attrs = cls . getDeclaredFields ( ) ; // Build a new map to put the fields in for the current class. HashMap map = new HashMap ( ) ; // Cache the field values by the class name. values . put ( cls , map ) ; // Loop over all the fields in the current class. for ( Field attr : attrs ) { // Make the field accessible (it may be protected or private). attr . setAccessible ( true ) ; // Check that the field should be captured. if ( shouldBeSaved ( attr ) ) { // Use a try block as access to the field may fail, although this should not happen because // even private, protected and package fields have been made accessible. try { // Cache the field by its name. map . put ( attr . getName ( ) , attr . get ( ob ) ) ; } catch ( IllegalAccessException e ) { // The field could not be accessed but all fields have been made accessible so this should // not happen. throw new IllegalStateException ( "Field '" + attr . getName ( ) + "' could not be accessed but the 'setAccessible(true)' method was invoked on it." , e ) ; } } } // Get the superclass for the next step of the iteration over the whole inheritence chain. cls = cls . getSuperclass ( ) ; } }


Input: Restores the values currently in this memento to the specified object . [CODESPLIT] public void restore ( Object ob ) throws NoSuchFieldException { /*log.fine("public void map(Object ob): called");*/ /*log.fine("class is " + ob.getClass());*/ // Iterate over the whole inheritence chain. for ( Object key : values . keySet ( ) ) { // Get the next class from the cache. Class cls = ( Class ) key ; // Get the cache of field values for the class. Map vals = ( HashMap ) values . get ( cls ) ; // Loop over all fields in the class. for ( Object o : vals . keySet ( ) ) { // Get the next field name. String attr = ( String ) o ; // Get the next field value. Object val = vals . get ( attr ) ; // Get a reference to the field in the object. Field f = cls . getDeclaredField ( attr ) ; // Make the field accessible (it may be protected, package or private). f . setAccessible ( true ) ; // Use a try block as writing to the field may fail. try { // Write to the field. f . set ( ob , val ) ; } catch ( IllegalAccessException e ) { // The field could not be written to but all fields have been made accessible so this should // not happen. throw new IllegalStateException ( "Field '" + f . getName ( ) + "' could not be accessed but the 'setAccessible(true)' method was invoked on it." , e ) ; } } } }


Input: Gets the value of the named field of the specified class . [CODESPLIT] public Object get ( Class cls , String attr ) { HashMap map ; // See if the class exists in the cache. if ( ! values . containsKey ( cls ) ) { // Class not in cache so return null. return null ; } // Get the cache of field values for the class. map = ( HashMap ) values . get ( cls ) ; // Extract the specified field from the cache. return map . get ( attr ) ; }


Input: Places the specified value into the memento based on the field s declaring class and name . [CODESPLIT] public void put ( Class cls , String attr , Object val ) { /*log.fine("public void put(Class cls, String attr, Object val): called");*/ /*log.fine("class name is " + cls.getName());*/ /*log.fine("attribute is " + attr);*/ /*log.fine("value to set is " + val);*/ HashMap map ; // Check that the cache for the class exists in the cache. if ( values . containsKey ( cls ) ) { // Get the cache of field for the class. map = ( HashMap ) values . get ( cls ) ; } else { // The class does not already exist in the cache to create a new cache for its fields. map = new HashMap ( ) ; // Cache the new field cache against the class. values . put ( cls , map ) ; } // Store the attribute in the field cache for the class. map . put ( attr , val ) ; }


Input: Generates a list of all the fields of the object that this memento maps for a given class . [CODESPLIT] public Collection getAllFieldNames ( Class cls ) { /*log.fine("public Collection getAllFieldNames(Class cls): called");*/ // See if the class exists in the cache if ( ! values . containsKey ( cls ) ) { // Class not in cache so return null return null ; } // Get the cache of fields for the class Map map = ( HashMap ) values . get ( cls ) ; // Return all the keys from cache of fields return map . keySet ( ) ; }


Input: Creates the interpreter and launches its top - level run loop . [CODESPLIT] public static void main ( String [ ] args ) { try { VariableAndFunctorInterner interner = new VariableAndFunctorInternerImpl ( "Prolog_Variable_Namespace" , "Prolog_Functor_Namespace" ) ; PrologCompiler compiler = new PrologCompiler ( interner ) ; PrologResolver resolver = new PrologResolver ( interner ) ; Parser < Clause , Token > parser = new InteractiveParser ( interner ) ; PrologEngine engine = new PrologEngine ( parser , interner , compiler , resolver ) ; engine . reset ( ) ; ResolutionInterpreter < PrologCompiledClause , PrologCompiledClause > interpreter = new ResolutionInterpreter < PrologCompiledClause , PrologCompiledClause > ( engine ) ; interpreter . interpreterLoop ( ) ; } catch ( Exception e ) { /*log.log(Level.SEVERE, e.getMessage(), e);*/ e . printStackTrace ( new PrintStream ( System . err ) ) ; System . exit ( - 1 ) ; } }


Input: Implementation of the prod - script goal . [CODESPLIT] public void execute ( ) throws MojoExecutionException , MojoFailureException { //log.debug("public void execute() throws MojoExecutionException: called"); // Turn each of the test runner command lines into a script. for ( String commandName : commands . keySet ( ) ) { if ( prodScriptOutDirectory != null ) { writeUnixScript ( commandName , prodScriptOutDirectory ) ; writeWindowsScript ( commandName , prodScriptOutDirectory ) ; } } }


Input: { [CODESPLIT] protected String appendClasspath ( String commandLine , boolean unix ) { String pathSeperator ; String seperator ; String classpathDirPrefix ; if ( unix ) { pathSeperator = "/" ; seperator = ":" ; classpathDirPrefix = JAR_DIR_PREFIX_UNIX ; } else { pathSeperator = "\\" ; seperator = ";" ; classpathDirPrefix = JAR_DIR_PREFIX_WINDOWS ; } for ( Iterator i = classpathElements . iterator ( ) ; i . hasNext ( ) ; ) { String cpPath = ( String ) i . next ( ) ; int lastSlash = cpPath . lastIndexOf ( "/" ) ; int lastBackslash = cpPath . lastIndexOf ( "\\" ) ; int lastPathSeperator = ( lastSlash > lastBackslash ) ? lastSlash : lastBackslash ; if ( lastPathSeperator != - 1 ) { cpPath = cpPath . substring ( lastPathSeperator + 1 ) ; } //cpPath = cpPath.replace("/", pathSeperator); if ( cpPath . endsWith ( ".jar" ) ) { commandLine += classpathDirPrefix + pathSeperator + cpPath + seperator ; } } commandLine += classpathDirPrefix + pathSeperator + outputJar + ".jar" ; return commandLine ; }


Input: { [CODESPLIT] public void setup ( ByteBuffer buffer , int t , int n ) { this . buffer = buffer ; this . offset = t ; this . size = ( n >> 3 ) ; // Shift by 3 as key and value must be stored as a pair, making 8 bytes per entry. }


Input: { [CODESPLIT] public int get ( int key ) { int addr = addr ( hash ( key ) ) ; while ( true ) { int tableKey = buffer . getInt ( addr ) ; if ( key == tableKey ) { return buffer . getInt ( addr + 4 ) ; } if ( tableKey == 0 ) { return 0 ; } addr += 8 ; } }


Input: { [CODESPLIT] public void put ( int key , int val ) { int addr = addr ( hash ( key ) ) ; while ( true ) { int tableKey = buffer . getInt ( addr ) ; if ( key == tableKey ) { break ; } if ( tableKey == 0 ) { break ; } addr += 8 ; } buffer . putInt ( addr , key ) ; buffer . putInt ( addr + 4 , val ) ; }


Input: Inserts the specified element onto the tail of this queue . [CODESPLIT] public boolean offer ( E o ) { /*log.fine("public boolean offer(E o): called");*/ /*log.fine("o = " + o);*/ // Ensure that the item to add is not null. if ( o == null ) { throw new IllegalArgumentException ( "The 'o' parameter may not be null." ) ; } // Derive the integer priority of the element using the priority function, shift it into this queues range if // necessary and adjust it to any offset caused by lowest priority not equal to zero. int level = priorityToLevel ( p . apply ( o ) ) ; /*log.fine("offer level = " + level);*/ // Create a new node to hold the new data element. Node < E > newNode = new DataNode < E > ( o , markers [ level + 1 ] ) ; // Add the element to the tail of the queue with matching level, looping until this can complete as an atomic // operation. while ( true ) { // Get tail and next ref. Would expect next ref to be null, but other thread may update it. Node < E > t = markers [ level + 1 ] . getTail ( ) ; Node < E > s = t . getNext ( ) ; /*log.fine("t = " + t);*/ /*log.fine("s = " + s);*/ // Recheck the tail ref, to ensure other thread has not already moved it. This can potentially prevent // a relatively expensive compare and set from failing later on, if another thread has already shited // the tail. if ( t == markers [ level + 1 ] . getTail ( ) ) { /*log.fine("t is still the tail.");*/ // Check that the next element reference on the tail is the tail marker, to confirm that another thread // has not updated it. Again, this may prevent a cas from failing later. if ( s == markers [ level + 1 ] ) { /*log.fine("s is  the tail marker.");*/ // Try to join the new tail onto the old one. if ( t . casNext ( s , newNode ) ) { // The tail join was succesfull, so now update the queues tail reference. No conflict should // occurr here as the tail join was succesfull, so its just a question of updating the tail // reference. A compare and set is still used because ... markers [ level + 1 ] . casTail ( t , newNode ) ; // Increment the queue size count. count . incrementAndGet ( ) ; return true ; } } // Update the tail reference, other thread may also be doing the same. else { // Why bother doing this at all? I suppose, because another thread may be stalled and doing this // will enable this one to keep running. // Update the tail reference for the queue because another thread has already added a new tail // but not yet managed to update the tail reference. markers [ level + 1 ] . casTail ( t , s ) ; } } } }


Input: Retrieves and removes the head of this queue or null if this queue is empty . [CODESPLIT] public E poll ( ) { /*log.fine("public E poll(): called");*/ // This is used to keep track of the level of the list that is found to have data in it. int currentLevel = 0 ; while ( true ) { // This is used to locate the marker head of a list that contains data. Marker < E > h = null ; // This is used to locate the potential data node of a list with data in it. Another thread may already // have taken this data. Node < E > first = null ; // Second data item, may also be tail marker, first data item of next list, or null at end of last list. Node < E > second = null ; // Loop down any empty lists at the front of the queue until a list with data in it is found. for ( ; currentLevel < n ; currentLevel ++ ) { h = markers [ currentLevel ] ; first = h . getNext ( ) ; second = first . getNext ( ) ; // Check if the list at the current level is not empty and should be tried for data. if ( ! h . isEmpty ( markers [ currentLevel + 1 ] ) ) { break ; } // Check if the current level is empty and is the last level, in which case return null. else if ( currentLevel == ( n - 1 ) ) { // log.info("returning null from level loop."); return null ; } // Else if the current level is empty loop to the next one to see if it has data. } /*log.fine("current poll level = " + currentLevel);*/ // This is used to locate the tail of the list that has been found with data in it. Node < E > t = markers [ currentLevel + 1 ] . getTail ( ) ; // Check that the first data item has not yet been taken. Another thread may already have taken it, // in which case performing a relatively expensive cas on the head will fail. If first is still intact // then second will be intact too. if ( first == h . getNext ( ) ) { // Check if the queue has become empty. if ( h . isEmpty ( markers [ currentLevel + 1 ] ) ) { // Another thread has managed to take data from the queue, leaving it empty. // First won't be null. It may point to tail though... if ( first == null ) { // Don't want to return here, want to try the next list. The list loop has a return null // once it gets to the end to take care of that. // log.info("returning null as first == null"); return null ; } else { // Not sure yet why castail here? Does this repair a broken tail ref left after the last item // was taken? markers [ currentLevel + 1 ] . casTail ( t , first ) ; } } // The queue contains data, so try to move its head marker reference from the first data item, onto the // second item (which may be data, or the tail marker). If this succeeds, then the first data node // has been atomically extracted from the head of the queue. else if ( h . casNext ( first , second ) ) { // h Does not refer to an empty queue, so first must be a data node. DataNode < E > firstDataNode = ( ( DataNode < E > ) first ) ; E item = firstDataNode . getItem ( ) ; // Even though the empty test did not indicate that the list was empty, it may contain null // data items, because the remove method doesn't extract nodes on a remove. These need to be skipped // over. Could they be removed here? if ( item != null ) { firstDataNode . setItem ( null ) ; /*log.fine("returing item = " + item);*/ // Decrement the queue size count. count . decrementAndGet ( ) ; return item ; } // else skip over deleted item, continue trying at this level. Go back an retry starting from same // level. List at this level may now be empty, or may get the next item from it. // else skip over marker element. just make markers return null for item to skip them? No, because // need to advance currentLevel and get head and tail markers for the next level. but then, next // level advance will occur when this level is retried and found to be empty won't it? } } } }


Input: Creates the correct type of search nodes for this search . This search uses ordinary search nodes . [CODESPLIT] public SearchNode < O , T > createSearchNode ( T state ) { return new SearchNode < O , T > ( state ) ; }


Input: Creates the correct type of queue for this search . This search uses a priority queue ordered by path cost . [CODESPLIT] public Queue < SearchNode < O , T > > createQueue ( ) { return new PriorityQueue < SearchNode < O , T > > ( 11 , new UniformCostComparator ( ) ) ; }


Input: { @inheritDoc } [CODESPLIT] public void open ( ) { // Build a text grid panel in the left position. grid = componentFactory . createTextGrid ( ) ; grid . insertVerticalSeparator ( 3 , 10 ) ; mainWindow . showLeftPane ( componentFactory . createTextGridPanel ( grid ) ) ; // Build a table model on the text grid, and construct a register monitor on the table. table = grid . createTable ( 0 , 0 , 20 , 20 ) ; monitor = new RegisterSetMonitor ( table ) ; // Attach a listener for updates to the register table. table . addTextTableListener ( new TableUpdateHandler ( ) ) ; grid . addTextGridSelectionListener ( new SelectionHandler ( ) ) ; }


Input: Provides a simple depth first walk over a term . [CODESPLIT] public static TermWalker simpleWalker ( TermVisitor visitor ) { DepthFirstBacktrackingSearch < Term , Term > search = new DepthFirstBacktrackingSearch < Term , Term > ( ) ; return new TermWalker ( search , new DefaultTraverser ( ) , visitor ) ; }


Input: Provides a depth first walk over a term visiting only when a goal predicate matches . [CODESPLIT] public static TermWalker goalWalker ( UnaryPredicate < Term > unaryPredicate , TermVisitor visitor ) { TermWalker walker = simpleWalker ( visitor ) ; walker . setGoalPredicate ( unaryPredicate ) ; return walker ; }


Input: Provides a positional depth first walk over a term . [CODESPLIT] public static TermWalker positionalWalker ( PositionalTermVisitor visitor ) { PositionalTermTraverser positionalTraverser = new PositionalTermTraverserImpl ( ) ; positionalTraverser . setContextChangeVisitor ( visitor ) ; visitor . setPositionalTraverser ( positionalTraverser ) ; return new TermWalker ( new DepthFirstBacktrackingSearch < Term , Term > ( ) , positionalTraverser , visitor ) ; }


Input: Provides a positional depth first walk over a term visiting only when a goal predicate matches . [CODESPLIT] public static TermWalker positionalGoalWalker ( UnaryPredicate < Term > unaryPredicate , PositionalTermVisitor visitor ) { TermWalker walker = positionalWalker ( visitor ) ; walker . setGoalPredicate ( unaryPredicate ) ; return walker ; }


Input: Provides a positional postfix walk over a term . [CODESPLIT] public static TermWalker positionalPostfixWalker ( PositionalTermVisitor visitor ) { PositionalTermTraverser positionalTraverser = new PositionalTermTraverserImpl ( ) ; positionalTraverser . setContextChangeVisitor ( visitor ) ; visitor . setPositionalTraverser ( positionalTraverser ) ; return new TermWalker ( new PostFixSearch < Term , Term > ( ) , positionalTraverser , visitor ) ; }


Input: { [CODESPLIT] public void addToDomain ( PrologCompiledClause term ) { List < PrologCompiledClause > predicate = domain . get ( term . getHead ( ) . getName ( ) ) ; if ( predicate == null ) { predicate = new LinkedList < PrologCompiledClause > ( ) ; domain . put ( term . getHead ( ) . getName ( ) , predicate ) ; } predicate . add ( term ) ; }


Input:
{ [CODESPLIT] public void setQuery ( PrologCompiledClause query ) { // Reset the search in order to initialize it. resolutionSearch . reset ( ) ; // Keep a reference to the current query. currentQuery = query ; // Create the starting point for the resolution, consisting of the queries to resolve as the intial goal stack, // and an empty list of bindings. goalStack = new StackQueue < BuiltInFunctor > ( ) ; // Create a fresh list to hold the results of the resolution in. bindings = new StackQueue < Variable > ( ) ; // Create the initial state of the proof search. ResolutionState initialState = new ResolutionStateImpl ( query ) ; addStartState ( initialState ) ; // If printing execution traces, ensure the execution indenter starts from zero. /*if (TRACE)
        {
            indenter.reset();
        }*/ }


Input: { [CODESPLIT] public Set < Variable > resolve ( ) { // Find all free variables in the query. Set < Variable > freeVars = TermUtils . findFreeNonAnonymousVariables ( currentQuery ) ; // Used to collect the results in. Set < Variable > results = null ; // Search for the next available solution. SearchNode solution ; try { solution = findGoalPath ( ) ; } catch ( SearchNotExhaustiveException e ) { // The search may fail if the maximum number of search steps is reached. This limit is not turned on by // default. If this happens, null is returned, indicating that no solution was found. // Exception ignored as empty search results are noted and dealt with by returning null. e = null ; solution = null ; results = null ; } // Check that a solution was found and return the variable bindings from it if so. Only the variable bindings // that were free and non-anonymous in the original query are returned. if ( solution != null ) { results = new HashSet < Variable > ( freeVars ) ; } return results ; }


Input:
{ @inheritDoc } [CODESPLIT] public void reset ( ) { // Empty the knowledge base and clear the current query. domain = new HashMap < Integer , List < PrologCompiledClause > > ( ) ; currentQuery = null ; // Reset the underlying search. resolutionSearch . reset ( ) ; // If printing execution traces, ensure the execution indenter starts from zero. /*if (TRACE)
        {
            indenter.reset();
        }*/ }


Input: { [CODESPLIT] public ResolutionState search ( ) throws SearchNotExhaustiveException { SearchNode < ResolutionState , ResolutionState > path = findGoalPath ( ) ; if ( path != null ) { return path . getState ( ) ; } else { return null ; } }


Input: { [CODESPLIT] public Iterator < Set < Variable > > iterator ( ) { // Find all free variables in the query. final Set < Variable > freeVars = TermUtils . findFreeNonAnonymousVariables ( currentQuery ) ; Function < ResolutionState , Set < Variable > > listFunction = new Function < ResolutionState , Set < Variable > > ( ) { public Set < Variable > apply ( ResolutionState state ) { return freeVars ; } } ; return new Filterator < ResolutionState , Set < Variable > > ( Searches . allSolutions ( this ) , listFunction ) ; }


Input: Get properties from an input stream . [CODESPLIT] public static Properties getProperties ( InputStream is ) throws IOException { /*log.fine("getProperties(InputStream): called");*/ // Create properties object laoded from input stream Properties properties = new Properties ( ) ; properties . load ( is ) ; return properties ; }


Input: Get properties from a file . [CODESPLIT] public static Properties getProperties ( File file ) throws IOException { /*log.fine("getProperties(File): called");*/ // Open the file as an input stream InputStream is = new FileInputStream ( file ) ; // Create properties object loaded from the stream Properties properties = getProperties ( is ) ; // Close the file is . close ( ) ; return properties ; }


Input: Get properties from a url . [CODESPLIT] public static Properties getProperties ( URL url ) throws IOException { /*log.fine("getProperties(URL): called");*/ // Open the URL as an input stream InputStream is = url . openStream ( ) ; // Create properties object loaded from the stream Properties properties = getProperties ( is ) ; // Close the url is . close ( ) ; return properties ; }


Input: Get properties from a path name . The path name may refer to either a file or a URL . [CODESPLIT] public static Properties getProperties ( String pathname ) throws IOException { /*log.fine("getProperties(String): called");*/ // Check that the path is not null if ( pathname == null ) { return null ; } // Check if the path is a URL if ( isURL ( pathname ) ) { // The path is a URL return getProperties ( new URL ( pathname ) ) ; } else { // Assume the path is a file name return getProperties ( new File ( pathname ) ) ; } }


Input: Trims whitespace from property values . This method returns a new set of properties the same as the properties specified as an argument but with any white space removed by the { @link java . lang . String#trim } method . [CODESPLIT] public static Properties trim ( Properties properties ) { Properties trimmedProperties = new Properties ( ) ; // Loop over all the properties for ( Object o : properties . keySet ( ) ) { String next = ( String ) o ; String nextValue = properties . getProperty ( next ) ; // Trim the value if it is not null if ( nextValue != null ) { nextValue . trim ( ) ; } // Store the trimmed value in the trimmed properties trimmedProperties . setProperty ( next , nextValue ) ; } return trimmedProperties ; }


Input: Helper method . Guesses whether a string is a URL or not . A String is considered to be a url if it begins with http : ftp : or uucp : . [CODESPLIT] private static boolean isURL ( String name ) { return ( name . toLowerCase ( ) . startsWith ( "http:" ) || name . toLowerCase ( ) . startsWith ( "ftp:" ) || name . toLowerCase ( ) . startsWith ( "uucp:" ) ) ; }


Input: { @inheritDoc } [CODESPLIT] protected void paintComponent ( Graphics g ) { Graphics2D graphics2D = ( Graphics2D ) g . create ( ) ; Rectangle clipRect = ( Rectangle ) g . getClip ( ) ; // Work out the area to be painted in grid coordinates against the clipping rectangle. int startCol = xToCol ( clipRect . x ) ; int startRow = yToRow ( clipRect . y ) ; int cols = xToCol ( clipRect . x + clipRect . width ) ; int rows = yToRow ( clipRect . y + clipRect . height ) ; graphics2D . setFont ( getFont ( ) ) ; graphics2D . setColor ( getBackground ( ) ) ; graphics2D . fillRect ( clipRect . x , clipRect . y , clipRect . width , clipRect . height ) ; initializeFontMetrics ( ) ; if ( useAntiAliasing ) { graphics2D . setRenderingHint ( RenderingHints . KEY_ANTIALIASING , RenderingHints . VALUE_ANTIALIAS_ON ) ; graphics2D . setRenderingHint ( RenderingHints . KEY_RENDERING , RenderingHints . VALUE_RENDER_QUALITY ) ; } SortedMap < Integer , Integer > hSeps = model . getHorizontalSeparators ( ) ; int hSepOffset = 0 ; for ( int row = 0 ; row <= rows ; row ++ ) { Integer hNextSep = null ; if ( ! hSeps . isEmpty ( ) ) { hNextSep = hSeps . firstKey ( ) ; } if ( ( hNextSep != null ) && ( hNextSep == row ) ) { hSepOffset += hSeps . get ( hNextSep ) ; hSeps . remove ( hNextSep ) ; } SortedMap < Integer , Integer > vSeps = model . getVerticalSeparators ( ) ; int vSepOffset = 0 ; for ( int col = 0 ; col <= cols ; col ++ ) { Integer vNextSep = null ; if ( ! vSeps . isEmpty ( ) ) { vNextSep = vSeps . firstKey ( ) ; } if ( ( vNextSep != null ) && ( vNextSep == col ) ) { int vSepWidth = vSeps . get ( vNextSep ) ; vSepOffset += vSepWidth ; vSeps . remove ( vNextSep ) ; // If adding a vertical separator row attributes should be rendered within it to fill the space // left by the separator. AttributeSet attributes = model . getRowAttribute ( row ) ; Color bgColor = ( attributes != null ) ? ( Color ) attributes . get ( AttributeSet . BACKGROUND_COLOR ) : null ; bgColor = ( bgColor == null ) ? getBackground ( ) : bgColor ; graphics2D . setColor ( bgColor ) ; graphics2D . fillRect ( colToX ( col ) + vSepOffset - vSepWidth , rowToY ( row ) + hSepOffset , colToX ( col ) + vSepOffset , charHeight ) ; } // Only render if within the clip rectangle if ( ( col >= startCol ) && ( row >= startRow ) ) { char character = model . getCharAt ( col , row ) ; AttributeSet attributes = model . getAttributeAt ( col , row ) ; Color bgColor = ( attributes != null ) ? ( Color ) attributes . get ( AttributeSet . BACKGROUND_COLOR ) : null ; bgColor = ( bgColor == null ) ? getBackground ( ) : bgColor ; graphics2D . setColor ( bgColor ) ; graphics2D . fillRect ( colToX ( col ) + vSepOffset , rowToY ( row ) + hSepOffset , charWidth , charHeight ) ; graphics2D . setColor ( getForeground ( ) ) ; graphics2D . drawString ( Character . toString ( character ) , colToX ( col ) + vSepOffset , ( rowToY ( ( row + 1 ) ) ) - descent + hSepOffset ) ; } } } graphics2D . dispose ( ) ; }


Input: Computes the rendered dimensions of the text grid model on screen . Used for sizing this component . [CODESPLIT] protected Dimension computeGridSize ( ) { int cols = model . getWidth ( ) ; int rows = model . getHeight ( ) ; int horizSeparatorSize = 0 ; for ( int size : model . getHorizontalSeparators ( ) . values ( ) ) { horizSeparatorSize += size ; } int vertSeparatorSize = 0 ; for ( int size : model . getVerticalSeparators ( ) . values ( ) ) { vertSeparatorSize += size ; } return new Dimension ( vertSeparatorSize + colToX ( cols ) , horizSeparatorSize + rowToY ( rows ) ) ; }


Input: Sets up metrics relating to the size of the font used to display the text grid . This only needs to be done once but this method can be called many times as it is guarded by an initialization flag to prevent these being calculated many times . [CODESPLIT] private void initializeFontMetrics ( ) { if ( ! fontMetricsInitialized ) { FontMetrics fontMetrics = getFontMetrics ( getFont ( ) ) ; charWidth = fontMetrics . charWidth ( ' ' ) ; charHeight = fontMetrics . getHeight ( ) ; descent = fontMetrics . getDescent ( ) ; fontMetricsInitialized = true ; } }


Input: Adds a property changed listener to be notified of changes to the application state . [CODESPLIT] public void addPropertyChangeListener ( PropertyChangeListener l ) { // Check if the listneres list has been initialized if ( listeners == null ) { // Listeneres list not intialized so create a new list listeners = new ArrayList ( ) ; } synchronized ( listeners ) { // Add the new listener to the list listeners . add ( l ) ; } }


Input: Adds a property changed listener to be notified of changes to the named property . [CODESPLIT] public void addPropertyChangeListener ( String p , PropertyChangeListener l ) { // Check if the listeneres list has been initialized if ( listeners == null ) { // Listeneres list not initialized so create a new list listeners = new ArrayList ( ) ; } synchronized ( listeners ) { // Add the new listener to the list listeners . add ( l ) ; } }


Input: Removes the specified property change listener from the list of active listeners . [CODESPLIT] public void removePropertyChangeListener ( String p , PropertyChangeListener l ) { if ( listeners == null ) { return ; } synchronized ( listeners ) { listeners . remove ( l ) ; } }


Input: Notifies all property change listeners of the given PropertyChangeEvent . [CODESPLIT] protected void firePropertyChange ( PropertyChangeEvent evt ) { /*log.fine("firePropertyChange: called");*/ // Take a copy of the event as a final variable so that it can be used in an inner class final PropertyChangeEvent finalEvent = evt ; Iterator it ; // Check if the list of listeners is empty if ( listeners == null ) { // There are no listeners so simply return without doing anything return ; } // synchronize on the list of listeners to prevent comodification synchronized ( listeners ) { // Cycle through all listeners and notify them it = listeners . iterator ( ) ; while ( it . hasNext ( ) ) { // Get the next listener from the list final PropertyChangeListener l = ( PropertyChangeListener ) it . next ( ) ; // Notify the listener of the property change event Runnable r = new Runnable ( ) { public void run ( ) { // Fire a property change event l . propertyChange ( finalEvent ) ; } } ; // Run the property change event in the Swing event queue SwingUtilities . invokeLater ( r ) ; } } }


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