package com.intuit.karate.netty;

import java.io.File;

public class FileChangedWatcher {

  private File file;
  private FeatureServer server;
  private Integer port;
  private boolean ssl;
  private File cert;
  private File key;

  public FileChangedWatcher(File mock, FeatureServer server, Integer port, boolean ssl, File cert, File key) {
    this.file = mock;
    this.server = server;
    this.port = port;
    this.ssl = ssl;
    this.cert = cert;
    this.key = key;
  }

  public void watch() throws InterruptedException {

    long currentModifiedDate = file.lastModified();

    while (true) {

      long newModifiedDate = file.lastModified();

      if (newModifiedDate != currentModifiedDate) {
        currentModifiedDate = newModifiedDate;
        onModified();
      }
      Thread.sleep(500);
    }
  }

  public void onModified() {
    if (server != null) {
      server.stop();
      server = FeatureServer.start(file, port, ssl, cert, key, null);
    }
  }
}

@@ -52,42 +52,424 @@
 le;%0A
-%0Apublic class FileChangedWatcher %7B
+import java.io.IOException;%0Aimport java.nio.file.FileSystems;%0Aimport java.nio.file.Path;%0Aimport java.nio.file.StandardWatchEventKinds;%0Aimport java.nio.file.WatchEvent;%0Aimport java.nio.file.WatchKey;%0Aimport java.nio.file.WatchService;%0Aimport org.slf4j.Logger;%0Aimport org.slf4j.LoggerFactory;%0A%0Apublic class FileChangedWatcher %7B%0A%0A  private static final Logger logger = LoggerFactory.getLogger(FileChangedWatcher.class);
 %0A%0A  
@@ -909,65 +909,263 @@
 tion
- %7B%0A%0A    long currentModifiedDat
+, IOException %7B%0A%0A    try %7B%0A      final Path directoryPath = file.toPath().getParent();%0A      final WatchService watchServic
 e = 
-file.lastModified();%0A%0A
+FileSystems.getDefault().newWatchService();%0A      directoryPath.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);%0A  
     
@@ -1183,159 +1183,236 @@
 ) %7B%0A
-%0A
       
-long newModifiedDate = file.lastModified
+  final WatchKey wk = watchService.take
 ();%0A
-%0A
+  
       
-if (newModifiedDate != currentModifiedDate) %7B%0A        currentModifiedDate = newModifiedDate;%0A
+for (WatchEvent%3C?%3E event : wk.pollEvents()) %7B%0A          final Path fileChangedPath = (Path) event.context();%0A          if (fileChangedPath.endsWith(file.getName())) %7B%0A    
     
@@ -1439,16 +1439,20 @@
     
+    
 %7D%0A      
 Thre
@@ -1451,24 +1451,140 @@
     
-Thread.sleep(500
+  %7D%0A        wk.reset();%0A      %7D%0A    %7D catch (Exception exception) %7B%0A      logger.error(%22exception when handling change of mock file%22
 );%0A 

change file change handler to use Jave Watchservice instead of a sleep loop