Example usage for org.apache.commons.io.monitor FileAlterationListenerAdaptor FileAlterationListenerAdaptor

List of usage examples for org.apache.commons.io.monitor FileAlterationListenerAdaptor FileAlterationListenerAdaptor

Introduction

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

Prototype

FileAlterationListenerAdaptor

Source Link

Usage

From source file:com.amazonaws.eclipse.core.accounts.profiles.SdkCredentialsFileContentMonitorTest.java

@Test
public void testFileChangedCallback() throws InterruptedException {

    final CountDownLatch latch = new CountDownLatch(1);

    SdkCredentialsFileContentMonitor monitor = new SdkCredentialsFileContentMonitor(targetFile,
            MONITOR_POLLING_INTERVAL_MILLIS, new FileAlterationListenerAdaptor() {

                @Override/*from  w  ww  .  j  a  va  2 s  . com*/
                public void onFileChange(final File changedFile) {
                    latch.countDown();
                }
            });
    monitor.setDebugMode(true);
    monitor.start();

    touch(targetFile);

    long waitTime = MONITOR_POLLING_INTERVAL_MILLIS * 2;
    Assert.assertTrue("File monitor callback not invoked after waiting for " + waitTime + " ms.",
            latch.await(waitTime, TimeUnit.MILLISECONDS));
}

From source file:com.cloudera.gertrude.file.FileExperimentSpaceLoader.java

private FileAlterationMonitor getMonitor(long pollIntervalMillis) {
    FileAlterationObserver observer = new FileAlterationObserver(dataFile.getParentFile(), new FileFilter() {
        @Override/*from ww w.j a  va2  s . c  o m*/
        public boolean accept(File file) {
            return dataFile.equals(file);
        }
    });

    observer.addListener(new FileAlterationListenerAdaptor() {
        @Override
        public void onFileChange(File file) {
            file.setLastModified(System.currentTimeMillis());
            reload(false);
        }
    });
    FileAlterationMonitor m = new FileAlterationMonitor(pollIntervalMillis);
    m.addObserver(observer);
    return m;
}

From source file:com.amazonaws.eclipse.core.accounts.profiles.SdkCredentialsFileContentMonitor.java

public SdkCredentialsFileContentMonitor(File target, long pollingIntervalInMs) {

    this(target, pollingIntervalInMs, new FileAlterationListenerAdaptor() {

        @Override/*from   w w  w  .j a  v  a 2s .  c  om*/
        public void onFileChange(final File changedFile) {
            Display.getDefault().asyncExec(new Runnable() {
                public void run() {
                    if (AwsToolkitCore.getDefault().getPreferenceStore().getBoolean(
                            PreferenceConstants.P_ALWAYS_RELOAD_WHEN_CREDNENTIAL_PROFILE_FILE_MODIFIED)) {
                        AwsToolkitCore.getDefault().getAccountManager().reloadAccountInfo();
                    } else {
                        showCredentialsReloadConfirmBox(changedFile);
                    }
                }
            });
        }
    });
}

From source file:com.amazonaws.eclipse.core.accounts.profiles.SdkCredentialsFileContentMonitorTest.java

@Test
public void testMonitorInStoppedStatus() throws InterruptedException {

    final CountDownLatch latch = new CountDownLatch(1);

    SdkCredentialsFileContentMonitor monitor = new SdkCredentialsFileContentMonitor(targetFile,
            MONITOR_POLLING_INTERVAL_MILLIS, new FileAlterationListenerAdaptor() {

                @Override//from  w  w w. j a  va2  s  .  co m
                public void onFileChange(final File changedFile) {
                    System.err.println("stopped");
                    latch.countDown();
                }
            });
    monitor.setDebugMode(true);
    monitor.start();
    monitor.stop();

    touch(targetFile);

    long waitTime = MONITOR_POLLING_INTERVAL_MILLIS * 2;
    Assert.assertFalse("Who counted it down to zero???", latch.await(waitTime, TimeUnit.MILLISECONDS));
}

From source file:io.fabric8.vertx.maven.plugin.FileFilterMain.java

private static FileAlterationMonitor fileWatcher(Set<Path> inclDirs) {
    FileAlterationMonitor monitor = new FileAlterationMonitor(1000);

    inclDirs.forEach(path -> {//from w  w  w.  ja v  a2 s.c om
        System.out.println("Adding Observer to " + path.toString());
        FileAlterationObserver observer = new FileAlterationObserver(path.toFile());
        observer.addListener(new FileAlterationListenerAdaptor() {
            @Override
            public void onFileCreate(File file) {
                System.out.println("File Create:" + file.toString());
            }

            @Override
            public void onFileChange(File file) {
                System.out.println("File Change:" + file.toString());
            }

            @Override
            public void onFileDelete(File file) {
                System.out.println("File Delete:" + file.toString());
            }

        });
        monitor.addObserver(observer);
    });

    return monitor;

}

