private String waitForPattern ( long timeout , TailLogBufferedReader bufferedReader , Pattern pattern , boolean searchWithinLines , long timeoutInSeconds ) throws IOException { StringBuilder sb = new StringBuilder ( ) ; String result ; label : while ( true ) { while ( bufferedReader . ready ( ) ) { int c = bufferedReader . read ( ) ; if ( c != - 1 ) { if ( c == ' ' || c == ' ' ) { if ( sb . length ( ) > 0 ) { Matcher m = pattern . matcher ( sb ) ; boolean match = searchWithinLines ? m . find ( ) : m . matches ( ) ; if ( match ) { result = sb . toString ( ) ; break label ; } else { sb . setLength ( 0 ) ; } } } else { sb . append ( ( char ) c ) ; } } } //nothing more to read, does the current output match the pattern? if ( sb . length ( ) > 0 && searchWithinLines ) { Matcher m = pattern . matcher ( sb ) ; if ( m . find ( ) ) { result = m . group ( 0 ) ; break label ; } } try { Thread . sleep ( 10 ) ; //avoid a busy loop since we are using nonblocking ready() / read() } catch ( InterruptedException e ) { } checkTimeout ( timeout , timeoutInSeconds ) ; if ( process . isStopped ( ) && ! bufferedReader . ready ( ) ) { ChorusAssert . fail ( process . isExitWithFailureCode ( ) ? "Process stopped with error code " + process . getExitCode ( ) + " while waiting for match" : "Process stopped while waiting for match" ) ; } } return result ; }
read ahead without blocking and attempt to match the pattern