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:it.univaq.disim.connectorOTF.utils.FileMonitor.java

public void monitor(String path) 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  w w  .  j a  va2 s .  c  o m

    FileAlterationObserver observer = new FileAlterationObserver(folder);
    FileAlterationMonitor monitor = new FileAlterationMonitor(pollingInterval);
    FileAlterationListener listener = new SpringAlterationListener();

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

From source file:com.japp.FtpConfigTest.java

@Test
public void fTPClientPushTest() throws Exception {

    FileAlterationObserver observer = new FileAlterationObserver(folder);
    FileAlterationMonitor monitor = new FileAlterationMonitor(pollingInterval);

    observer.addListener(listener);// ww w  .  ja v  a2s. c om
    monitor.addObserver(observer);
    monitor.start();

}

From source file:com.carolinarollergirls.scoreboard.xml.MediaXmlDocumentManager.java

protected void monitorType(File typeDir) {
    String type = typeDir.getName();
    synchronized (typeMonitors) {
        if (typeMonitors.containsKey(type))
            return;
        update(editor.getElement(createXPathElement(), "Type", type));
        FileAlterationObserver faO = new FileAlterationObserver(typeDir, mediaFileFilter);
        faO.addListener(new MediaTypeDirAlterationListener(type));
        FileAlterationMonitor monitor = new FileAlterationMonitor(INTERVAL, faO);
        try {//w  w w  .j  ava2s .  c  om
            monitor.start();
        } catch (Exception e) {
            ScoreBoardManager.printMessage("MediaXmlDocumentManager for " + getMediaName()
                    + " ERROR: Could not start type " + type + " monitor : " + e.getMessage());
        }
        typeMonitors.put(type, monitor);
    }
    initializeType(typeDir);
}

From source file:de.jakusys.jackhammer.cli.upload.command.WatchCommand.java

@Override
public void run() {

    if (!directory.exists()) {
        System.out.println(//w  ww  .  j  a v a2  s.c  o  m
                "Cannot watch directory " + directory.getPath() + ". The specified path could not be found.");
        return;
    }

    Node node;
    try {

        String tmp = rootPath;
        if (rootPath.startsWith("/"))
            tmp = rootPath.substring(1);

        if ("".equals(tmp)) {
            node = session.getRootNode();
        } else {
            node = session.getRootNode().getNode(tmp);
        }
    } catch (RepositoryException e) {
        throw new RuntimeException("Unable to get node", e);
    }

    final DefaultFileHandlerFactory fileHandlerFactory = new DefaultFileHandlerFactory(
            new PathRelativizer(directory));

    final EventBus eventBus = new EventBus();
    eventBus.register(new LoggingEventListener(new Path(rootPath)));
    eventBus.register(new UploadingEventListener(fileHandlerFactory, session, node));

    final FileAlterationObserver observer = new FileAlterationObserver(directory);
    final FileAlterationMonitor monitor = new FileAlterationMonitor(1000);

    PathRelativizer pathRelativizer = new PathRelativizer(directory);

    FileAlterationListener listener = new JackhammerFileAlternationListener(eventBus, pathRelativizer);

    observer.addListener(listener);

    monitor.addObserver(observer);
    try {
        System.out.println(
                "Watching " + directory.getCanonicalPath() + " and uploading changes to " + node.getPath());
        monitor.start();

    } catch (Exception e) {
        throw new RuntimeException("Unable to monitor files", e);
    }
}

From source file:com.lxd.client.monitor.MonitorDir.java

