Skip to content

Commit

Permalink
Merge pull request #909 from benjaminqc/feature/server_hot_reload
Browse files Browse the repository at this point in the history
add hot reload functionnality for mock server
  • Loading branch information
ptrthomas authored Oct 9, 2019
2 parents 45bc4f1 + 9abcaf4 commit a1e5b99
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package com.intuit.karate.netty;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FileChangedWatcher {

private static final Logger logger = LoggerFactory.getLogger(FileChangedWatcher.class);

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, IOException {

try {
final Path directoryPath = file.toPath().getParent();
final WatchService watchService = FileSystems.getDefault().newWatchService();
directoryPath.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
while (true) {
final WatchKey wk = watchService.take();
for (WatchEvent<?> event : wk.pollEvents()) {
final Path fileChangedPath = (Path) event.context();
if (fileChangedPath.endsWith(file.getName())) {
onModified();
}
}
wk.reset();
}
} catch (Exception exception) {
logger.error("exception when handling change of mock file");
}
}

public void onModified() {
if (server != null) {
server.stop();
server = FeatureServer.start(file, port, ssl, cert, key, null);
}
}
}
7 changes: 6 additions & 1 deletion karate-netty/src/main/java/com/intuit/karate/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import com.intuit.karate.exception.KarateException;
import com.intuit.karate.job.JobExecutor;
import com.intuit.karate.netty.FeatureServer;
import com.intuit.karate.netty.FileChangedWatcher;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
Expand Down Expand Up @@ -199,8 +200,12 @@ public Void call() throws Exception {
key = new File(FeatureServer.DEFAULT_KEY_NAME);
}
FeatureServer server = FeatureServer.start(mock, port, ssl, cert, key, null);

// hot reload
FileChangedWatcher watcher = new FileChangedWatcher(mock, server, port, ssl, cert, key);
watcher.watch();

server.waitSync();
return null;
}

}

0 comments on commit a1e5b99

Please sign in to comment.