List of usage examples for org.apache.commons.io.monitor FileAlterationMonitor FileAlterationMonitor
public FileAlterationMonitor(long interval)
From source file:org.duracloud.sync.monitor.DirectoryUpdateMonitor.java
/** * Creates a directory update monitor which, when started, will notify * on changes within the given directories. * * @param directories to monitor/*from w ww . j a v a2 s . c o m*/ * @param pollFrequency how often the monitor should look for changes */ public DirectoryUpdateMonitor(List<File> directories, long pollFrequency, boolean syncDeletes) { monitor = new FileAlterationMonitor(pollFrequency); for (File watchDir : directories) { if (watchDir.exists()) { FileAlterationObserver observer; if (watchDir.isDirectory()) { observer = new FileAlterationObserver(watchDir); } else { final File file = watchDir; observer = new FileAlterationObserver(watchDir.getParentFile(), new FileFilter() { @Override public boolean accept(File pathname) { return (file.equals(pathname)); } }); } observer.addListener(new DirectoryListener(syncDeletes)); monitor.addObserver(observer); } else { throw new RuntimeException("Path " + watchDir.getAbsolutePath() + " does not exist"); } } }
From source file:org.jboss.forge.addon.resource.monitor.FileMonitor.java
public FileMonitor() { alterationMonitor = new FileAlterationMonitor(CHECK_INTERVAL); alterationMonitor.setThreadFactory(new ThreadFactory() { @Override/*from w w w . j av a 2 s.c o m*/ public Thread newThread(Runnable r) { Thread resourceMonitorThread = new Thread(r, "Resource File Monitor"); resourceMonitorThread.setDaemon(true); resourceMonitorThread.setContextClassLoader(null); return resourceMonitorThread; } }); }
From source file:org.jboss.pressgang.ccms.contentspec.client.commands.EditCommand.java
protected void editFile(final File file, final Integer id) { // Add a listener for any changes to the file content final FileFilter fileFilter = FileFilterUtils.and(FileFilterUtils.fileFileFilter(), FileFilterUtils.nameFileFilter(file.getName())); final FileAlterationObserver fileObserver = new FileAlterationObserver(file.getParentFile(), fileFilter); final FileAlterationMonitor monitor = new FileAlterationMonitor(FILE_CHECK_INTERVAL); monitor.addObserver(fileObserver);//from www. j a v a2 s. c o m // Create the listener, where on changes (ie saves), the content is saved to PressGang final String[] currentContent = { null }; final FileAlterationListener listener = new FileAlterationListenerAdaptor() { @Override public void onFileChange(final File file) { final String content = FileUtilities.readFileContents(file); final String prevContent = getCurrentContent(); setCurrentContent(content); if (prevContent == null || !content.trim().equals(prevContent.trim())) { // If we are already saving something then wait until it's finished while (saving.get()) { try { Thread.sleep(1000); } catch (InterruptedException e) { // Do nothing } } // Make sure this content is still the latest (ie another save hasn't been done) final String currentContent = getCurrentContent(); if (content.trim().equals(currentContent.trim())) { saveChanges(id, content); } } } protected synchronized void setCurrentContent(final String content) { currentContent[0] = content; } protected synchronized String getCurrentContent() { return currentContent[0]; } }; // Add the listener and start the monitor fileObserver.addListener(listener); try { monitor.start(); } catch (Exception e) { e.printStackTrace(); } // Open the file in the editor JCommander.getConsole().println(ClientUtilities.getMessage("OPENING_FILE_MSG", file.getAbsoluteFile())); try { final Process process = ClientUtilities.runCommand(getCommand(file.getAbsolutePath()), null, null); final long startTime = System.currentTimeMillis(); // Add a stream reader to clear anything that might stop the process from finishing final BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream())); String errorMsg; while ((errorMsg = reader.readLine()) != null) { printError(errorMsg, false); } // Wait for the editor to close try { process.waitFor(); // If the time between the start and the end is small (ie 1 second) then it means the program probably forked a child process // and the parent has ended. So wait instead for the user to type "exit". final long endTime = System.currentTimeMillis(); if (endTime - startTime < MIN_START_INTERVAL) { final Scanner sc = new Scanner(System.in); printWarn(ClientUtilities.getMessage("WARN_EDITOR_FORKED_MSG")); String answer = sc.nextLine(); while (!(answer.equalsIgnoreCase("exit") || answer.equalsIgnoreCase("quit") || answer.equalsIgnoreCase("q"))) { answer = sc.nextLine(); } } // Wait a little to allow for changes to be picked up Thread.sleep(FILE_CHECK_INTERVAL); } catch (InterruptedException e) { } } catch (IOException e) { printError(e.getMessage(), false); } // Clean up try { monitor.stop(); } catch (Exception e) { e.printStackTrace(); } fileObserver.removeListener(listener); // Wait for any saving to finish if (saving.get()) { JCommander.getConsole().println(ClientUtilities.getMessage("WAITING_FOR_SAVE_TO_COMPLETE")); while (saving.get()) { try { Thread.sleep(500); } catch (InterruptedException e) { // Do nothing } } } }
From source file:org.jnap.core.assets.StaticAssetsHandler.java
@PostConstruct public void init() throws Exception { Assert.notNull(servletContext);//from w w w. j a v a 2 s . com this.resourceResolver = new ServletContextResourcePatternResolver(this.servletContext); if (this.shouldInit()) { this.handle(); if (monitor) { fileMonitor = new FileAlterationMonitor(this.monitorInterval); FileAlterationObserver observer = new FileAlterationObserver(path.getFile()); observer.addListener(new FileAlterationListenerAdaptor() { public void onFileCreate(File file) { StaticAssetsHandler.this.handle(); } public void onFileChange(File file) { StaticAssetsHandler.this.handle(); } public void onFileDelete(File file) { StaticAssetsHandler.this.handle(); } }); fileMonitor.addObserver(observer); fileMonitor.start(); logger.info(getClass().getSimpleName() + " started and watching for file changes..."); } logger.info(getClass().getSimpleName() + " executed!"); } }
From source file:org.jwebsocket.plugins.filesystem.FileSystemPlugIn.java
/** * Starts the aliases file-system monitor. * * @param aInterval Changes checks interval value. *//*from w ww . j a va 2s . c om*/ public void startAliasesMonitor(long aInterval) { if (null == mFileSystemMonitor) { mFileSystemMonitor = new FileAlterationMonitor(aInterval); mFileSystemMonitor.setThreadFactory(new FileSystemPlugIn.MonitorThreadFactory()); String lMask = "*"; IOFileFilter lFileFilter = new WildcardFileFilter(lMask); if (mLog.isDebugEnabled()) { mLog.debug("Starting file-system monitor..."); } FileAlterationListener lFileSystemListener = getFileSystemListener(); Set<String> lAliases = mSettings.getAliases().keySet(); for (Object lAlias : lAliases) { if (lAlias.equals(PRIVATE_ALIAS_DIR_KEY) || lAlias.equals(ALIAS_WEB_ROOT_KEY)) { continue; } // registering file-system listener FileAlterationObserver lObserver = new FileAlterationObserver( JWebSocketConfig.expandEnvVarsAndProps(mSettings.getAliasPath(lAlias.toString())), lFileFilter); lObserver.addListener(lFileSystemListener); mFileSystemMonitor.addObserver(lObserver); } } try { // starting file-system monitor... mFileSystemMonitor.start(); } catch (Exception lEx) { mLog.error(Logging.getSimpleExceptionMessage(lEx, "starting directory monitor...")); } }
From source file:org.kie.appformer.backend.server.service.build.BuildAndDeployCallable.java
private FileMonitorHandle startDeployedFileObserver(File deployDir, final File destination) throws Exception { final FileAlterationMonitor monitor = new FileAlterationMonitor(500); final IOFileFilter filter = FileFilterUtils.nameFileFilter(destination.getName() + ".deployed"); final FileAlterationObserver observer = new FileAlterationObserver(deployDir, filter); observer.addListener(new FileAlterationListenerAdaptor() { @Override/*from w w w .j a va 2s.c om*/ public void onFileCreate(final File file) { fireAppReadyEvent(destination, sreq); } @Override public void onFileChange(final File file) { fireAppReadyEvent(destination, sreq); } }); monitor.addObserver(observer); monitor.start(); return new FileMonitorHandle(monitor, destination.getName()); }
From source file:org.onexus.resource.authorization.internal.AuthorizationManager.java
public void load() { try {//from w ww . ja va 2s .c o m this.properties = loadProperties(); } catch (IOException e) { LOGGER.error("Loading authorization config file", e); } // Watch file changes and fire a reload monitor = new FileAlterationMonitor(2000); File file = new File(authorizationFile); FileAlterationObserver observer = new FileAlterationObserver(file.getParent(), FileFilterUtils.nameFileFilter(file.getName())); observer.addListener(new FileAlterationListenerAdaptor() { @Override public void onFileChange(File file) { try { properties = AuthorizationManager.this.loadProperties(); } catch (IOException e) { LOGGER.error("Loading authorization config file", e); } } }); monitor.addObserver(observer); try { monitor.start(); } catch (Exception e) { LOGGER.error("On start authorization config file monitor", e); } }
From source file:org.onexus.resource.manager.internal.ProjectsContainer.java
public ProjectsContainer(IResourceSerializer serializer, PluginLoader pluginLoader) { super();//from w ww . j a v a 2s. c om File onexusFolder = new File(ONEXUS_FOLDER); File projectsFolder = new File(ONEXUS_PROJECTS_FOLDER); propertiesFile = new File(onexusFolder, ONEXUS_PROJECTS_SETTINGS); monitor = new FileAlterationMonitor(2000); if (!onexusFolder.exists()) { onexusFolder.mkdir(); } if (!projectsFolder.exists()) { projectsFolder.mkdir(); } try { if (!propertiesFile.exists()) { propertiesFile.createNewFile(); } this.providerFactory = new ProjectProviderFactory(serializer, pluginLoader, monitor, listeners); this.providers = new ConcurrentHashMap<String, AbstractProjectProvider>(); init(); } catch (IOException e) { throw new RuntimeException("Loading projects file '" + ONEXUS_PROJECTS_SETTINGS + "'", e); } FileAlterationObserver observer = new FileAlterationObserver(onexusFolder, FileFilterUtils.nameFileFilter(ONEXUS_PROJECTS_SETTINGS)); observer.addListener(new FileAlterationListenerAdaptor() { @Override public void onFileChange(File file) { try { ProjectsContainer.this.init(); } catch (IOException e) { LOGGER.error("Loading projects file '" + ONEXUS_PROJECTS_SETTINGS + "'", e); } } }); monitor.addObserver(observer); try { monitor.start(); } catch (Exception e) { LOGGER.error("On start projects file monitor", e); } }
From source file:org.onexus.resource.manger.internal.FileObserver.java
public static void main(String[] args) throws Exception { File file = new File("/home/jdeu/.onexus"); FileAlterationObserver fileObserver = new FileAlterationObserver(file, FileFilterUtils.nameFileFilter("projects.ini")); fileObserver.addListener(new FileAlterationListenerAdaptor() { @Override//from ww w. j av a2s . c om public void onFileChange(File file) { System.out.println("FileChange: " + file.toString()); } }); FileAlterationMonitor monitor = new FileAlterationMonitor(2000); monitor.addObserver(fileObserver); monitor.start(); System.in.read(); monitor.stop(); }
From source file:org.openbase.bco.manager.device.binding.openhab.util.configgen.OpenHABConfigGenerator.java
public OpenHABConfigGenerator() throws InstantiationException, InterruptedException { try {/* www .ja v a 2 s . c om*/ Registries.waitForData(); this.itemConfigGenerator = new OpenHABItemConfigGenerator(); this.recurrenceGenerationFilter = new RecurrenceEventFilter(TIMEOUT) { @Override public void relay() throws Exception { internalGenerate(); } }; FileAlterationObserver fileAlterationObserver = new FileAlterationObserver( JPService.getProperty(JPOpenHABItemConfig.class).getValue().getParent()); fileAlterationObserver.initialize(); fileAlterationObserver.addListener(new FileAlterationListenerAdaptor() { @Override public void onFileDelete(File file) { logger.warn("Detect config file deletion!"); try { generate(); } catch (CouldNotPerformException ex) { ExceptionPrinter.printHistory("Coult not regenerate config file after deletion!", ex, logger); } } }); final FileAlterationMonitor monitor = new FileAlterationMonitor(10000); monitor.addObserver(fileAlterationObserver); monitor.start(); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { shutdown(); try { monitor.stop(); } catch (Exception ex) { ExceptionPrinter.printHistory(ex, logger); } } })); } catch (InterruptedException ex) { throw ex; } catch (Exception ex) { throw new InstantiationException(this, ex); } }