use of java.nio.file.WatchService in project tutorials by eugenp.
the class DirectoryWatcherExample method main.
public static void main(String[] args) throws IOException, InterruptedException {
WatchService watchService = FileSystems.getDefault().newWatchService();
Path path = Paths.get(System.getProperty("user.home"));
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
WatchKey key;
while ((key = watchService.take()) != null) {
for (WatchEvent<?> event : key.pollEvents()) {
System.out.println("Event kind:" + event.kind() + ". File affected: " + event.context() + ".");
}
key.reset();
}
watchService.close();
}
use of java.nio.file.WatchService in project webpieces by deanhiller.
the class YourCompanyAbstractDevServer method watchForDangerousJarChangesImpl.
private void watchForDangerousJarChangesImpl(URL res) throws IOException {
// It's always a jar in your code but sometimes we run Dev Server in webpieces where the code is not a jar
// ie(you can delete the if statement if you like)
log.info("res=" + res.getFile() + " res=" + res + " res1" + res.getPath());
// register jar file listener so on changes, we shutdown the server on the developer and make them reboot
String filePath = res.getFile();
String absPath = filePath.substring("file:".length());
String fullJarPath = absPath.split("!")[0];
File f = new File(fullJarPath);
Path directoryPath = f.getParentFile().toPath();
WatchService watcher = FileSystems.getDefault().newWatchService();
directoryPath.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
fileWatchThread.execute(new MyFileWatchRunnable(watcher));
}
use of java.nio.file.WatchService in project streamsx.topology by IBMStreams.
the class DirectoryWatcher method process.
@SuppressWarnings("unchecked")
@Override
protected void process() throws Exception {
Path dir = dirFile.toPath();
WatchService watcher = FileSystems.getDefault().newWatchService();
dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE);
sortAndSubmit(Arrays.asList(dirFile.listFiles(this)));
for (; !Thread.interrupted(); ) {
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException e) {
// shutdown has been requested
return;
}
List<File> newFiles = new ArrayList<>();
boolean needFullScan = false;
for (WatchEvent<?> watchEvent : key.pollEvents()) {
if (ENTRY_CREATE == watchEvent.kind()) {
Path newPath = ((WatchEvent<Path>) watchEvent).context();
File newFile = toFile(newPath);
if (accept(newFile))
newFiles.add(newFile);
} else if (ENTRY_DELETE == watchEvent.kind()) {
Path deletedPath = ((WatchEvent<Path>) watchEvent).context();
File deletedFile = toFile(deletedPath);
seenFiles.remove(deletedFile.getName());
} else if (OVERFLOW == watchEvent.kind()) {
needFullScan = true;
}
}
key.reset();
if (needFullScan) {
Collections.addAll(newFiles, dirFile.listFiles(this));
}
sortAndSubmit(newFiles);
}
}
use of java.nio.file.WatchService in project crate by crate.
the class PutHeadChunkRunnable method run.
@Override
public void run() {
FileInputStream fileInputStream = null;
try {
int bufSize = 4096;
int bytesRead;
int size;
int maxFileGrowthWait = 5;
int fileGrowthWaited = 0;
byte[] buffer = new byte[bufSize];
long remainingBytes = bytesToSend;
File pendingFile;
try {
pendingFile = digestBlob.file();
if (pendingFile == null) {
pendingFile = digestBlob.getContainerFile();
}
fileInputStream = new FileInputStream(pendingFile);
} catch (FileNotFoundException e) {
// this happens if the file has already been moved from tmpDirectory to containerDirectory
pendingFile = digestBlob.getContainerFile();
fileInputStream = new FileInputStream(pendingFile);
}
while (remainingBytes > 0) {
size = (int) Math.min(bufSize, remainingBytes);
bytesRead = fileInputStream.read(buffer, 0, size);
if (bytesRead < size) {
waitUntilFileHasGrown(pendingFile);
fileGrowthWaited++;
if (fileGrowthWaited == maxFileGrowthWait) {
throw new HeadChunkFileTooSmallException(pendingFile.getAbsolutePath());
}
if (bytesRead < 1) {
continue;
}
}
remainingBytes -= bytesRead;
var listener = new PlainActionFuture<TransportResponse>();
transportService.sendRequest(recipientNode, BlobHeadRequestHandler.Actions.PUT_BLOB_HEAD_CHUNK, new PutBlobHeadChunkRequest(transferId, new BytesArray(buffer, 0, bytesRead)), TransportRequestOptions.EMPTY, new ActionListenerResponseHandler<>(listener, in -> TransportResponse.Empty.INSTANCE));
listener.actionGet();
}
} catch (IOException ex) {
LOGGER.error("IOException in PutHeadChunkRunnable", ex);
} finally {
blobTransferTarget.putHeadChunkTransferFinished(transferId);
if (watcher != null) {
try {
watcher.close();
} catch (IOException e) {
LOGGER.error("Error closing WatchService in {}", e, getClass().getSimpleName());
}
}
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
LOGGER.error("Error closing HeadChunk", e);
}
}
}
}
use of java.nio.file.WatchService in project spring-cloud-gcp by spring-cloud.
the class PubSubEmulator method updateConfig.
/**
* Wait until a PubSub emulator configuration file is updated.
* Fail if the file does not update after 1 second.
* @param watchService the watch-service to poll
* @throws InterruptedException which should interrupt the peaceful slumber and bubble up
* to fail the test.
*/
private void updateConfig(WatchService watchService) throws InterruptedException {
int attempts = 10;
while (--attempts >= 0) {
WatchKey key = watchService.poll(100, TimeUnit.MILLISECONDS);
if (key != null) {
Optional<Path> configFilePath = key.pollEvents().stream().map((event) -> (Path) event.context()).filter((path) -> ENV_FILE_NAME.equals(path.toString())).findAny();
if (configFilePath.isPresent()) {
return;
}
}
}
fail("Configuration file update could not be detected");
}
Aggregations