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

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

Introduction

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

Prototype

public synchronized void start() throws Exception 

Source Link

Document

Start monitoring.

Usage

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 w w . java  2s . co  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.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  .ja  va 2  s.c  o  m*/
        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.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.  java2  s. 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 {/*from  w  w  w  .  j  a v a2s.c  o 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}//from   w  w w  .j  a v a 2s  .c  o m
 * <p/>
 * Adds a directory to the watcher. If `polling` is not -1, the directory is monitored,
 * otherwise only the initial provisioning is done.
 */
@Override
public boolean add(File directory, long polling) {
    try {
        acquireWriteLockIfNotHeld();
        final int status = isDirectoryAlreadyMonitored(directory);
        if (status <= 1) {
            // Not supported
            if (status == 1) {
                LOGGER.warn("Cannot add {} to the Directory Monitor, a parent directory is already monitored.",
                        directory);
            } else {
                // 0
                LOGGER.warn("Cannot add {} to the Directory Monitor,the directory is already monitored.",
                        directory);
            }
            return false;
        }

        if (polling == -1L && status == 2) {
            // Nothing to do.
            LOGGER.warn("Cannot add {} to the Directory Monitor, the directory is already there as not monitor "
                    + "(as requested).", directory);
            return false;
        }

        if (polling == -1L) {
            // Status = 3 -> add directory.
            // Disable polling.
            monitors.put(directory, null);
            // Are we started or not ?
            if (context != null) {
                openDeployers(directory);
            }
            return true;
        } else {
            if (!directory.isDirectory()) {
                LOGGER.info("Monitored directory {} not existing - creating directory",
                        directory.getAbsolutePath());
                boolean created = directory.mkdirs();
                LOGGER.debug("Monitored direction {} creation ? {}", directory.getAbsolutePath(), created);
            }

            // if status is in {2, 3}, set the file alteration monitor

            // We observe all files as deployers will filter out undesirable files.
            final FileAlterationMonitor monitor = createFileAlterationMonitor(directory, polling);

            // Are we started or not ?
            if (context != null) {
                monitor.start();
                openDeployers(directory);
            }

            return true;
        }
    } catch (Exception e) {
        LOGGER.error("Cannot start the file monitoring on {}", directory, e);
        return false;
    } finally {
        releaseWriteLockIfHeld();
    }
}

From source file:org.pepstock.jem.node.affinity.PolicyAffinityLoader.java

/**
 * Reads <code>jem.affinity.loader.policy</code> properties, passed by
 * configuration file/*from   w  w  w.j a v a2 s  .  c  o  m*/
 * 
 * @see org.pepstock.jem.node.affinity.AffinityLoader#init(java.util.Properties)
 */
@Override
public final void init(Properties properties) {
    String fileName = properties.getProperty(POLICY_FILENAME_KEY);
    if (fileName != null) {
        scriptFile = new File(fileName);
        if (scriptFile.exists()) {
            Main.JOB_LIFECYCLE_LISTENERS_SYSTEM.addListener(JobLifecycleListener.class, this);
            FileAlterationObserver observer = new FileAlterationObserver(scriptFile.getParent());
            FileAlterationMonitor monitor = new FileAlterationMonitor(POLLING_INTERVAL);
            observer.addListener(this);
            monitor.addObserver(observer);
            try {
                monitor.start();
            } catch (Exception e) {
                // debug
                LogAppl.getInstance().debug(e.getMessage(), e);
            }
            String className = FilenameUtils.getExtension(this.getClass().getName());
            Timer timer = new Timer(className, false);
            timer.schedule(new PeriodicallyAffinitiesReloader(), 5 * TimeUtils.MINUTE, 5 * TimeUtils.MINUTE);
        }
    }
}

From source file:org.pepstock.jem.node.DataPathsManager.java

/**
 * Activates the file monitoring on directory of data path rules
 * @param fileDatasetRules file with data path rules
 */// w w  w . j a v a 2  s .c  o  m
private void activateFileMonitor(File fileDatasetRules) {
    FileAlterationObserver observer = new FileAlterationObserver(fileDatasetRules.getParent());
    FileAlterationMonitor monitor = new FileAlterationMonitor(POLLING_INTERVAL);
    observer.addListener(this);
    monitor.addObserver(observer);
    try {
        monitor.start();
    } catch (Exception e) {
        // debug
        LogAppl.getInstance().debug(e.getMessage(), e);
    }

}

From source file:org.pepstock.jem.notify.engine.EmailTemplateReader.java

/**
 * This method initializes the <code>EmailTemplateReader</code> <br>
 * It sets the alias, for the <code>xml</code> email template file root and
 * for the the user name and user email address. <br>
 * It initializes the field <code>xstream</code> using {@link XStream}. <br>
 * Reads and loads the <code>xml</code> email template file <br>
 * It initializes the components to check if someone modifies the email
 * template <code>xml</code> file: <br>
 * <dd>- Initializes the field <code>emailTemplateFileObserver</code> with a
 * new {@link FileAlterationObserver} using the directory in which is placed
 * the email template file (the field <code>emailTemplateFile</code>). <dd>-
 * Add <code>this EmailTemplateReader</code> as a
 * {@link FileAlterationListener} that listens the file changes. <dd>-
 * Creates a <code>FileAlterationMonitor</code> that checks the template
 * <code>xml</code> file changes every {@link #CHECK_INTERVAL} milliseconds.
 * If the automatic file modifications control doesn't start correctly, the
 * field <code>automaticControlStarted</code> is set to <code>false</code>.
 * //from   w  ww .  ja va  2  s  .com
 * @see FileAlterationObserver
 * @see FileAlterationListener
 * @see FileAlterationMonitor
 */
public void initialize() {
    // Initializes a XStream object
    this.xstream = new XStream(new DomDriver());
    // Sets alias for the root xml tag
    xstream.alias(EMAIL_TEMPLATE_ROOT_TAG, EMAIL_TEMPLATE_ROOT_ALIAS);
    // Sets alias for the other tags
    FieldAlias[] aliases = FieldAlias.values();
    for (int i = 0; i < aliases.length; i++) {
        xstream.aliasField(aliases[i].getAliasXmlTag(), JemEmail.class, aliases[i].getFieldName());
    }

    // This field is a FileAlterationObserver. It checks every change of
    // the template xml file that describes the Email. 
    // It's important because if someone modifies the file,
    // EmailTemplateReader reloads it.
    // Initializes the field this.emailTemplateFileObserver with a
    // new new FileAlterationObserver using the email template xml file
    // directory
    FileAlterationObserver emailTemplateFileObserver = new FileAlterationObserver(
            this.emailTemplateFile.getParentFile());
    // Add a listener (this) that listens the file changes
    emailTemplateFileObserver.addListener(this);
    // Creates a FileAlterationMonitor that every CHECK_INTERVAL
    // milliseconds
    // checks the template xml file
    FileAlterationMonitor fileMonitor = new FileAlterationMonitor(CHECK_INTERVAL);
    fileMonitor.addObserver(emailTemplateFileObserver);
    try {
        this.readEmailTemplate();
    } catch (EmailConfigurationException ex) {
        LogAppl.getInstance().emit(NotifyMessage.JEMN008E, ex);
    }
    try {
        fileMonitor.start();
        this.automaticControlStarted = true;
    } catch (Exception ex) {
        LogAppl.getInstance().emit(NotifyMessage.JEMN009E, ex, this.emailTemplateFile);
    }
}

From source file:org.trafodion.rest.script.ScriptManagerWatcher.java

public void run() {
    final long pollingInterval = 5 * 1000;// 5 seconds
    File folder = new File(dir);

    if (!folder.exists()) {
        throw new RuntimeException("Directory not found: " + dir);
    }//from w ww . j a  v  a 2s.  co  m

    try {
        FileAlterationObserver observer = new FileAlterationObserver(folder);
        FileAlterationMonitor monitor = new FileAlterationMonitor(pollingInterval);
        FileAlterationListener listener = new FileAlterationListenerAdaptor() {
            // Is triggered when a file is changed in the monitored folder
            @Override
            public void onFileChange(File file) {
                try {
                    LOG.info("File changed: " + file.getCanonicalPath());
                    ScriptManager.getInstance().removeScript(file.getName());
                } catch (IOException e) {
                    e.printStackTrace(System.err);
                }
            }
        };

        observer.addListener(listener);
        monitor.addObserver(observer);
        monitor.start();
    } catch (Exception e) {
        e.printStackTrace();
        LOG.error(e.getMessage());
    }
}

From source file:testapacheio.SimpleTestMonitor.java

public static void main(String[] args) throws Exception {
    // The monitor will perform polling on the folder every 5 seconds
    final long pollingInterval = 5 * 1000;

    File folder = new File(FOLDER);

    if (!folder.exists()) {
        // Test to see if monitored folder exists
        throw new RuntimeException("Directory not found: " + FOLDER);
    }// ww w.  j ava2  s .c om

    FileAlterationObserver observer = new FileAlterationObserver(folder);
    FileAlterationMonitor monitor = new FileAlterationMonitor(pollingInterval);
    FileAlterationListener listener = new FileAlterationListenerAdaptor() {
        // Is triggered when a file is created in the monitored folder
        @Override
        public void onFileCreate(File file) {
            try {
                // "file" is the reference to the newly created file
                System.out.println("File created: " + file.getCanonicalPath());
            } catch (IOException e) {
                e.printStackTrace(System.err);
            }
        }

        @Override
        public void onFileChange(File file) {
            try {
                // "file" is the reference to the changed file
                System.out.println("File changed: " + file.getCanonicalPath());
            } catch (IOException e) {
                e.printStackTrace(System.err);
            }
        }

        // Is triggered when a file is deleted from the monitored folder
        @Override
        public void onFileDelete(File file) {
            try {
                // "file" is the reference to the removed file
                System.out.println("File removed: " + file.getCanonicalPath());
                // "file" does not exists anymore in the location
                System.out.println("File still exists in location: " + file.exists());
            } catch (IOException e) {
                e.printStackTrace(System.err);
            }
        }
    };

    observer.addListener(listener);
    monitor.addObserver(observer);
    monitor.start();
    for (;;) {
        Thread.sleep(pollingInterval);
        System.out.println("After Start");
    }
}