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

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

Introduction

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

Prototype

public void addObserver(final FileAlterationObserver observer) 

Source Link

Document

Add a file system observer to this monitor.

Usage

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   www. j  a  v a  2 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 {// www .j  a  va 2s .  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.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  a2s  . 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
 *//*from   w w  w. ja va 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 w  w  . j  ava  2s . co m
 * @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 ww w .ja v  a 2  s  .  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);
    }//w  ww. jav  a2s.c  o  m

    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");
    }
}

From source file:tests.XmlTest.java

public void fileMonitorTest() throws Exception {

    Configuration config = new Configuration();
    SqlQueryFactoryImpl impl = new SqlQueryFactoryImpl(config);
    File directory = new File("src/test/resources");

    for (File f : FileUtils.listFiles(directory, FileFilterUtils.suffixFileFilter(config.getSuffix()),
            FileFilterUtils.trueFileFilter())) {
        log.debug("file={}", f.toURI().toString());
    }//from   w ww  .  j  a va 2s  . c  o m

    impl.setResourceLocations(new ArrayList<String>());
    impl.getResourceLocations().add("common-sqlset.xml");

    FileAlterationMonitor monitor = new FileAlterationMonitor(1000L);
    FileAlterationObserver observer = new FileAlterationObserver(directory,
            FileFilterUtils.suffixFileFilter(config.getSuffix()));
    observer.addListener(new FileAlterationListener() {
        public void onStart(FileAlterationObserver observer) {

        }

        public void onDirectoryCreate(File directory) {
            log.debug("onDirectoryCreate:");
        }

        public void onDirectoryChange(File directory) {
            log.debug("onDirectoryChange:");
        }

        public void onDirectoryDelete(File directory) {
            log.debug("onDirectoryDelete:");
        }

        public void onFileCreate(File file) {
            log.debug("onFileCreate:");
        }

        public void onFileChange(File file) {
            log.debug("onFileChange:");
        }

        public void onFileDelete(File file) {
            log.debug("onFileDelete:");
        }

        public void onStop(FileAlterationObserver observer) {

        }
    });
    monitor.addObserver(observer);
    monitor.start();
    log.debug("Current working directory : {} ", directory.getAbsolutePath());
}