From source file:com.chigix.autosftp.Application.java

public static void watchDir(Path dir) throws Exception {
    // The monitor will perform polling on the folder every 5 seconds
    final long pollingInterval = 5 * 1000;

    File folder = dir.toFile();//from w  w w. jav  a  2  s  .c  o  m

    if (!folder.exists()) {
        // Test to see if monitored folder exists
        throw new FileNotFoundException("Directory not found: " + dir);
    }

    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) {
            Path relativePath = localPath.toAbsolutePath().normalize()
                    .relativize(file.getAbsoluteFile().toPath().normalize());
            System.out.println("File created: " + relativePath);
            final String destPath = remotePath.resolve(relativePath).normalize().toString().replace('\\', '/');
            ArrayList<String> lackDirs = new ArrayList<>();
            String tmpParentPath = destPath;
            while (!tmpParentPath.equals("/") && !tmpParentPath.equals("\\")) {
                tmpParentPath = new File(tmpParentPath).getParentFile().toPath().toString().replace('\\', '/');
                try {
                    sftpChannel.cd(tmpParentPath);
                } catch (SftpException ex) {
                    if (ex.id == SSH_FX_NO_SUCH_FILE) {
                        lackDirs.add(tmpParentPath);
                        continue;
                    }
                    Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
                    return;
                }
                break;
            }
            for (int i = lackDirs.size() - 1; i > -1; i--) {
                try {
                    sftpChannel.mkdir(lackDirs.get(i));
                } catch (SftpException ex) {
                    Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
                    System.err.println(destPath + " Creating Fail.");
                    return;
                }
            }
            InputStream fi = null;
            try {
                fi = new FileInputStream(file);
                sftpChannel.put(fi, destPath, 644);
            } catch (FileNotFoundException ex) {
                System.out.println("File: " + file.getAbsolutePath() + " not exists.");
                return;
            } catch (SftpException ex) {
                Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
                return;
            } finally {
                if (fi != null) {
                    try {
                        fi.close();
                    } catch (IOException ex) {
                    }
                }
            }
            System.out.println("File Uploaded: " + destPath);
        }

        // Is triggered when a file is deleted from the monitored folder
        @Override
        public void onFileDelete(File file) {
            if (file.exists()) {
                return;
            }
            Path relativePath = localPath.toAbsolutePath().normalize()
                    .relativize(file.getAbsoluteFile().toPath().normalize());
            System.out.println("File Deleted: " + relativePath);
            final String destPath = remotePath.resolve(relativePath).normalize().toString().replace('\\', '/');
            try {
                sftpChannel.rm(destPath);
            } catch (SftpException ex) {
                if (ex.id == SSH_FX_NO_SUCH_FILE) {
                } else {
                    Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            System.out.println("Remote Deleted: " + relativePath);
        }

        @Override
        public void onFileChange(File file) {
            this.onFileCreate(file);
        }

    };

    observer.addListener(listener);
    monitor.addObserver(observer);
    monitor.start();
}

From source file:com.bcmcgroup.flare.client.PublisherOutbox11.java

/**
 * Establishes a directory watch service that will publish STIX XML files that are placed into it. This will not account for overwrites.
 *
 * @param dir Directory to watch for STIX content to be published.
 *
 */// w w  w.  j a v  a2s.  c o m
