AbstractFileTransformationService: stop watchService properly (#965)

* AbstractFileTransformationService: stop watchService properly

Signed-off-by: Laurent Garnier <lg.hc@free.fr>
This commit is contained in:
lolodomo 2019-09-18 19:29:58 +02:00 committed by Christoph Weitkamp
parent 8509a94cfd
commit a11385101b

View File

@ -57,6 +57,7 @@ public abstract class AbstractFileTransformationService<T> implements Transforma
private @Nullable WatchService watchService = null;
protected final Map<String, T> cachedFiles = new ConcurrentHashMap<>();
private final Map<WatchKey, Path> registeredKeys = new ConcurrentHashMap<>();
protected final List<String> watchedDirectories = new ArrayList<String>();
private final Logger logger = LoggerFactory.getLogger(AbstractFileTransformationService.class);
@ -98,6 +99,7 @@ public abstract class AbstractFileTransformationService<T> implements Transforma
protected void deactivate() {
localeProviderTracker.close();
stopWatchService();
}
protected Locale getLocale() {
@ -187,9 +189,10 @@ public abstract class AbstractFileTransformationService<T> implements Transforma
String watchedDirectory = getSourcePath() + subDirectory;
Path transformFilePath = Paths.get(watchedDirectory);
try {
transformFilePath.register(watchService, ENTRY_DELETE, ENTRY_MODIFY);
WatchKey registrationKey = transformFilePath.register(watchService, ENTRY_DELETE, ENTRY_MODIFY);
logger.debug("Watching directory {}", transformFilePath);
watchedDirectories.add(subDirectory);
registeredKeys.put(registrationKey, transformFilePath);
} catch (IOException e) {
logger.warn("Unable to watch transformation directory : {}", watchedDirectory);
cachedFiles.clear();
@ -225,6 +228,23 @@ public abstract class AbstractFileTransformationService<T> implements Transforma
}
}
private synchronized void stopWatchService() {
if (watchService != null) {
for (WatchKey watchKey : registeredKeys.keySet()) {
watchKey.cancel();
}
registeredKeys.clear();
watchedDirectories.clear();
try {
watchService.close();
} catch (IOException e) {
logger.warn("Cannot deactivate transformation directory watcher", e);
}
watchService = null;
cachedFiles.clear();
}
}
/**
* Returns the name of the localized transformation file
* if it actually exists, keeps the original in the other case