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

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

Introduction

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

Prototype

public static void forceDelete(File file) throws IOException 

Source Link

Document

Deletes a file.

Usage

From source file:edu.lternet.pasta.datapackagemanager.ArchiveCleaner.java

/**
 * Removes any archive file that is older than the specified time-to-live (ttl).
 * //w ww  . j a v  a2 s. c  om
 * @param ttl The time-to-live value in milliseconds.
 * @return    the number of archive files that were removed
 */
public int doClean(Long ttl) {
    File tmpDir = new File(this.tmpDir);
    String[] ext = { "zip" };
    Long time = new Date().getTime();
    Long lastModified = null;
    int deleteCount = 0;

    Collection<File> files = FileUtils.listFiles(tmpDir, ext, false);

    for (File file : files) {
        if (file != null && file.exists()) {
            lastModified = file.lastModified();
            // Remove file if older than the ttl
            if (lastModified + ttl <= time) {
                try {
                    FileUtils.forceDelete(file);
                    deleteCount++;
                } catch (IOException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                }
            }
        }
    }

    return deleteCount;
}

From source file:com.mindquarry.desktop.workspace.conflict.ReplaceConflict.java

public void beforeUpdate() throws ClientException, IOException {
    File file = new File(status.getPath());

    switch (action) {
    case UNKNOWN:
        // client did not set a conflict resolution
        log.error("AddConflict with no action set: " + status.getPath());
        break;/*  w  w w  .  j a v  a 2s. c  o  m*/

    case RENAME:
        log.info("renaming " + file.getAbsolutePath() + " to " + newName);

        File source = new File(status.getPath());
        File destination = new File(source.getParent(), newName);

        if (source.isDirectory()) {
            FileUtils.copyDirectory(source, destination);

            removeDotSVNDirectories(destination.getPath());
        } else {
            FileUtils.copyFile(source, destination);
        }

        client.add(destination.getPath(), true, true);
        client.remove(new String[] { file.getPath() }, null, true);

        break;

    case REPLACE:
        log.info("replacing with new file/folder from server: " + status.getPath());

        client.revert(file.getPath(), true);

        if (status.getRepositoryTextStatus() == StatusKind.replaced) {
            FileUtils.forceDelete(file);
        }

        break;
    }
}

From source file:TmpContent.java

/**
 * Clear all caches or delete disk temporary file.
 *
 * @throws IOException if cannot delete temporary file on disk
 *///from   w w w  .ja  va2 s .  co m
public void clear() throws IOException {
    if ((tmpFile != null) && tmpFile.exists()) {
        FileUtils.forceDelete(tmpFile);
    } else {
        byteArrayOutputStream = null;
    }
}

From source file:com.jivesoftware.os.jive.utils.shell.utils.Untar.java

public static List<File> unTar(boolean verbose, final File outputDir, final File inputFile,
        boolean deleteOriginal) throws FileNotFoundException, IOException, ArchiveException {

    if (verbose) {
        System.out.println(String.format("untaring %s to dir %s.", inputFile.getAbsolutePath(),
                outputDir.getAbsolutePath()));
    }//w  w w .j  av a2  s  .com

    final List<File> untaredFiles = new LinkedList<>();
    final InputStream is = new FileInputStream(inputFile);
    final TarArchiveInputStream debInputStream = (TarArchiveInputStream) new ArchiveStreamFactory()
            .createArchiveInputStream("tar", is);
    TarArchiveEntry entry = null;
    while ((entry = (TarArchiveEntry) debInputStream.getNextEntry()) != null) {
        String entryName = entry.getName();
        entryName = entryName.substring(entryName.indexOf("/") + 1);
        final File outputFile = new File(outputDir, entryName);
        if (entry.isDirectory()) {
            if (verbose) {
                System.out.println(String.format("Attempting to write output directory %s.",
                        getRelativePath(outputDir, outputFile)));
            }
            if (!outputFile.exists()) {
                if (verbose) {
                    System.out.println(String.format("Attempting to create output directory %s.",
                            getRelativePath(outputDir, outputFile)));
                }
                if (!outputFile.mkdirs()) {
                    throw new IllegalStateException(String.format("Couldn't create directory %s.",
                            getRelativePath(outputDir, outputFile)));
                }
            }
        } else {
            try {
                if (verbose) {
                    System.out.println(
                            String.format("Creating output file %s.", getRelativePath(outputDir, outputFile)));
                }
                outputFile.getParentFile().mkdirs();
                final OutputStream outputFileStream = new FileOutputStream(outputFile);
                IOUtils.copy(debInputStream, outputFileStream);
                outputFileStream.close();

                if (getRelativePath(outputDir, outputFile).contains("bin/")
                        || outputFile.getName().endsWith(".sh")) { // Hack!
                    if (verbose) {
                        System.out.println(
                                String.format("chmod +x file %s.", getRelativePath(outputDir, outputFile)));
                    }
                    outputFile.setExecutable(true);
                }

            } catch (Exception x) {
                System.err.println("failed to untar " + getRelativePath(outputDir, outputFile) + " " + x);
            }
        }
        untaredFiles.add(outputFile);
    }
    debInputStream.close();

    if (deleteOriginal) {
        FileUtils.forceDelete(inputFile);
        if (verbose) {
            System.out.println(String.format("deleted original file %s.", inputFile.getAbsolutePath()));
        }
    }
    return untaredFiles;
}

