Example usage for org.apache.commons.io FileUtils isFileOlder

List of usage examples for org.apache.commons.io FileUtils isFileOlder

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils isFileOlder.

Prototype

public static boolean isFileOlder(File file, long timeMillis) 

Source Link

Document

Tests if the specified File is older than the specified time reference.

Usage

From source file:com.norconex.commons.lang.file.FileUtil.java

/**
 * Deletes all directories that are empty and are <b>older</b> 
 * than the given date.  If the date is <code>null</code>, all empty 
 * directories will be deleted, regardless of their date.
 * @param parentDir the directory where to start looking for empty 
 *        directories/*www .  j  a  v  a  2 s .c  o  m*/
 * @param date the date to compare empty directories against
 * @return the number of deleted directories
 * @since 1.3.0
 */
public static int deleteEmptyDirs(File parentDir, final Date date) {
    final MutableInt dirCount = new MutableInt(0);
    visitEmptyDirs(parentDir, new IFileVisitor() {
        @Override
        public void visit(File file) {
            if (date == null || FileUtils.isFileOlder(file, date)) {
                String[] children = file.list();
                if (file.isDirectory() && (children == null || children.length == 0)) {
                    try {
                        FileUtil.delete(file);
                        dirCount.increment();
                    } catch (IOException e) {
                        LOG.error("Could not be delete directory: " + file, e);
                    }
                }
            }
        }
    });
    return dirCount.intValue();
}

From source file:com.daimler.spm.storefront.filters.AcceleratorAddOnFilter.java

/**
 * Copies file @param sourceAddOnFileName to @param targetWebAddOnFileName if it is older. Creates a directory
 * structure if needed.//from   w w w . j  a  v a 2  s  .  c o  m
 *
 * @param sourceAddOnFileName
 * @param targetWebAddOnFileName
 * @throws IOException
 */
protected void copyFileInternalIfNeeded(final String sourceAddOnFileName, final String targetWebAddOnFileName)
        throws IOException {
    PathTraversalResourceUtils.assertPathSegmentIsSecure(sourceAddOnFileName);
    PathTraversalResourceUtils.assertPathSegmentIsSecure(targetWebAddOnFileName);

    final File sourceAddOnFile = new File(sourceAddOnFileName);
    final File targetAddOnFile = new File(targetWebAddOnFileName);

    if (!sourceAddOnFile.exists()) {
        LOG.warn("Add-on source file [" + sourceAddOnFileName + "] should exists ");
        return;
    }
    if (!targetAddOnFile.exists()) {
        try {
            FileUtils.forceMkdir(targetAddOnFile.getParentFile());
        } catch (final IOException e) {
            LOG.info("Unable to create addon folder for resource " + targetAddOnFile.getParent()
                    + " please rebuild platform for relocating add-ons");
            if (LOG.isDebugEnabled()) {
                LOG.debug(e);
            }
        }
        FileUtils.copyFile(sourceAddOnFile, targetAddOnFile);
    } else {
        if (FileUtils.isFileOlder(targetAddOnFile, sourceAddOnFile)) {
            LOG.info("Copying <<" + sourceAddOnFile.getAbsolutePath() + ">> to <<"
                    + targetAddOnFile.getAbsolutePath() + ">>.");
            FileUtils.copyFile(sourceAddOnFile, targetAddOnFile);
        }
    }
}

From source file:ch.entwine.weblounge.contentrepository.impl.PreviewGeneratorWorker.java

/**
 * Creates the actual preview./* ww  w.jav a2s  .c  om*/
 * 
 * @param resource
 *          the resource
 * @param style
 *          the image style
 * @param language
 *          the language
 * @param previewGenerator
 *          the preview generator
 * @param the
 *          preview format
 * @return returns the preview file
 */