private void fileWatch() {
    //?  /* www  .  ja  v a  2s  . c  om*/
    FileAlterationMonitor monitor = new FileAlterationMonitor(Define.SCANNING); //??
    //  
    FileAlterationObserver observer = new FileAlterationObserver(new File(filePath));

    ///< ??
    observer.addListener(new AdamFileListener());
    ///< ??
    monitor.addObserver(observer);
    try {
        monitor.start();
    } catch (Exception e) {
        e.printStackTrace();
    }

    ///< ??
    MonitorMsg msg = null;
    while ((msg = ClientResource.getSingleton().takeMonitorMsg()) != null) {
        if (msg.getStart() == 0 || msg.getStart() <= System.currentTimeMillis()) {
            ///< ?
            if (msg.getStart() == 0 && msg.getType() == Type.UPDATE) {
                ///< , ??, ?
                msg.setStart(System.currentTimeMillis() + Define.UPDATETIME);
                ClientResource.getSingleton().submitMonitorMsg(msg);
            } else {
                ///< ??
                if (msg.getType() == Type.DELETE || fileCanRead(msg.getFile())) {
                    ///< 
                    if (msg.getType() == Type.ADD
                            && msg.getState().equals(com.lxd.client.monitor.MonitorMsg.State.BEGIN)) {
                        msg.setStart(System.currentTimeMillis() + Define.CREATEFILETIME);
                        msg.setState(com.lxd.client.monitor.MonitorMsg.State.ACCESS);
                        ClientResource.getSingleton().submitMonitorMsg(msg);
                        continue;
                    }
                    msg = ClientResource.getSingleton().reviseMsg(msg);
                    msgPacking(msg);
                } else {

                    log.info("" + msg.getFile() + ", ?");
                    msg.setStart(System.currentTimeMillis() + Define.ERRORTIME);
                    ClientResource.getSingleton().submitMonitorMsg(msg);
                }
            }
        } else {
            ///< ??
            ClientResource.getSingleton().submitMonitorMsg(msg);
            try {
                ///< ??, , ?
                log.info("" + msg.getFile() + ", ?");
                sleep(Define.SLEEPTIME);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

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  .  java2 s.com
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.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  a2  s . 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.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();/* w ww  .  j a v  a 2  s  .co 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:org.apache.syncope.client.enduser.SyncopeEnduserApplication.java

@Override
protected void init() {
    super.init();

    // read enduser.properties
    Properties props = PropertyUtils.read(getClass(), ENDUSER_PROPERTIES, "enduser.directory").getLeft();

    domain = props.getProperty("domain", SyncopeConstants.MASTER_DOMAIN);
    adminUser = props.getProperty("adminUser");
    Args.notNull(adminUser, "<adminUser>");
    anonymousUser = props.getProperty("anonymousUser");
    Args.notNull(anonymousUser, "<anonymousUser>");
    anonymousKey = props.getProperty("anonymousKey");
    Args.notNull(anonymousKey, "<anonymousKey>");

    captchaEnabled = Boolean.parseBoolean(props.getProperty("captcha"));
    Args.notNull(captchaEnabled, "<captcha>");

    xsrfEnabled = Boolean.parseBoolean(props.getProperty("xsrf"));
    Args.notNull(xsrfEnabled, "<xsrf>");

    String scheme = props.getProperty("scheme");
    Args.notNull(scheme, "<scheme>");
    String host = props.getProperty("host");
    Args.notNull(host, "<host>");
    String port = props.getProperty("port");
    Args.notNull(port, "<port>");
    String rootPath = props.getProperty("rootPath");
    Args.notNull(rootPath, "<rootPath>");
    String useGZIPCompression = props.getProperty("useGZIPCompression");
    Args.notNull(useGZIPCompression, "<useGZIPCompression>");
    maxUploadFileSizeMB = props.getProperty("maxUploadFileSizeMB") == null ? null
            : Integer.valueOf(props.getProperty("maxUploadFileSizeMB"));

    clientFactory = new SyncopeClientFactoryBean()
            .setAddress(scheme + "://" + host + ":" + port + "/" + rootPath)
            .setContentType(SyncopeClientFactoryBean.ContentType.JSON)
            .setUseCompression(BooleanUtils.toBoolean(useGZIPCompression));

    // read customForm.json
    try (InputStream is = getClass().getResourceAsStream("/" + CUSTOM_FORM_FILE)) {
        customForm = MAPPER.readValue(is, new TypeReference<HashMap<String, CustomAttributesInfo>>() {
        });/*w  w w .ja v  a 2s.  com*/
        File enduserDir = new File(props.getProperty("enduser.directory"));
        boolean existsEnduserDir = enduserDir.exists() && enduserDir.canRead() && enduserDir.isDirectory();
        if (existsEnduserDir) {
            File customFormFile = FileUtils.getFile(enduserDir, CUSTOM_FORM_FILE);
            if (customFormFile.exists() && customFormFile.canRead() && customFormFile.isFile()) {
                customForm = MAPPER.readValue(FileUtils.openInputStream(customFormFile),
                        new TypeReference<HashMap<String, CustomAttributesInfo>>() {
                        });
            }
        }
        FileAlterationObserver observer = existsEnduserDir
                ? new FileAlterationObserver(enduserDir,
                        pathname -> StringUtils.contains(pathname.getPath(), CUSTOM_FORM_FILE))
                : new FileAlterationObserver(getClass().getResource("/" + CUSTOM_FORM_FILE).getFile(),
                        pathname -> StringUtils.contains(pathname.getPath(), CUSTOM_FORM_FILE));

        FileAlterationMonitor monitor = new FileAlterationMonitor(5000);

        FileAlterationListener listener = new FileAlterationListenerAdaptor() {

            @Override
            public void onFileChange(final File file) {
                try {
                    LOG.trace("{} has changed. Reloading form customization configuration.", CUSTOM_FORM_FILE);
                    customForm = MAPPER.readValue(FileUtils.openInputStream(file),
                            new TypeReference<HashMap<String, CustomAttributesInfo>>() {
                            });
                } catch (IOException e) {
                    e.printStackTrace(System.err);
                }
            }

            @Override
            public void onFileCreate(final File file) {
                try {
                    LOG.trace("{} has been created. Loading form customization configuration.",
                            CUSTOM_FORM_FILE);
                    customForm = MAPPER.readValue(FileUtils.openInputStream(file),
                            new TypeReference<HashMap<String, CustomAttributesInfo>>() {
                            });
                } catch (IOException e) {
                    e.printStackTrace(System.err);
                }
            }

            @Override
            public void onFileDelete(final File file) {
                LOG.trace("{} has been deleted. Resetting form customization configuration.", CUSTOM_FORM_FILE);
                customForm = null;
            }
        };

        observer.addListener(listener);
        monitor.addObserver(observer);
        monitor.start();
    } catch (Exception e) {
        throw new WicketRuntimeException("Could not read " + CUSTOM_FORM_FILE, e);
    }

    // mount resources
    ClassPathScanImplementationLookup classPathScanImplementationLookup = (ClassPathScanImplementationLookup) getServletContext()
            .getAttribute(EnduserInitializer.CLASSPATH_LOOKUP);
    for (final Class<? extends AbstractResource> resource : classPathScanImplementationLookup.getResources()) {
        Resource annotation = resource.getAnnotation(Resource.class);
        if (annotation == null) {
            LOG.debug("No @Resource annotation found on {}, ignoring", resource.getName());
        } else {
            try {
                final AbstractResource instance = resource.newInstance();

                mountResource(annotation.path(), new ResourceReference(annotation.key()) {

                    private static final long serialVersionUID = -128426276529456602L;

                    @Override
                    public IResource getResource() {
                        return instance;
                    }
                });
            } catch (Exception e) {
                LOG.error("Could not instantiate {}", resource.getName(), e);
            }
        }
    }
    //mount captcha resource only if captcha is enabled
    if (captchaEnabled) {
        mountResource("/api/captcha", new ResourceReference("captcha") {

            private static final long serialVersionUID = -128426276529456602L;

            @Override
            public IResource getResource() {
                return new CaptchaResource();
            }
        });
    }
}

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

private void startPolling() throws MojoExecutionException {
    monitors = new ArrayList<FileAlterationMonitor>();

    { // content monitor
        final FileAlterationObserver observer;
        if (sourceDocumentName != null) {
            observer = new FileAlterationObserver(sourceDirectory, new NameFileFilter(sourceDocumentName));
        } else if (sourceDirectory != null) {
            observer = new FileAlterationObserver(sourceDirectory,
                    new RegexFileFilter(ASCIIDOC_REG_EXP_EXTENSION));
        } else {//from www.  java  2 s  .  c om
            monitors = null; // no need to start anything because there is no content
            return;
        }

        final FileAlterationMonitor monitor = new FileAlterationMonitor(interval);
        final FileAlterationListener listener = new FileAlterationListenerAdaptor() {
            @Override
            public void onFileCreate(final File file) {
                getLog().info("File " + file.getAbsolutePath() + " created.");
                needsUpdate.set(true);
            }

            @Override
            public void onFileChange(final File file) {
                getLog().info("File " + file.getAbsolutePath() + " updated.");
                needsUpdate.set(true);
            }

            @Override
            public void onFileDelete(final File file) {
                getLog().info("File " + file.getAbsolutePath() + " deleted.");
                needsUpdate.set(true);
            }
        };

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

        monitors.add(monitor);
    }

    { // resources monitors
        if (synchronizations != null) {
            for (final Synchronization s : synchronizations) {
                final FileAlterationMonitor monitor = new FileAlterationMonitor(interval);
                final FileAlterationListener listener = new FileAlterationListenerAdaptor() {
                    @Override
                    public void onFileCreate(final File file) {
                        getLog().info("File " + file.getAbsolutePath() + " created.");
                        synchronize(s);
                        needsUpdate.set(true);
                    }

                    @Override
                    public void onFileChange(final File file) {
                        getLog().info("File " + file.getAbsolutePath() + " updated.");
                        synchronize(s);
                        needsUpdate.set(true);
                    }

                    @Override
                    public void onFileDelete(final File file) {
                        getLog().info("File " + file.getAbsolutePath() + " deleted.");
                        FileUtils.deleteQuietly(file);
                        needsUpdate.set(true);
                    }
                };

                final File source = s.getSource();

                final FileAlterationObserver observer;
                if (source.isDirectory()) {
                    observer = new FileAlterationObserver(source);
                } else {
                    observer = new FileAlterationObserver(source.getParentFile(),
                            new NameFileFilter(source.getName()));
                }

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

                monitors.add(monitor);
            }
        }
    }

    for (final FileAlterationMonitor monitor : monitors) {
        try {
            monitor.start();
        } catch (final Exception e) {
            throw new MojoExecutionException(e.getMessage(), e);
        }
    }
}