Example #1
0
  @Test
  public void testModifyFile() throws Exception {

    log.debug("**** testModifyFile **** ");
    File f = new File(mytempdir + File.separator + "just_edited");
    writeInFile(f, "foo, bar");
    long interval = 700;

    try {
      final Semaphore s = new Semaphore(0);
      fw = new FolderWatcher(new File(mytempdir), interval);
      fw.initialRun();

      IModificationListener failer =
          new IModificationListener() {

            public void fileModified(File f, ModifyActions action) {
              Assert.fail("Got unwanted event: " + f.getAbsolutePath() + ":" + action);
            }
          };
      fw.addListener(failer);
      fw.run();

      awaitNextTimeUnit();

      log.debug("We expect no event.");

      writeInFile(f, "foo, bar");

      Thread.sleep(interval * 3);

      fw.removeListener(failer);
      fw.addListener(
          new IModificationListener() {

            public void fileModified(File f, ModifyActions action) {
              log.debug("got event: " + f.getAbsolutePath() + ":" + action);
              Assert.assertEquals("just_edited", f.getName());
              Assert.assertEquals(ModifyActions.MODIFIED, action);
              s.release();
            }
          });

      awaitNextTimeUnit();

      log.debug("We expect no event.");

      writeInFile(f, "bar, baz");
      Assert.assertTrue("Real content change", s.tryAcquire(interval * 3, TimeUnit.MILLISECONDS));

      fw.cancel();
      f.delete();
      System.gc();
      f.delete();
      Assert.assertFalse(f.exists());

    } catch (Exception e) {
      fw.cancel();
      f.delete();

      throw e;
    }
  }