private File createPreview(Resource<?> resource, ImageStyle style, Language language,
        PreviewGenerator previewGenerator, String format) {

    ResourceURI resourceURI = resource.getURI();
    String resourceType = resourceURI.getType();

    // Create the filename
    ResourceContent content = resource.getContent(language);

    // Initiate creation of previews
    InputStream resourceInputStream = null;
    InputStream contentRepositoryIs = null;
    FileOutputStream fos = null;
    File scaledResourceFile = null;

    try {
        scaledResourceFile = ImageStyleUtils.getScaledFile(resource, language, style);

        // Find the modification date
        long lastModified = ResourceUtils.getModificationDate(resource, language).getTime();

        // Create the file if it doesn't exist or if it is out dated. Note that
        // the last modified date of a file has a precision of seconds
        if (!scaledResourceFile.isFile() || FileUtils.isFileOlder(scaledResourceFile, new Date(lastModified))) {
            contentRepositoryIs = contentRepository.getContent(resourceURI, language);

            // Is this local content?
            if (contentRepositoryIs == null && content != null && content.getExternalLocation() != null) {
                contentRepositoryIs = content.getExternalLocation().openStream();
            }

            // Create the parent directory
            File scaledResourceDir = scaledResourceFile.getParentFile();
            if (!scaledResourceDir.isDirectory() && !scaledResourceDir.mkdirs()) {
                AbstractContentRepository.logger.warn("Error creating parent directory of preview file {}",
                        scaledResourceFile.getAbsolutePath());
                return null;
            }

            // Create the file if it doesn't exist
            if (!scaledResourceFile.isFile() && !scaledResourceFile.createNewFile()) {
                AbstractContentRepository.logger.warn("Error creating preview file {}",
                        scaledResourceFile.getAbsolutePath());
                return null;
            }

            // Create the preview
            fos = new FileOutputStream(scaledResourceFile);
            AbstractContentRepository.logger.debug("Creating preview of '{}' at {}", resource,
                    scaledResourceFile);
            previewGenerator.createPreview(resource, environment, language, style, format, contentRepositoryIs,
                    fos);
        }

    } catch (ContentRepositoryException e) {
        AbstractContentRepository.logger.error("Error loading {} {} '{}' from {}: {}",
                new Object[] { language, resourceType, resource, this, e.getMessage() });
        AbstractContentRepository.logger.error(e.getMessage(), e);
        IOUtils.closeQuietly(resourceInputStream);
    } catch (IOException e) {
        AbstractContentRepository.logger.warn("Error creating preview for {} '{}': {}",
                new Object[] { resourceType, resourceURI, e.getMessage() });
        IOUtils.closeQuietly(resourceInputStream);
    } catch (Throwable t) {
        AbstractContentRepository.logger.warn("Error creating preview for {} '{}': {}",
                new Object[] { resourceType, resourceURI, t.getMessage() });
        IOUtils.closeQuietly(resourceInputStream);

    } finally {
        IOUtils.closeQuietly(contentRepositoryIs);
        IOUtils.closeQuietly(fos);

        // Make sure corrupted preview images are being deleted
        File f = scaledResourceFile;
        if (f != null && f.length() == 0) {
            FileUtils.deleteQuietly(f);
            f = f.getParentFile();
            while (f != null && f.isDirectory() && (f.listFiles() == null || f.listFiles().length == 0)) {
                FileUtils.deleteQuietly(f);
                f = f.getParentFile();
            }
        }
    }

    return scaledResourceFile;
}

From source file:eu.earthobservatory.org.StrabonEndpoint.QueryBean.java

/**
  * Processes the request made from the HTML visual interface of Strabon Endpoint.
  * //from   w ww .  j  a va  2 s  .c o  m
  * @param request
  * @param response
  * @throws ServletException
  * @throws IOException
  */
