Example usage for org.apache.commons.vfs.impl DefaultFileMonitor DefaultFileMonitor

List of usage examples for org.apache.commons.vfs.impl DefaultFileMonitor DefaultFileMonitor

Introduction

In this page you can find the example usage for org.apache.commons.vfs.impl DefaultFileMonitor DefaultFileMonitor.

Prototype

public DefaultFileMonitor(final FileListener listener) 

Source Link

Usage

From source file:net.nicoulaj.benchmark.mockwebapp.MockWebAppServlet.java

/**
 * Initialize the servlet./*from   w  w  w. j  a  v a 2  s  . c o m*/
 * <p/>
 * Loads the {@link #mockWebAppConfig} by looking up the {@link #MOCK_WEB_APP_CONF_PROPERTY} as a system property or init parameter,
 * and sets up a listener on the file changes.
 *
 * @param config the {@link ServletConfig}, optionally with a {@link #MOCK_WEB_APP_CONF_PROPERTY} parameter.
 * @throws ServletException if the {@link #MOCK_WEB_APP_CONF_PROPERTY} was neither defined as a system property nor an init parameter.
 */
@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);

    // Locate the config file parameter.
    String configFilePath = System.getProperty(MOCK_WEB_APP_CONF_PROPERTY);
    if (configFilePath == null)
        configFilePath = config.getInitParameter(MOCK_WEB_APP_CONF_PROPERTY);
    if (configFilePath == null)
        throw new ServletException("No mock web app config file defined. Please define one using the '"
                + MOCK_WEB_APP_CONF_PROPERTY + "' system property or servlet init parameter.");

    // Setup the config file changes listener.
    try {
        fileMonitor = new DefaultFileMonitor(new ConfigFileListener());
        fileMonitor.addFile(VFS.getManager().resolveFile(new File("."), configFilePath));
        fileMonitor.start();
    } catch (Exception e) {
        getServletContext().log(
                "Failed setting up config file changes listener, config file changes will not be taken into account",
                e);
    }

    // Load the config from the file.
    final File configFile = new File(configFilePath);
    try {
        mockWebAppConfig = MockWebAppConfig.Parser.parseConfig(configFile);
        getServletContext().log("Loaded config file " + configFilePath);
    } catch (Exception e) {
        getServletContext().log("Failed loading config, please replace it with a valid one", e);
    }
}

From source file:com.sonatype.nexus.plugin.groovyconsole.DefaultScriptStorage.java

public void initialize() throws InitializationException {
    scripts = new LinkedHashMap<String, String>();

    FileObject listendir;/*from  w w w. j  a va2 s.  com*/
    try {
        FileSystemManager fsManager = VFS.getManager();
        scriptDir = applicationConfiguration.getWorkingDirectory("scripts");
        if (!scriptDir.exists()) {
            scriptDir.mkdirs();

            try {
                new File(scriptDir, "place your .groovy files here.txt").createNewFile();
            } catch (IOException e) {
                throw new InitializationException(e.getMessage(), e);
            }
        }

        listendir = fsManager.resolveFile(scriptDir.getAbsolutePath());
    } catch (FileSystemException e) {
        throw new InitializationException(e.getMessage(), e);
    }

    FileSelector selector = new FileSelector() {
        public boolean traverseDescendents(FileSelectInfo arg0) throws Exception {
            return true;
        }

        public boolean includeFile(FileSelectInfo arg0) throws Exception {
            return isScriptFile(arg0.getFile());
        }
    };

    try {
        FileObject[] availableScripts = listendir.findFiles(selector);
        for (FileObject fileObject : availableScripts) {
            updateScript(fileObject);
        }
    } catch (FileSystemException e) {
        getLogger().warn("Unable to perform initial directory scan.", e);
    }

    DefaultFileMonitor fm = new DefaultFileMonitor(this);
    fm.setRecursive(true);
    fm.addFile(listendir);
    fm.start();

    this.fileMonitor = fm;
}

From source file:com.collabnet.ccf.core.transformer.XsltProcessor.java

/**
 * Hook to perform any validation of the component properties required by
 * the implementation. Default behaviour should be a no-op.
 *///from   w w w  .j  a v a2 s.  c  o  m
@SuppressWarnings("unchecked")
public void validate(List exceptions) {
    // we have to make this map thread safe because it will be
    // updated asynchronously
    xsltFileNameTransformerMap = Collections.synchronizedMap(new HashMap<String, Transformer>());
    if (isListenForFileUpdates()) {
        try {
            fsManager = VFS.getManager();
        } catch (FileSystemException e) {
            exceptions
                    .add(new ValidationException("could not initialize file manager: " + e.getMessage(), this));
            return;
        }
        fileMonitor = new DefaultFileMonitor(new FileListener() {
            public void fileChanged(org.apache.commons.vfs.FileChangeEvent arg0) throws Exception {
                xsltFileNameTransformerMap.clear();
            }

            public void fileCreated(FileChangeEvent arg0) throws Exception {
                xsltFileNameTransformerMap.clear();
            }

            public void fileDeleted(FileChangeEvent arg0) throws Exception {
                xsltFileNameTransformerMap.clear();
            }
        });
    }

    String xsltDir = this.getXsltDir();
    String xsltFile = this.getXsltFile();
    if (!StringUtils.isEmpty(xsltDir)) {
        File xsltDirFile = new File(xsltDir);
        if (xsltDirFile.exists() && xsltDirFile.isDirectory()) {
            log.debug("xsltDir property " + xsltDir + " is a valid directory");
            if (listenForFileUpdates) {
                FileObject fileObject = null;
                try {
                    fileObject = fsManager.resolveFile(xsltDirFile.getAbsolutePath());
                } catch (FileSystemException e) {
                    exceptions.add(new ValidationException(
                            "xsltDir property " + xsltDir + " is not a valid directory: " + e.getMessage(),
                            this));
                    return;
                }
                fileMonitor.setRecursive(true);
                fileMonitor.addFile(fileObject);
                fileMonitor.start();
            }

        } else {
            exceptions.add(new ValidationException(
                    "xsltDir property " + xsltDir + " is not a valid directory...!", this));
            return;
        }
    } else if (!StringUtils.isEmpty(xsltFile)) {
        File xsltFileFile = new File(xsltFile);
        if (xsltFileFile.exists() && xsltFileFile.isFile()) {
            log.debug("xsltFile property " + xsltFile + " is a valid file");
            if (listenForFileUpdates) {
                FileObject fileObject = null;
                try {
                    fileObject = fsManager.resolveFile(xsltFileFile.getAbsolutePath());
                } catch (FileSystemException e) {
                    exceptions.add(new ValidationException(
                            "xsltFile property " + xsltFile + " is not a valid file...:" + e.getMessage(),
                            this));
                    return;
                }
                fileMonitor.addFile(fileObject);
                fileMonitor.start();
            }
        } else {
            exceptions.add(new ValidationException("xsltFile property " + xsltFile + " is not a valid file...!",
                    this));
            return;
        }
    }
}

From source file:com.collabnet.ccf.core.transformer.DynamicXsltProcessor.java

/**
 * Hook to perform any validation of the component properties required by
 * the implementation. Default behaviour should be a no-op.
 *//*  w  w w . j ava2  s .c o  m*/
@SuppressWarnings("unchecked")
public void validate(List exceptions) {
    // we have to make this map thread safe because it will be
    // updated asynchronously
    xsltFileNameTransformerMap = Collections.synchronizedMap(new HashMap<String, List<Transformer>>());
    if (isListenForFileUpdates()) {
        try {
            fsManager = VFS.getManager();
        } catch (FileSystemException e) {
            exceptions
                    .add(new ValidationException("could not initialize file manager: " + e.getMessage(), this));
            return;
        }
        fileMonitor = new DefaultFileMonitor(new FileListener() {
            public void fileChanged(org.apache.commons.vfs.FileChangeEvent arg0) throws Exception {
                xsltFileNameTransformerMap.clear();
            }

            public void fileCreated(FileChangeEvent arg0) throws Exception {
                xsltFileNameTransformerMap.clear();
            }

            public void fileDeleted(FileChangeEvent arg0) throws Exception {
                xsltFileNameTransformerMap.clear();
            }
        });
    }

    String xsltDir = this.getXsltDir();
    String xsltFile = this.getXsltFile();
    if (!StringUtils.isEmpty(xsltDir)) {
        File xsltDirFile = new File(xsltDir);
        if (xsltDirFile.exists() && xsltDirFile.isDirectory()) {
            log.debug("xsltDir property " + xsltDir + " is a valid directory");
            if (listenForFileUpdates) {
                FileObject fileObject = null;
                try {
                    fileObject = fsManager.resolveFile(xsltDirFile.getAbsolutePath());
                } catch (FileSystemException e) {
                    exceptions.add(new ValidationException(
                            "xsltDir property " + xsltDir + " is not a valid directory: " + e.getMessage(),
                            this));
                    return;
                }
                fileMonitor.setRecursive(true);
                fileMonitor.addFile(fileObject);
                fileMonitor.start();
            }
            if (scriptProcessors.isEmpty()) {
                log.warn("No scripts supplied, so dynamic XSLT processor will not change data at all");
            }
        } else {
            exceptions.add(new ValidationException(
                    "xsltDir property " + xsltDir + " is not a valid directory...!", this));
            return;
        }
    } else if (!StringUtils.isEmpty(xsltFile)) {
        File xsltFileFile = new File(xsltFile);
        if (xsltFileFile.exists() && xsltFileFile.isFile()) {
            log.debug("xsltFile property " + xsltFile + " is a valid file");
            if (listenForFileUpdates) {
                FileObject fileObject = null;
                try {
                    fileObject = fsManager.resolveFile(xsltFileFile.getAbsolutePath());
                } catch (FileSystemException e) {
                    exceptions.add(new ValidationException(
                            "xsltFile property " + xsltFile + " is not a valid file...:" + e.getMessage(),
                            this));
                    return;
                }
                fileMonitor.addFile(fileObject);
                fileMonitor.start();
            }
        } else {
            exceptions.add(new ValidationException("xsltFile property " + xsltFile + " is not a valid file...!",
                    this));
            return;
        }
    }
    factory = TransformerFactory.newInstance();
    if (isOnlyAllowWhiteListedJavaFunctionCalls()) {
        try {
            secureFactory = TransformerFactory.newInstance();
            secureFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
            secureFactory.setErrorListener(new XsltValidationErrorListener());
        } catch (TransformerConfigurationException e) {
            exceptions.add(new ValidationException(
                    "Setting secure processing feature on XSLT processor failed, bailing out since this feature is required by onlyAllowWhiteListedJavaFunctions property",
                    this));
            return;
        }
    }
}

From source file:org.ambud.marauder.source.ids.IDSFileSource.java

@Override
public void configure(Context context) {
    super.configure(context);
    context = new Context(context.getSubProperties(getPrefix()));
    this.watchDirectory = new File(context.getString(PROP_DIRECTORY, getDefaultDirectory()));
    this.logBaseName = context.getString(PROP_BASE_NAME, getDefaultFilename());
    this.isSequential = context.getBoolean(PROP_IS_SEQUENTIAL, true);
    logger.info("Snort Source will spool/watch - " + this.watchDirectory.getAbsolutePath()
            + " for Snort log files whose names start with:" + this.logBaseName);
    FileSystemManager fsMgr = null;//from w  w w.  ja  v a 2s .c o  m
    try {
        fsMgr = VFS.getManager();
    } catch (FileSystemException e) {
        Throwables.propagate(e);
    }
    try {
        this.watchObject = fsMgr.resolveFile(watchDirectory.getAbsolutePath());
    } catch (FileSystemException e) {
        Throwables.propagate(e);
    }
    this.monitor = new DefaultFileMonitor(new FileListener() {

        @Override
        public void fileChanged(FileChangeEvent arg0) throws Exception {
            // ignore these
        }

        @Override
        public void fileCreated(FileChangeEvent fileEvent) throws Exception {
            if (acceptFile(fileEvent.getFile().getName().getBaseName())) {
                logger.info("Acknowledged new file:" + fileEvent.getFile().getName().getPath());
                builderFileReader(fileEvent.getFile(), true);
            }
        }

        @Override
        public void fileDeleted(FileChangeEvent arg0) throws Exception {
            // acknowledge these
        }

    });
    int bufferSize = context.getInteger(PROP_BUFFER_SIZE, 500);
    this.outputQueue = new ArrayBlockingQueue<MarauderIDSEvent>(bufferSize);
}

From source file:org.ambud.marauder.source.readers.MarauderPollingTextFileReader.java

public MarauderPollingTextFileReader(File file, int pollingInterval)
        throws FileNotFoundException, FileSystemException {
    super(file);//w ww.  j av  a2s .c  o  m
    FileSystemManager fsMgr = VFS.getManager();
    FileObject fo = fsMgr.resolveFile(getFile().getAbsolutePath());
    this.monitor = new DefaultFileMonitor(new FileListener() {

        @Override
        public void fileDeleted(FileChangeEvent arg0) throws Exception {
            // can't do anything since the file is closed
            closeReader();
        }

        @Override
        public void fileCreated(FileChangeEvent arg0) throws Exception {
            // shouldn't happen if file already exist
        }

        @Override
        public void fileChanged(FileChangeEvent arg0) throws Exception {
            readFile();
        }
    });
    monitor.addFile(fo);
    monitor.setRecursive(false);
    monitor.setDelay(pollingInterval);
}

From source file:org.ambud.marauder.source.snort.SnortSourceBack.java

@Override
public void configure(Context context) {
    super.configure(context);
    context = new Context(context.getSubProperties(PROP_PREFIX));
    this.watchDirectory = new File(context.getString(PROP_DIRECTORY, PROP_DEFAULT_DIR));
    this.logBaseName = context.getString(PROP_BASE_NAME, PROP_DEFAULT_FILENAME);
    this.isSequential = context.getBoolean(PROP_IS_SEQUENTIAL, true);
    logger.info("Snort Source will spool/watch - " + this.watchDirectory.getAbsolutePath()
            + " for Snort log files whose names start with:" + this.logBaseName);
    FileSystemManager fsMgr = null;//from w w w.  j a  v a 2 s.c  om
    try {
        fsMgr = VFS.getManager();
    } catch (FileSystemException e) {
        Throwables.propagate(e);
    }
    try {
        this.watchObject = fsMgr.resolveFile(watchDirectory.getAbsolutePath());
    } catch (FileSystemException e) {
        Throwables.propagate(e);
    }
    this.monitor = new DefaultFileMonitor(new FileListener() {

        @Override
        public void fileChanged(FileChangeEvent arg0) throws Exception {
            // ignore these
        }

        @Override
        public void fileCreated(FileChangeEvent fileEvent) throws Exception {
            if (acceptFile(fileEvent.getFile().getName().getBaseName())) {
                logger.info("Acknowledged new file:" + fileEvent.getFile().getName().getPath());
                processFile(fileEvent.getFile(), true);
            }
        }

        @Override
        public void fileDeleted(FileChangeEvent arg0) throws Exception {
            // acknowledge these
        }

    });
    int bufferSize = context.getInteger("buffer.size", 500);
    this.outputQueue = new ArrayBlockingQueue<MarauderIDSEvent>(bufferSize);
}

From source file:org.innobuilt.fincayra.FincayraApplication.java

public void watch(String fileName) {
    if (this.getReloadRootScope()) {

        LOGGER.info("Adding file to root scope watch: {}", fileName);
        try {//from w  ww. jav  a2  s. c om
            FileSystemManager fsManager = VFS.getManager();
            FileObject listendir = fsManager.resolveFile(fileName);

            DefaultFileMonitor fm = new DefaultFileMonitor(new FincayraFileListener());
            fm.setRecursive(true);
            fm.addFile(listendir);
            fm.start();
        } catch (FileSystemException e) {
            LOGGER.error("Unable to watch directory: {}", fileName);
        }
    }
}