private PublisherOutbox11(final File dir) {

    logger.info("Outbox is awaiting files...");

    // The monitor will perform polling on the folder every 2 seconds
    final long pollingInterval = 2000;

    // Create an observer, monitor, and listener to watch for directory changes
    FileAlterationObserver observer = new FileAlterationObserver(dir);
    FileAlterationMonitor monitor = new FileAlterationMonitor(pollingInterval);
    FileAlterationListener listener = new FileAlterationListenerAdaptor() {

        private String collectionName;

        // Is triggered when a file is created in the monitored folder. Works recursively, and ignores publishFeeds.
        @Override
        public void onFileCreate(File file) {

            List<ContentBlock> contentBlocks = new ArrayList<>();

            // Do nothing if dropping files into the publishFeeds directory
            if (file.getParentFile().getName().equals("publishFeeds")) {
                return;
            }

            try {
                this.collectionName = file.getParentFile().getName();

                String contentBinding = ClientUtil.getContentBinding(file);

                // Form a content block and ensure it passes STIX validation
                ContentBlock contentBlock = new ContentBlock(contentBinding, file, null, null, null);
                contentBlocks.add(contentBlock);

                int responseCode = publish(this.collectionName, null, null, contentBlocks);
                if (responseCode != 0) {
                    logger.info(file.getName() + " " + responseCode);
                } else {
                    logger.warn("Error publishing " + file.getName() + " to collection " + this.collectionName);
                }
            } catch (IOException e) {
                logger.error("IOException when trying to publish " + file.getName());
            } catch (SAXException e) {
                logger.error("SAXException when trying to publish " + file.getName());
            }
        }
    };

    // Start the directory watch service
    observer.addListener(listener);
    monitor.addObserver(observer);
    try {
        monitor.start();
        logger.info("Directory monitoring service has started and is awaiting files...");
        logger.debug("Monitor started...");
    } catch (Exception e) {
        logger.error("General exception thrown when trying to start the directory monitor...");
    }

}

From source file:com.bcmcgroup.flare.client.PublisherOutbox10.java

/**
 * Establishes a directory watch service that will publish STIX XML files that are placed into it. This will not account for overwrites.
 *
 * @param dir Directory to watch for STIX content to be published.
 *
 *//*from   w  ww  .  j a v  a  2 s .c o  m*/
private PublisherOutbox10(final File dir) {

    logger.info("Outbox is awaiting files...");

    // The monitor will perform polling on the folder every 2 seconds
    final long pollingInterval = 2000;

    // Create an observer, monitor, and listener to watch for directory changes
    FileAlterationObserver observer = new FileAlterationObserver(dir);
    FileAlterationMonitor monitor = new FileAlterationMonitor(pollingInterval);
    FileAlterationListener listener = new FileAlterationListenerAdaptor() {

        private String feedName;

        // Is triggered when a file is created in the monitored folder. Works recursively, and ignores publishFeeds.
        @Override
        public void onFileCreate(File file) {

            List<ContentBlock> contentBlocks = new ArrayList<>();

            // Do nothing if dropping files into the publishFeeds directory
            if (file.getParentFile().getName().equals("publishFeeds")) {
                return;
            }

            try {
                this.feedName = file.getParentFile().getName();

                String contentBinding = ClientUtil.getContentBinding(file);

                // Form a content block and ensure it passes STIX validation
                ContentBlock contentBlock = new ContentBlock(contentBinding, file, null, null, null);
                contentBlocks.add(contentBlock);

                int responseCode = publish(this.feedName, null, null, contentBlocks);
                if (responseCode != 0) {
                    logger.info(file.getName() + " " + responseCode);
                } else {
                    logger.warn("Error publishing " + file.getName() + " to collection " + this.feedName + ".");
                }

            } catch (IOException e) {
                logger.error("IOException when trying to publish " + file.getName());
            } catch (SAXException s) {
                logger.error("SAXException when trying to publish " + file.getName());
            }

        }
    };

    // Start the directory watch service
    observer.addListener(listener);
    monitor.addObserver(observer);
    try {
        monitor.start();
        logger.info("Directory monitoring service has started and is awaiting files...");
        logger.debug("Monitor started...");
    } catch (Exception e) {
        logger.error("General exception thrown when trying to start the directory monitor...");
    }

}

From source file:com.jkoolcloud.tnt4j.streams.custom.dirStream.DirStreamingManager.java

private void initialize() {
    executorService = new ThreadPoolExecutor(CORE_TREAD_POOL_SIZE, MAX_TREAD_POOL_SIZE, KEEP_ALIVE_TIME,
            TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(MAX_TREAD_POOL_SIZE * 2),
            new TNTInputStream.StreamsThreadFactory("DirStreamingManagerExecutorThread-")); // NON-NLS

    executorService.setRejectedExecutionHandler(new RejectedExecutionHandler() {
        @Override//from   ww  w . j  a va 2 s .  co m
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            try {
                boolean added = executor.getQueue().offer(r, offerTimeout, TimeUnit.SECONDS);
                if (!added) {
                    LOGGER.log(OpLevel.WARNING,
                            StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME,
                                    "TNTInputStream.tasks.buffer.limit"),
                            offerTimeout);
                    notifyStreamingJobRejected(r);
                }
            } catch (InterruptedException exc) {
                LOGGER.log(OpLevel.WARNING,
                        StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME,
                                "DirStreamingManager.job.offer.interrupted"),
                        ((StreamingJob) r).getJobId(), exc);
            }
        }
    });

    dirWatchdog = new DirWatchdog(dirPath, DirWatchdog.getDefaultFilter(fileWildcardName));
    dirWatchdog.addObserverListener(new FileAlterationListenerAdaptor() {
        @Override
        public void onFileCreate(File file) {
            handleJobConfigCreate(file);
        }

        @Override
        public void onFileChange(File file) {
            handleJobConfigChange(file);
        }

        @Override
        public void onFileDelete(File file) {
            handleJobConfigRemoval(file);
        }
    });

    LOGGER.log(OpLevel.DEBUG, StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME,
            "DirStreamingManager.dir.monitoring.started"), dirPath, fileWildcardName);
}