private void processVIEWRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    RequestDispatcher dispatcher;

    // check whether Update submit button was fired
    String reqFuncionality = (request.getParameter("submit") == null) ? "" : request.getParameter("submit");

    if (reqFuncionality.equals("Update")) {
        // get the dispatcher for forwarding the rendering of the response
        dispatcher = request.getRequestDispatcher("/Update");
        dispatcher.forward(request, response);

    } else {
        String query = URLDecoder.decode(request.getParameter("query"), "UTF-8");
        String format = request.getParameter("format");
        String handle = request.getParameter("handle");
        String maxLimit = request.getParameter("maxLimit");

        // get stSPARQLQueryResultFormat from given format name
        TupleQueryResultFormat queryResultFormat = stSPARQLQueryResultFormat.valueOf(format);

        if (query == null || format == null || queryResultFormat == null) {
            dispatcher = request.getRequestDispatcher("query.jsp");
            request.setAttribute(ERROR, PARAM_ERROR);
            dispatcher.forward(request, response);

        } else {
            query = strabonWrapper.addLimit(query, maxLimit);
            if ("download".equals(handle)) { // download as attachment
                ServletOutputStream out = response.getOutputStream();

                response.setContentType(queryResultFormat.getDefaultMIMEType());
                response.setHeader("Content-Disposition", "attachment; filename=results."
                        + queryResultFormat.getDefaultFileExtension() + "; " + queryResultFormat.getCharset());

                try {
                    strabonWrapper.query(query, format, out);
                    response.setStatus(HttpServletResponse.SC_OK);

                } catch (Exception e) {
                    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                    out.print(ResponseMessages.getXMLHeader());
                    out.print(ResponseMessages.getXMLException(e.getMessage()));
                    out.print(ResponseMessages.getXMLFooter());
                }

                out.flush();

            } else if (("map".equals(handle) || "map_local".equals(handle) || "timemap".equals(handle))
                    && (queryResultFormat == stSPARQLQueryResultFormat.KML
                            || queryResultFormat == stSPARQLQueryResultFormat.KMZ)) {
                // show map (only valid for KML/KMZ)

                // get dispatcher
                dispatcher = request.getRequestDispatcher("query.jsp");

                // re-assign handle
                request.setAttribute("handle", handle);

                SecureRandom random = new SecureRandom();
                String temp = new BigInteger(130, random).toString(32);

                // the temporary KML/KMZ file to create in the server
                String tempKMLFile = temp + "." + queryResultFormat.getDefaultFileExtension();
                ;

                try {
                    Date date = new Date();

                    // get the absolute path of the temporary directory
                    if (!request.getParameter("handle").toString().contains("timemap")) {
                        tempDirectory = appName + "-temp";

                        basePath = context.getRealPath("/") + "/../ROOT/" + tempDirectory + "/";
                        // fix the temporary directory for this web application

                        FileUtils.forceMkdir(new File(basePath));

                        @SuppressWarnings("unchecked")
                        Iterator<File> it = FileUtils.iterateFiles(new File(basePath), null, false);
                        while (it.hasNext()) {
                            File tbd = new File((it.next()).getAbsolutePath());
                            if (FileUtils.isFileOlder(new File(tbd.getAbsolutePath()), date.getTime())) {
                                FileUtils.forceDelete(new File(tbd.getAbsolutePath()));
                            }
                        }
                    } else { //timemap case
                        tempDirectory = "js/timemap";
                        basePath = context.getRealPath("/") + tempDirectory + "/";
                        // fix the temporary directory for this web application
                    }

                    // fix the temporary directory for this web application

                    // create temporary KML/KMZ file
                    File file = new File(basePath + tempKMLFile);
                    // if file does not exist, then create it
                    if (!file.exists()) {
                        file.createNewFile();
                    }

                    try {
                        // query and write the result in the temporary KML/KMZ file
                        FileOutputStream fos = new FileOutputStream(basePath + tempKMLFile);
                        strabonWrapper.query(query, format, fos);
                        fos.close();

                        if (request.getParameter("handle").toString().contains("timemap")) {
                            request.setAttribute("pathToKML", tempDirectory + "/" + tempKMLFile);
                        } else {
                            request.setAttribute("pathToKML",
                                    request.getScheme() + "://" + request.getServerName() + ":"
                                            + request.getServerPort() + "/" + tempDirectory + "/"
                                            + tempKMLFile);
                        }

                    } catch (MalformedQueryException e) {
                        logger.error("[StrabonEndpoint.QueryBean] Error during querying. {}", e.getMessage());
                        request.setAttribute(ERROR, e.getMessage());

                    } catch (Exception e) {
                        logger.error("[StrabonEndpoint.QueryBean] Error during querying.", e);
                        request.setAttribute(ERROR, e.getMessage());
                    }

                    dispatcher.forward(request, response);

                } catch (IOException e) {
                    logger.error("[StrabonEndpoint.QueryBean] Error during querying.", e);
                }

            } else { // "plain" is assumed as the default
                dispatcher = request.getRequestDispatcher("query.jsp");
                ByteArrayOutputStream bos = new ByteArrayOutputStream();

                try {
                    strabonWrapper.query(query, format, bos);
                    if (format.equals(Common.getHTMLFormat())) {
                        request.setAttribute(RESPONSE, bos.toString());
                    } else if (format.equals(Format.PIECHART.toString())
                            || format.equals(Format.AREACHART.toString())
                            || format.equals(Format.COLUMNCHART.toString())) {
                        request.setAttribute("format", "CHART");
                        request.setAttribute(RESPONSE, strabonWrapper.getgChartString());
                    }

                    else {
                        request.setAttribute(RESPONSE, StringEscapeUtils.escapeHtml(bos.toString()));
                    }

                } catch (MalformedQueryException e) {
                    logger.error("[StrabonEndpoint.QueryBean] Error during querying. {}", e.getMessage());
                    request.setAttribute(ERROR, e.getMessage());

                } catch (Exception e) {
                    logger.error("[StrabonEndpoint.QueryBean] Error during querying.", e);
                    request.setAttribute(ERROR, e.getMessage());

                } finally {
                    dispatcher.forward(request, response);
                }
            }
        }
    }
}

