use of org.apache.commons.io.monitor.FileAlterationListenerAdaptor in project cytoscape-impl by cytoscape.
the class AppManager method setupAlterationMonitor.
private void setupAlterationMonitor() {
// Set up the FileAlterationMonitor to install/uninstall apps when apps are moved in/out of the
// installed/uninstalled app directories
fileAlterationMonitor = new FileAlterationMonitor(2000L);
File installedAppsPath = new File(getInstalledAppsPath());
FileAlterationObserver installAlterationObserver = new FileAlterationObserver(installedAppsPath, new AppFileFilter(installedAppsPath), IOCase.SYSTEM);
final AppManager appManager = this;
// Listen for events on the "installed apps" folder
installAlterationObserver.addListener(new FileAlterationListenerAdaptor() {
@Override
public void onFileCreate(File file) {
App parsedApp = null;
try {
parsedApp = appParser.parseApp(file);
} catch (AppParsingException e) {
userLogger.error("Could not parse app from newly discovered file '" + file.getAbsolutePath() + "' :", e);
return;
}
boolean startApp = parsedApp.isCompatible(version);
if (!startApp) {
userLogger.error("Newly discovered app '" + parsedApp.getAppName() + "' is not compatible with the running version of Cytoscape (" + version + ").");
}
App registeredApp = null;
for (App app : apps) {
if (parsedApp.heuristicEquals(app)) {
registeredApp = app;
userLogger.warn("Newly discovered app '" + parsedApp.getAppName() + "' in file '" + parsedApp.getAppFile().getAbsolutePath() + "' is equal to an already registered app '" + registeredApp.getAppName() + "' in file '" + (registeredApp.getAppFile() == null ? "N/A" : registeredApp.getAppFile().getAbsolutePath()) + "'");
// Delete old file if it was still there
File oldFile = registeredApp.getAppFile();
if (oldFile != null && oldFile.exists() && !registeredApp.getAppFile().equals(parsedApp.getAppFile())) {
userLogger.info("Trying to delete the installed copy of app '" + registeredApp.getAppName() + "' in file '" + registeredApp.getAppFile().getAbsolutePath() + "' because another copy exists.");
FileUtils.deleteQuietly(oldFile);
}
// Update file reference to reflect file having been moved
registeredApp.setAppFile(file);
registeredApp.setStatus(AppStatus.INACTIVE);
} else if (parsedApp.isCompatible(version) && parsedApp.getAppName().equals(app.getAppName())) {
try {
if (!app.isDetached() && app.isCompatible(version)) {
if (compareApps(parsedApp, app) > 0) {
startApp = false;
userLogger.warn("Not starting newly discovered app '" + parsedApp.getAppName() + "' because a newer version is already loaded.");
} else {
app.unload(AppManager.this);
app.setStatus(AppStatus.INACTIVE);
userLogger.warn("Unloading app '" + app.getAppName() + "' because the newly discovered app '" + parsedApp.getAppName() + "' is a newer version.");
}
}
} catch (AppUnloadingException e) {
// TODO Auto-generated catch block
userLogger.warn("Failed to unload app " + app.getAppName(), e);
}
}
}
App app = null;
if (registeredApp == null) {
app = parsedApp;
apps.add(app);
} else {
app = registeredApp;
}
try {
if (startApp) {
app.load(appManager);
app.start(appManager);
app.setStatus(AppStatus.INSTALLED);
userLogger.info("Started newly discovered app '" + app.getAppName() + "'.");
}
} catch (AppLoadingException e) {
app.setStatus(AppStatus.FAILED_TO_LOAD);
userLogger.error("Failed to load app " + app.getAppName(), e);
} catch (AppStartupException e) {
app.setStatus(AppStatus.FAILED_TO_START);
userLogger.error("Failed to start app " + app.getAppName(), e);
}
fireAppsChangedEvent();
}
@Override
public void onFileChange(File file) {
// Can treat file replacements/changes as old file deleted, new file added
this.onFileDelete(file);
this.onFileCreate(file);
fireAppsChangedEvent();
}
@Override
public void onFileDelete(File file) {
// System.out.println(file + " on delete");
DebugHelper.print(this + " installObserverDelete", file.getAbsolutePath() + " deleted.");
App registeredApp = null;
for (App app : apps) {
if (file.equals(app.getAppFile())) {
app.setAppFile(null);
registeredApp = app;
break;
}
}
if (registeredApp == null)
return;
try {
registeredApp.unload(appManager);
registeredApp.setStatus(AppStatus.FILE_MOVED);
userLogger.info("Unloaded app '" + registeredApp.getAppName() + "', because its file is no longer available.");
} catch (AppUnloadingException e) {
userLogger.warn("Failed to unload app " + registeredApp.getAppName(), e);
}
// Do this so that we don't reload an old app when responding to change events
if (file.exists()) {
App parsedApp = null;
try {
parsedApp = appParser.parseApp(file);
} catch (AppParsingException e) {
return;
}
if (parsedApp.isCompatible(version) && registeredApp.getAppName().equalsIgnoreCase(parsedApp.getAppName()))
return;
}
App appToStart = null;
for (App app : apps) {
if (!app.isDetached() && app.isCompatible(version) && app.getAppName().equalsIgnoreCase(registeredApp.getAppName())) {
if (appToStart == null || compareApps(appToStart, app) > 0)
appToStart = app;
}
}
if (appToStart != null) {
try {
appToStart.load(appManager);
appToStart.start(appManager);
appToStart.setStatus(AppStatus.INSTALLED);
userLogger.info("Started app " + appToStart.getAppName() + " because a different version has been unloaded.");
} catch (AppLoadingException e) {
appToStart.setStatus(AppStatus.FAILED_TO_LOAD);
userLogger.error("Failed to load app " + appToStart.getAppName(), e);
} catch (AppStartupException e) {
appToStart.setStatus(AppStatus.FAILED_TO_START);
userLogger.error("Failed to start app " + appToStart.getAppName(), e);
}
}
fireAppsChangedEvent();
}
});
FileAlterationObserver disableAlterationObserver = new FileAlterationObserver(getDisabledAppsPath(), new AppFileFilter(new File(getDisabledAppsPath())), IOCase.SYSTEM);
// Listen for events on the "disabled apps" folder
disableAlterationObserver.addListener(new FileAlterationListenerAdaptor() {
@Override
public void onFileCreate(File file) {
App parsedApp = null;
try {
parsedApp = appParser.parseApp(file);
} catch (AppParsingException e) {
return;
}
DebugHelper.print(this + " disableObserver Create", parsedApp.getAppName() + " parsed");
App registeredApp = null;
for (App app : apps) {
if (parsedApp.heuristicEquals(app)) {
registeredApp = app;
// Delete old file if it was still there
// TODO: Possible rename from filename-2 to filename?
File oldFile = registeredApp.getAppFile();
if (oldFile != null && oldFile.exists() && !registeredApp.getAppFile().equals(parsedApp.getAppFile())) {
DebugHelper.print(this + " disableObserverCreate", registeredApp.getAppName() + " moved from " + registeredApp.getAppFile().getAbsolutePath() + " to " + parsedApp.getAppFile().getAbsolutePath() + ". deleting: " + oldFile);
FileUtils.deleteQuietly(oldFile);
}
// Update file reference to reflect file having been moved
registeredApp.setAppFile(file);
}
}
App app = null;
if (registeredApp == null) {
app = parsedApp;
apps.add(app);
} else {
app = registeredApp;
}
app.setStatus(AppStatus.DISABLED);
fireAppsChangedEvent();
// System.out.println(file + " on create");
}
@Override
public void onFileChange(File file) {
// Can treat file replacements/changes as old file deleted, new file added
this.onFileDelete(file);
this.onFileCreate(file);
fireAppsChangedEvent();
}
@Override
public void onFileDelete(File file) {
// System.out.println(file + " on delete");
DebugHelper.print(this + " disableObserverDelete", file.getAbsolutePath() + " deleted.");
for (App app : apps) {
// System.out.println("checking " + app.getAppFile().getAbsolutePath());
if (file.equals(app.getAppFile())) {
app.setAppFile(null);
app.setStatus(AppStatus.FILE_MOVED);
break;
}
}
fireAppsChangedEvent();
}
});
FileAlterationObserver uninstallAlterationObserver = new FileAlterationObserver(getUninstalledAppsPath(), new AppFileFilter(new File(getUninstalledAppsPath())), IOCase.SYSTEM);
// Listen for events on the "uninstalled apps" folder
uninstallAlterationObserver.addListener(new FileAlterationListenerAdaptor() {
@Override
public void onFileCreate(File file) {
App parsedApp = null;
try {
parsedApp = appParser.parseApp(file);
} catch (AppParsingException e) {
return;
}
DebugHelper.print(this + " uninstallObserverCreate", parsedApp.getAppName() + " parsed");
App registeredApp = null;
for (App app : apps) {
if (parsedApp.heuristicEquals(app)) {
registeredApp = app;
// Delete old file if it was still there
// TODO: Possible rename from filename-2 to filename?
File oldFile = registeredApp.getAppFile();
if (oldFile != null && oldFile.exists() && !registeredApp.getAppFile().equals(parsedApp.getAppFile())) {
DebugHelper.print(this + " uninstallObserverCreate", registeredApp.getAppName() + " moved from " + registeredApp.getAppFile().getAbsolutePath() + " to " + parsedApp.getAppFile().getAbsolutePath() + ". deleting: " + oldFile);
FileUtils.deleteQuietly(oldFile);
}
// Update file reference to reflect file having been moved
registeredApp.setAppFile(file);
}
}
App app = null;
if (registeredApp == null) {
app = parsedApp;
apps.add(app);
} else {
app = registeredApp;
}
app.setStatus(AppStatus.UNINSTALLED);
fireAppsChangedEvent();
// System.out.println(file + " on create");
}
@Override
public void onFileChange(File file) {
// Can treat file replacements/changes as old file deleted, new file added
this.onFileDelete(file);
this.onFileCreate(file);
fireAppsChangedEvent();
}
@Override
public void onFileDelete(File file) {
// System.out.println(file + " on delete");
DebugHelper.print(this + " uninstallObserverDelete", file.getAbsolutePath() + " deleted.");
for (App app : apps) {
// System.out.println("checking " + app.getAppFile().getAbsolutePath());
if (file.equals(app.getAppFile())) {
app.setAppFile(null);
app.setStatus(AppStatus.FILE_MOVED);
break;
}
}
fireAppsChangedEvent();
}
});
try {
installAlterationObserver.initialize();
fileAlterationMonitor.addObserver(installAlterationObserver);
disableAlterationObserver.initialize();
fileAlterationMonitor.addObserver(disableAlterationObserver);
uninstallAlterationObserver.initialize();
fileAlterationMonitor.addObserver(uninstallAlterationObserver);
fileAlterationMonitor.start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
use of org.apache.commons.io.monitor.FileAlterationListenerAdaptor in project tutorials by eugenp.
the class FileMonitor method startFileMonitor.
/**
* @param folder
* @throws Exception
*/
public static void startFileMonitor(File folder) throws Exception {
FileAlterationObserver observer = new FileAlterationObserver(folder);
FileAlterationMonitor monitor = new FileAlterationMonitor(5000);
FileAlterationListener fal = new FileAlterationListenerAdaptor() {
@Override
public void onFileCreate(File file) {
// on create action
}
@Override
public void onFileDelete(File file) {
// on delete action
}
};
observer.addListener(fal);
monitor.addObserver(observer);
monitor.start();
}
use of org.apache.commons.io.monitor.FileAlterationListenerAdaptor in project JSpiderCluster by xiyuan-fengyu.
the class FileWatchers method add.
/**
* @param listener
* @param path 绝对地址
* @param ignoreChildren 要忽略的文件夹或者文件,绝对路径
*/
public static void add(final FileListener listener, final String path, final String[] ignoreChildren) {
if (listener == null || path == null) {
return;
}
Thread thread = new Thread() {
@Override
public void run() {
try {
File file = new File(path);
if (!file.exists() && !file.mkdirs()) {
return;
}
final HashSet<String> ignores = new HashSet<>();
if (ignoreChildren != null) {
for (String child : ignoreChildren) {
ignores.add(child);
}
}
FileAlterationObserver observer = new FileAlterationObserver(file, new FileFilter() {
@Override
public boolean accept(File pathname) {
return !ignores.contains(pathname.getAbsolutePath());
}
});
observer.addListener(new FileAlterationListenerAdaptor() {
@Override
public void onDirectoryCreate(File directory) {
listener.onChange(directory);
}
@Override
public void onDirectoryChange(File directory) {
listener.onChange(directory);
}
@Override
public void onDirectoryDelete(File directory) {
listener.onChange(directory);
}
@Override
public void onFileCreate(File file) {
listener.onChange(file);
}
@Override
public void onFileChange(File file) {
listener.onChange(file);
}
@Override
public void onFileDelete(File file) {
listener.onChange(file);
}
});
FileAlterationMonitor monitor = new FileAlterationMonitor(3000, observer);
monitor.start();
} catch (Exception e) {
e.printStackTrace();
}
}
};
thread.setDaemon(true);
thread.start();
}
use of org.apache.commons.io.monitor.FileAlterationListenerAdaptor in project syncope by apache.
the class SyncopeEnduserApplication method init.
@Override
protected void init() {
super.init();
// read enduser.properties
Properties props = PropertyUtils.read(getClass(), ENDUSER_PROPERTIES, "enduser.directory").getLeft();
domain = props.getProperty("domain", SyncopeConstants.MASTER_DOMAIN);
adminUser = props.getProperty("adminUser");
Args.notNull(adminUser, "<adminUser>");
anonymousUser = props.getProperty("anonymousUser");
Args.notNull(anonymousUser, "<anonymousUser>");
anonymousKey = props.getProperty("anonymousKey");
Args.notNull(anonymousKey, "<anonymousKey>");
captchaEnabled = Boolean.parseBoolean(props.getProperty("captcha"));
Args.notNull(captchaEnabled, "<captcha>");
xsrfEnabled = Boolean.parseBoolean(props.getProperty("xsrf"));
Args.notNull(xsrfEnabled, "<xsrf>");
String scheme = props.getProperty("scheme");
Args.notNull(scheme, "<scheme>");
String host = props.getProperty("host");
Args.notNull(host, "<host>");
String port = props.getProperty("port");
Args.notNull(port, "<port>");
String rootPath = props.getProperty("rootPath");
Args.notNull(rootPath, "<rootPath>");
String useGZIPCompression = props.getProperty("useGZIPCompression");
Args.notNull(useGZIPCompression, "<useGZIPCompression>");
maxUploadFileSizeMB = props.getProperty("maxUploadFileSizeMB") == null ? null : Integer.valueOf(props.getProperty("maxUploadFileSizeMB"));
clientFactory = new SyncopeClientFactoryBean().setAddress(scheme + "://" + host + ":" + port + "/" + rootPath).setContentType(SyncopeClientFactoryBean.ContentType.JSON).setUseCompression(BooleanUtils.toBoolean(useGZIPCompression));
// read customForm.json
try (InputStream is = getClass().getResourceAsStream("/" + CUSTOM_FORM_FILE)) {
customForm = MAPPER.readValue(is, new TypeReference<HashMap<String, CustomAttributesInfo>>() {
});
File enduserDir = new File(props.getProperty("enduser.directory"));
boolean existsEnduserDir = enduserDir.exists() && enduserDir.canRead() && enduserDir.isDirectory();
if (existsEnduserDir) {
File customFormFile = FileUtils.getFile(enduserDir, CUSTOM_FORM_FILE);
if (customFormFile.exists() && customFormFile.canRead() && customFormFile.isFile()) {
customForm = MAPPER.readValue(FileUtils.openInputStream(customFormFile), new TypeReference<HashMap<String, CustomAttributesInfo>>() {
});
}
}
FileAlterationObserver observer = existsEnduserDir ? new FileAlterationObserver(enduserDir, pathname -> StringUtils.contains(pathname.getPath(), CUSTOM_FORM_FILE)) : new FileAlterationObserver(getClass().getResource("/" + CUSTOM_FORM_FILE).getFile(), pathname -> StringUtils.contains(pathname.getPath(), CUSTOM_FORM_FILE));
FileAlterationMonitor monitor = new FileAlterationMonitor(5000);
FileAlterationListener listener = new FileAlterationListenerAdaptor() {
@Override
public void onFileChange(final File file) {
try {
LOG.trace("{} has changed. Reloading form customization configuration.", CUSTOM_FORM_FILE);
customForm = MAPPER.readValue(FileUtils.openInputStream(file), new TypeReference<HashMap<String, CustomAttributesInfo>>() {
});
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
@Override
public void onFileCreate(final File file) {
try {
LOG.trace("{} has been created. Loading form customization configuration.", CUSTOM_FORM_FILE);
customForm = MAPPER.readValue(FileUtils.openInputStream(file), new TypeReference<HashMap<String, CustomAttributesInfo>>() {
});
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
@Override
public void onFileDelete(final File file) {
LOG.trace("{} has been deleted. Resetting form customization configuration.", CUSTOM_FORM_FILE);
customForm = null;
}
};
observer.addListener(listener);
monitor.addObserver(observer);
monitor.start();
} catch (Exception e) {
throw new WicketRuntimeException("Could not read " + CUSTOM_FORM_FILE, e);
}
// mount resources
ClassPathScanImplementationLookup classPathScanImplementationLookup = (ClassPathScanImplementationLookup) getServletContext().getAttribute(EnduserInitializer.CLASSPATH_LOOKUP);
for (final Class<? extends AbstractResource> resource : classPathScanImplementationLookup.getResources()) {
Resource annotation = resource.getAnnotation(Resource.class);
if (annotation == null) {
LOG.debug("No @Resource annotation found on {}, ignoring", resource.getName());
} else {
try {
final AbstractResource instance = resource.newInstance();
mountResource(annotation.path(), new ResourceReference(annotation.key()) {
private static final long serialVersionUID = -128426276529456602L;
@Override
public IResource getResource() {
return instance;
}
});
} catch (Exception e) {
LOG.error("Could not instantiate {}", resource.getName(), e);
}
}
}
// mount captcha resource only if captcha is enabled
if (captchaEnabled) {
mountResource("/api/captcha", new ResourceReference("captcha") {
private static final long serialVersionUID = -128426276529456602L;
@Override
public IResource getResource() {
return new CaptchaResource();
}
});
}
}
use of org.apache.commons.io.monitor.FileAlterationListenerAdaptor in project tutorials by eugenp.
the class DirectoryMonitoringExample method main.
public static void main(String[] args) throws Exception {
FileAlterationObserver observer = new FileAlterationObserver(System.getProperty("user.home"));
FileAlterationMonitor monitor = new FileAlterationMonitor(POLL_INTERVAL);
FileAlterationListener listener = new FileAlterationListenerAdaptor() {
@Override
public void onFileCreate(File file) {
LOG.debug("File: " + file.getName() + " created");
}
@Override
public void onFileDelete(File file) {
LOG.debug("File: " + file.getName() + " deleted");
}
@Override
public void onFileChange(File file) {
LOG.debug("File: " + file.getName() + " changed");
}
};
observer.addListener(listener);
monitor.addObserver(observer);
monitor.start();
}
Aggregations