Example usage for org.apache.commons.io.monitor FileAlterationMonitor stop

List of usage examples for org.apache.commons.io.monitor FileAlterationMonitor stop

Introduction

In this page you can find the example usage for org.apache.commons.io.monitor FileAlterationMonitor stop.

Prototype

public synchronized void stop() throws Exception 

Source Link

Document

Stop monitoring.

Usage

From source file:org.asciidoctor.maven.AsciidoctorRefreshMojo.java

private void stopMonitor() throws MojoExecutionException {
    if (monitors != null) {
        for (final FileAlterationMonitor monitor : monitors) {
            try {
                monitor.stop();
            } catch (Exception e) {
                throw new MojoExecutionException(e.getMessage(), e);
            }/*from   w w w . ja va2 s  . c  o m*/
        }
    }
}

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 w  ww. ja  va 2 s.c om*/

    // 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.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  a  v  a  2s . c o  m
        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 {//w  w w  . jav a  2  s .co m
        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);
    }
}

From source file:org.ow2.chameleon.core.activators.DirectoryMonitor.java

/**
 * {@inheritDoc}//  ww w.ja  v  a  2  s. c om
 * <p/>
 * If the directory is watched, stop it.
 */
@Override
public boolean removeAndStopIfNeeded(File directory) {
    try {
        acquireWriteLockIfNotHeld();
        FileAlterationMonitor monitor = monitors.remove(directory);
        if (monitor != null) {
            try {
                monitor.stop();
            } catch (IllegalStateException e) {
                LOGGER.warn("Stopping an already stopped file monitor on {}.", directory.getAbsolutePath());
                LOGGER.debug(e.getMessage(), e);
            } catch (Exception e) {
                LOGGER.error("Something bad happened while trying to stop the file monitor on {}", directory,
                        e);
            }
            return true;
        }
        return false;
    } finally {
        releaseWriteLockIfHeld();
    }
}