From source file:dk.dma.msinm.common.repo.RepositoryService.java

/**
 * Recursively delete one day old files and folders
 * @param file the current root file or folder
 * @param date the expiry date/*from w w w. j  av a 2  s  .  c  o m*/
 */
private void checkDeletePath(File file, Date date) {
    if (FileUtils.isFileOlder(file, date)) {
        log.info("Deleting expired temp file or folder: " + file);
        FileUtils.deleteQuietly(file);
    } else if (file.isDirectory()) {
        File[] files = file.listFiles();
        if (files != null && files.length > 0) {
            Arrays.asList(files).forEach(f -> checkDeletePath(f, date));
        }
    }
}

From source file:me.mast3rplan.phantombot.PhantomBot.java

/**
 * Backup the database, keeping so many days.
 *//*  www  . j  a v a  2  s  .com*/
private void doBackupSQLiteDB() {

    if (!dataStoreType.equals("sqlite3store")) {
        return;
    }

    ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
    service.scheduleAtFixedRate(() -> {
        SimpleDateFormat datefmt = new SimpleDateFormat("ddMMyyyy.hhmmss");
        datefmt.setTimeZone(TimeZone.getTimeZone(timeZone));
        String timestamp = datefmt.format(new Date());

        dataStore.backupSQLite3("phantombot.auto.backup." + timestamp + ".db");

        try {
            Iterator dirIterator = FileUtils.iterateFiles(new File("./dbbackup"),
                    new WildcardFileFilter("phantombot.auto.*"), null);
            while (dirIterator.hasNext()) {
                File backupFile = (File) dirIterator.next();
                if (FileUtils.isFileOlder(backupFile,
                        System.currentTimeMillis() - (86400000 * backupSQLiteKeepDays))) {
                    FileUtils.deleteQuietly(backupFile);
                }
            }
        } catch (Exception ex) {
            com.gmt2001.Console.err.println("Failed to clean up database backup directory: " + ex.getMessage());
        }
    }, 0, backupSQLiteHourFrequency, TimeUnit.HOURS);
}

From source file:org.apache.jackrabbit.oak.spi.blob.FileBlobStore.java

