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);
}
}
}
}