Return to Snippet

Revision: 4965
at January 31, 2008 09:00 by narkisr


Initial Code
public class TailAssertor {

    private static final long sec = 1000L;

    private static final Log log = LogService.getLog(TailAssertor.class.getName());

    private static long sampleInterval = 5000;

    public static void assertNewLinesWithTail(final File logfile, final String expectedLine, int durationInSec) {

        long filePointer = logfile.length();// The file pointer keeps track of where we are in the file
        RandomAccessFile file = null;
        try {
            file = new RandomAccessFile(logfile, "r");
            for (final Date startTime = new Date(); new Date().getTime() - startTime.getTime() < durationInSec * sec;) {
                long fileLength = logfile.length();
                if (fileLength < filePointer) {// file has been cleared
                    file = new RandomAccessFile(logfile, "r");
                    filePointer = 0;
                }
                if (fileLength > filePointer) {
                    file.seek(filePointer);// There is new data to read
                    for (String line = file.readLine(); line != null;) {
                        if (line.contains(expectedLine)) {
                            return;
                        }
                        line = file.readLine();
                    }
                    filePointer = file.getFilePointer();
                }
                Thread.sleep(sampleInterval);// Sleep for the specified interval
            }
        } catch (Exception e) {
            log.error(e);
        } finally {
            closeFile(file);
        }
        throw new AssertionError("the requested line wasn't found within the required time frame!");
    }

    private static void closeFile(RandomAccessFile file) {
        if (file != null) {
            try {
                file.close();
            } catch (IOException e) {
                log.error(e);
            }
        }
    }
}

Initial URL

                                

Initial Description
A simple testing assertion which looks up for a line within a file until a pre defined time frame ends (loosely based upon http://www.informit.com/guides/content.aspx?g=java&seqNum=226).

Initial Title
Simple tail like assertion

Initial Tags
java

Initial Language
Java