We Recommend

Java How to Program Java How to Program
Takes a new tools-based approach to Web application development that uses Netbeans 5.5 and Java Studio Creator 2 to create and consume Web Services. Features new AJAX-enabled, Web applications built with JavaServer Faces (JSF), Java Studio Creator 2 and the Java Blueprints AJAX Components. Includes new topics throughout, such as JDBC 4, SwingWorker for multithreaded GUIs, GroupLayout, Java Desktop Integration Components (JDIC), and much more.


Posted By

narkisr on 01/31/08


Tagged

java tail Assertion


Versions (?)


Simple tail like assertion


Published in: Java 


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).


  1. public class TailAssertor {
  2.  
  3. private static final long sec = 1000L;
  4.  
  5. private static final Log log = LogService.getLog(TailAssertor.class.getName());
  6.  
  7. private static long sampleInterval = 5000;
  8.  
  9. public static void assertNewLinesWithTail(final File logfile, final String expectedLine, int durationInSec) {
  10.  
  11. long filePointer = logfile.length();// The file pointer keeps track of where we are in the file
  12. RandomAccessFile file = null;
  13. try {
  14. file = new RandomAccessFile(logfile, "r");
  15. for (final Date startTime = new Date(); new Date().getTime() - startTime.getTime() < durationInSec * sec;) {
  16. long fileLength = logfile.length();
  17. if (fileLength < filePointer) {// file has been cleared
  18. file = new RandomAccessFile(logfile, "r");
  19. filePointer = 0;
  20. }
  21. if (fileLength > filePointer) {
  22. file.seek(filePointer);// There is new data to read
  23. for (String line = file.readLine(); line != null;) {
  24. if (line.contains(expectedLine)) {
  25. return;
  26. }
  27. line = file.readLine();
  28. }
  29. filePointer = file.getFilePointer();
  30. }
  31. Thread.sleep(sampleInterval);// Sleep for the specified interval
  32. }
  33. } catch (Exception e) {
  34. log.error(e);
  35. } finally {
  36. closeFile(file);
  37. }
  38. throw new AssertionError("the requested line wasn't found within the required time frame!");
  39. }
  40.  
  41. private static void closeFile(RandomAccessFile file) {
  42. if (file != null) {
  43. try {
  44. file.close();
  45. } catch (IOException e) {
  46. log.error(e);
  47. }
  48. }
  49. }
  50. }

Report this snippet 

You need to login to post a comment.