@Override
public long countDeleteChunks(List<String> chunkIds, long maxLastModifiedTime) throws Exception {
    int count = 0;
    for (String chunkId : chunkIds) {
        byte[] digest = StringUtils.convertHexToBytes(chunkId);
        File f = getFile(digest, false);
        if (!f.exists()) {
            File old = getFile(digest, true);
            f.getParentFile().mkdir();//from  w w  w  .j  a v a2 s. c o  m
            old.renameTo(f);
            f = getFile(digest, false);
        }
        if ((maxLastModifiedTime <= 0) || FileUtils.isFileOlder(f, maxLastModifiedTime)) {
            f.delete();
            count++;
        }
    }
    return count;
}

From source file:org.apache.jackrabbit.oak.spi.blob.FileBlobStore.java

@Override
public Iterator<String> getAllChunkIds(final long maxLastModifiedTime) throws Exception {
    FluentIterable<File> iterable = Files.fileTreeTraverser().postOrderTraversal(baseDir);
    final Iterator<File> iter = iterable.filter(new Predicate<File>() {
        // Ignore the directories and files newer than maxLastModifiedTime if specified
        @Override/*from   w  w w. j  av a2s  . c  om*/
        public boolean apply(@Nullable File input) {
            if (!input.isDirectory()
                    && ((maxLastModifiedTime <= 0) || FileUtils.isFileOlder(input, maxLastModifiedTime))) {
                return true;
            }
            return false;
        }
    }).iterator();
    return new AbstractIterator<String>() {
        @Override
        protected String computeNext() {
            if (iter.hasNext()) {
                File file = iter.next();
                return FilenameUtils.removeExtension(file.getName());
            }
            return endOfData();
        }
    };
}

From source file:org.efaps.admin.program.esjp.EFapsClassLoader.java

/**
 * In case of jbpm this is necessary for compiling,
 * because they search the classes with URL.
 * @param _name filename as url//from   w ww.j ava 2 s  .  c o  m
 * @return URL if found
 */
@Override
public URL findResource(final String _name) {
    URL ret = null;
    final String name = _name.replaceAll(System.getProperty("file.separator"), ".").replaceAll(".class", "");
    final byte[] data = loadClassData(name);
    if (data != null && data.length > 0) {
        final File file = FileUtils.getFile(EFapsClassLoader.getTempFolder(), name);
        try {
            if (!file.exists() || FileUtils.isFileOlder(file, new DateTime().minusHours(1).toDate())) {
                FileUtils.writeByteArrayToFile(file, data);
            }
            ret = file.toURI().toURL();
        } catch (final IOException e) {
            LOG.error("Could not geneate File for reading from URL: {}", name);
        }
    }
    return ret;
}

From source file:org.niord.core.batch.BatchService.java

/**
 * Called every hour to clean up the batch job "[jobName]/execution" folders for expired files
 *///w w w . ja  v  a2s. c  o  m
@Schedule(persistent = false, second = "30", minute = "42", hour = "*/1")
protected void cleanUpExpiredBatchJobFiles() {

    long t0 = System.currentTimeMillis();

    // Resolve the list of batch job "execution" folders
    List<Path> executionFolders = getBatchJobSubFolders("execution");

    // Compute the expiry time
    Calendar expiryDate = Calendar.getInstance();
    expiryDate.add(Calendar.DATE, -batchFileExpiryDays);

    // Clean up the files
    executionFolders.forEach(folder -> {
        try {
            Files.walkFileTree(folder, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                    if (isDirEmpty(dir)) {
                        log.debug("Deleting batch job directory :" + dir);
                        Files.delete(dir);
                    }
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    if (FileUtils.isFileOlder(file.toFile(), expiryDate.getTime())) {
                        log.debug("Deleting batch job file      :" + file);
                        Files.delete(file);
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException e) {
            log.error("Failed cleaning up " + folder + " batch job directory: " + e.getMessage(), e);
        }
    });

    log.debug(String.format("Cleaned up expired batch job files in %d ms", System.currentTimeMillis() - t0));
}