From source file:gobblin.runtime.local.LocalJobManager.java

/**
 * Start the job configuration file monitor.
 *
 * <p>/*w  ww . j a va2  s .co  m*/
 *     The job configuration file monitor currently only supports monitoring
 *     newly added job configuration files.
 * </p>
 */
private void startJobConfigFileMonitor() throws Exception {
    File jobConfigFileDir = new File(this.properties.getProperty(ConfigurationKeys.JOB_CONFIG_FILE_DIR_KEY));
    FileAlterationObserver observer = new FileAlterationObserver(jobConfigFileDir);
    FileAlterationListener listener = new FileAlterationListenerAdaptor() {
        /**
         * Called when a new job configuration file is dropped in.
         */
        @Override
        public void onFileCreate(File file) {
            int pos = file.getName().lastIndexOf(".");
            String fileExtension = pos >= 0 ? file.getName().substring(pos + 1) : "";
            if (!jobConfigFileExtensions.contains(fileExtension)) {
                // Not a job configuration file, ignore.
                return;
            }

            LOG.info("Detected new job configuration file " + file.getAbsolutePath());
            Properties jobProps = new Properties();
            // First add framework configuration properties
            jobProps.putAll(properties);
            // Then load job configuration properties from the new job configuration file
            loadJobConfig(jobProps, file);

            // Schedule the new job
            try {
                boolean runOnce = Boolean
                        .valueOf(jobProps.getProperty(ConfigurationKeys.JOB_RUN_ONCE_KEY, "false"));
                scheduleJob(jobProps, runOnce ? new RunOnceJobListener() : new EmailNotificationJobListener());
            } catch (Throwable t) {
                LOG.error("Failed to schedule new job loaded from job configuration file "
                        + file.getAbsolutePath(), t);
            }
        }

        /**
         * Called when a job configuration file is changed.
         */
        @Override
        public void onFileChange(File file) {
            int pos = file.getName().lastIndexOf(".");
            String fileExtension = pos >= 0 ? file.getName().substring(pos + 1) : "";
            if (!jobConfigFileExtensions.contains(fileExtension)) {
                // Not a job configuration file, ignore.
                return;
            }

            LOG.info("Detected change to job configuration file " + file.getAbsolutePath());
            Properties jobProps = new Properties();
            // First add framework configuration properties
            jobProps.putAll(properties);
            // Then load the updated job configuration properties
            loadJobConfig(jobProps, file);

            String jobName = jobProps.getProperty(ConfigurationKeys.JOB_NAME_KEY);
            try {
                // First unschedule and delete the old job
                unscheduleJob(jobName);
                boolean runOnce = Boolean
                        .valueOf(jobProps.getProperty(ConfigurationKeys.JOB_RUN_ONCE_KEY, "false"));
                // Reschedule the job with the new job configuration
                scheduleJob(jobProps, runOnce ? new RunOnceJobListener() : new EmailNotificationJobListener());
            } catch (Throwable t) {
                LOG.error("Failed to update existing job " + jobName, t);
            }
        }

        private void loadJobConfig(Properties jobProps, File file) {
            Closer closer = Closer.create();
            try {
                Reader propsReader = closer.register(new InputStreamReader(new FileInputStream(file),
                        ConfigurationKeys.DEFAULT_CHARSET_ENCODING));
                jobProps.load(propsReader);
                jobProps.setProperty(ConfigurationKeys.JOB_CONFIG_FILE_PATH_KEY, file.getAbsolutePath());
            } catch (Exception e) {
                LOG.error("Failed to load job configuration from file " + file.getAbsolutePath(), e);
            } finally {
                try {
                    closer.close();
                } catch (IOException e) {
                    LOG.error("unable to close properties file:" + e, e);
                }
            }
        }
    };

    observer.addListener(listener);
    this.fileAlterationMonitor.addObserver(observer);
    this.fileAlterationMonitor.start();
}