From source file:net.sourceforge.floggy.maven.PersistenceMojo.java

/**
 * DOCUMENT ME!/*www. j  av a2  s. c  o  m*/
*
* @throws MojoExecutionException DOCUMENT ME!
*/
public void execute() throws MojoExecutionException {
    MavenLogWrapper.setLog(getLog());

    LogFactory.getFactory().setAttribute("org.apache.commons.logging.Log",
            "net.sourceforge.floggy.maven.MavenLogWrapper");

    Weaver weaver = new Weaver();

    try {
        List list = project.getCompileClasspathElements();
        File temp = new File(project.getBuild().getDirectory(), String.valueOf(System.currentTimeMillis()));
        FileUtils.forceMkdir(temp);
        weaver.setOutputFile(temp);
        weaver.setInputFile(input);
        weaver.setClasspath((String[]) list.toArray(new String[list.size()]));

        if (configurationFile == null) {
            Configuration configuration = new Configuration();
            configuration.setAddDefaultConstructor(addDefaultConstructor);
            configuration.setGenerateSource(generateSource);
            weaver.setConfiguration(configuration);
        } else {
            weaver.setConfigurationFile(configurationFile);
        }

        weaver.execute();
        FileUtils.copyDirectory(temp, output);
        FileUtils.forceDelete(temp);
    } catch (Exception e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
}

From source file:com.facebook.presto.accumulo.tools.TestUtils.java

/**
 * Creates and starts an instance of MiniAccumuloCluster, returning the new instance.
 *
 * @return New MiniAccumuloCluster//from   w  ww.j a  v a 2  s. com
 */
private static MiniAccumuloCluster createMiniAccumuloCluster() throws IOException, InterruptedException {
    // Create MAC directory
    File macDir = Files.createTempDirectory("mac-").toFile();
    LOG.info("MAC is enabled, starting MiniAccumuloCluster at %s", macDir);

    // Start MAC and connect to it
    MiniAccumuloCluster accumulo = new MiniAccumuloCluster(macDir, "secret");
    accumulo.start();

    // Add shutdown hook to stop MAC and cleanup temporary files
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        try {
            LOG.info("Shutting down MAC");
            accumulo.stop();
        } catch (IOException | InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new PrestoException(MINI_ACCUMULO, "Failed to shut down MAC instance", e);
        }

        try {
            LOG.info("Cleaning up MAC directory");
            FileUtils.forceDelete(macDir);
        } catch (IOException e) {
            throw new PrestoException(MINI_ACCUMULO, "Failed to clean up MAC directory", e);
        }
    }));

    return accumulo;
}

From source file:com.bluexml.side.framework.facetmap.multimap.FacetMapCacheManager.java

public void deleteAllFacets() throws Exception {
    availableFacetMap.clear();//from www  .  j a  v a  2  s.c om
    // purge all facets (cache and files)
    File fileCacheRep = new Helper().getFileFromClassPath(cacheRep);
    if (fileCacheRep.exists()) {
        File[] l = fileCacheRep.listFiles();
        for (File file : l) {
            try {
                FileUtils.forceDelete(file);
                logger.debug("Erase Facet :" + getMapKey(file));
            } catch (Exception e) {
                logger.error("FacetMap " + getMapKey(file) + " not Erase :\n" + e.getMessage());
            }
        }
    }
    logger.debug("facetMaps :" + availableFacetMap.size());
}

From source file:com.willwinder.universalgcodesender.AbstractControllerTest.java

@AfterClass
static public void teardown() throws IOException {
    FileUtils.forceDelete(tempDir);
}

From source file:edu.ur.hibernate.ir.file.db.FileCollaboratorDAOTest.java

/**
* Setup for testing//  w  ww.j av  a 2s.c o  m
* 
* this deletes exiting test directories if they exist
*/
@BeforeMethod
public void cleanDirectory() {
    try {
        File f = new File(properties.getProperty("a_repo_path"));
        if (f.exists()) {
            FileUtils.forceDelete(f);
        }
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.btoddb.fastpersitentqueue.MemorySegmentSerializer.java

public void removePagingFile(MemorySegment segment) {
    File theFile = new File(directory, segment.getId().toString());
    try {/*from   ww w.  j a v a2 s  . c o m*/
        FileUtils.forceDelete(theFile);
        logger.debug("removed memory paging file {}", theFile.toString());
    } catch (FileNotFoundException e) {
        try {
            logger.debug("File not found (this is normal) while removing memory paging file, {}",
                    theFile.getCanonicalFile());
        } catch (IOException e1) {
            // ignore
        }
    } catch (IOException e) {
        try {
            logger.error("exception while removing memory paging file, {}", theFile.getCanonicalFile(), e);
        } catch (IOException e1) {
            // ignore
            logger.error("another exception while removing memory paging file", e);
        }
    }
}