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

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

Introduction

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

Prototype

public static boolean deleteQuietly(File file) 

Source Link

Document

Deletes a file, never throwing an exception.

Usage

From source file:it.anyplace.sync.core.cache.FileBlockCache.java

private void runCleanup() {
    if (size > MAX_SIZE) {
        logger.info("starting cleanup of cache directory, initial size = {}",
                FileUtils.byteCountToDisplaySize(size));
        List<File> files = Lists.newArrayList(dir.listFiles());
        Collections.sort(files, Ordering.natural().onResultOf(new Function<File, Long>() {
            @Override//from   w  w w  .  j  a  va2  s .c o  m
            public Long apply(File input) {
                return input.lastModified();
            }
        }));
        for (File file : Iterables.limit(files, (int) (files.size() * PERC_TO_DELETE))) {
            logger.debug("delete file {}", file);
            FileUtils.deleteQuietly(file);
        }
        size = FileUtils.sizeOfDirectory(dir);
        logger.info("cleanup of cache directory completed, final size = {}",
                FileUtils.byteCountToDisplaySize(size));
    }
}

From source file:de.uzk.hki.da.convert.TiffConversionStrategyTests.java

@After
public void tearDown() throws IOException {
    Path.makeFile(contractorFolder, "1/data/rep+b/CCITT_1.TIF").delete();
    Path.makeFile(contractorFolder, "1/data/rep+b/CCITT_1_UNCOMPRESSED.TIF").delete();
    FileUtils.deleteQuietly(Path.makeFile(contractorFolder, "1/data/rep+b"));
    org.apache.commons.io.FileUtils.deleteDirectory(Path.makeFile(contractorFolder, "/1/data/rep+b/subfolder"));
}

From source file:ke.co.tawi.babblesms.server.persistence.utils.DbFileUtils.java

/**
 * This is used to export the results of an SQL query into a CSV text file.
 *
 * @param sqlQuery/*from  w ww  . j  a v  a 2 s .c o  m*/
 * @param fileName this should include the full path of the file e.g.
 * /tmp/myFile.csv
 * @param delimiter
 *
 * @return whether the action was successful or not
 */
public boolean sqlResultToCSV(String sqlQuery, String fileName, char delimiter) {
    boolean success = true;

    String sanitizedQuery = StringUtils.remove(sqlQuery, ';');

    BufferedWriter writer;

    try (
            // Return a database connection that is not pooled
            // to enable the connection to be cast to BaseConnection
            Connection conn = dbCredentials.getJdbcConnection();) {

        FileUtils.deleteQuietly(new File(fileName));
        FileUtils.touch(new File(fileName));
        writer = new BufferedWriter(new FileWriter(fileName));

        CopyManager copyManager = new CopyManager((BaseConnection) conn);

        StringBuffer query = new StringBuffer("COPY (").append(sanitizedQuery)
                .append(") to STDOUT WITH DELIMITER '").append(delimiter).append("'");

        copyManager.copyOut(query.toString(), writer);
        writer.close();

    } catch (SQLException e) {
        logger.error(
                "SQLException while exporting results of query '" + sqlQuery + "' to file '" + fileName + "'.");
        logger.error(ExceptionUtils.getStackTrace(e));
        success = false;

    } catch (IOException e) {
        logger.error(
                "IOException while exporting results of query '" + sqlQuery + "' to file '" + fileName + "'.");
        logger.error(ExceptionUtils.getStackTrace(e));
        success = false;
    }

    return success;
}

From source file:com.strandls.alchemy.rest.client.stubgenerator.GuiceModuleGeneratorTest.java

/**
 * Test method for//from w w  w.j a  v a 2 s  .c  o m
 * {@link com.strandls.alchemy.rest.client.stubgenerator.GuiceModuleGenerator#generateGuiceModule(java.lang.String, java.io.File, java.util.Map)}
 * .
 *
 * @throws Exception
 */
@Test
public void testGenerateModuleWithOutPackage() throws Exception {
    final GuiceModuleGenerator generator = new GuiceModuleGenerator();
    final File tempDir = File.createTempFile("test", "test");
    FileUtils.deleteQuietly(tempDir);

    if (!tempDir.mkdirs()) {
        throw new IOException("Cannot create temporary directory.");
    }
    try {
        final Map<String, String> map = new LinkedHashMap<String, String>();
        map.put("testStub1", "testStub1Proxy");
        map.put("testStub2", "testStub2Proxy");
        generator.generateGuiceModule(null, tempDir, map);

        String actualGuicemodule = FileUtils
                .readFileToString(new File(tempDir, GuiceModuleGenerator.CLIENT_GUICE_MODULE_NAME + ".java"))
                .trim();
        String actualGuiceModule = actualGuicemodule;
        assertEquals(
                FileUtils.readFileToString(
                        new File("src/test/resources/com/strandls/alchemy/rest/client/stubgenerator/"
                                + GuiceModuleGenerator.CLIENT_GUICE_MODULE_NAME + ".txt"))
                        .trim(),
                actualGuiceModule);
    } finally {
        FileUtils.deleteQuietly(tempDir);
    }
}

From source file:com.thoughtworks.go.domain.builder.FetchArtifactBuilderTest.java

@After
public void tearDown() throws Exception {
    for (File fileToClean : toClean) {
        FileUtils.deleteQuietly(fileToClean);
    }
}

From source file:com.adaptris.core.lms.LargeFsConsumerTest.java

public void testConsumeWithAlternateFactory() throws Exception {
    String subDir = GUID.safeUUID();
    MockMessageListener stub = new MockMessageListener(10);
    FsConsumer fs = createConsumer(subDir);
    fs.setResetWipFiles(false);/*from w ww . j a v a  2  s  .  c  o m*/
    fs.setMessageFactory(new DefaultMessageFactory());
    fs.setPoller(new FixedIntervalPoller(new TimeInterval(300L, TimeUnit.MILLISECONDS)));
    StandaloneConsumer sc = new StandaloneConsumer(fs);
    sc.registerAdaptrisMessageListener(stub);
    int count = 10;
    File parentDir = FsHelper
            .createFileReference(FsHelper.createUrlFromString(PROPERTIES.getProperty(BASE_KEY), true));
    try {
        File baseDir = new File(parentDir, subDir);
        baseDir.mkdirs();
        super.createFiles(baseDir, ".xml", count);
        start(sc);
        waitForMessages(stub, count);
        assertEquals(count, stub.getMessages().size());
        super.assertMessages(stub.getMessages(), count,
                baseDir.listFiles((FilenameFilter) new Perl5FilenameFilter(".*\\.xml")));
        assertDefaultMessageType(stub.getMessages());
    } finally {
        stop(sc);
        FileUtils.deleteQuietly(new File(parentDir, subDir));
    }
}

From source file:com.francetelecom.clara.cloud.activation.plugin.cf.infrastructure.FileFetcherUtil.java

/**
 * Typically invoked by ManageJEEDeploymentImpl.deployOnPaas() using an inputstream read from the SOAP request.
 *
 * @param filename the original name of the file (e.g. "myapp.ear")
 * @param filetype optional file type (e.g. usually extension "jar" "ear" or "war") or null to try to detect it from filename
 * @throws TechnicalException//from  www  .j a v  a  2s. co  m
 */
public void fetchInputStreamAndApplyProcessing(String filename, String filetype, InputStream filestream,
        FileProcessor fileProcessor) throws TechnicalException {

    // define filetype regarding file extension
    if (filetype == null) {
        filetype = getDeployableType(filename);
    }

    File tempFile = null;
    try {
        // The CF SDK is requiring local files only, so we need to create a temp local file in a temp directory
        tempFile = createTempFileFromInputStream(filename, filestream, filetype);
        fileProcessor.process(filename, filetype, tempFile);
    } catch (IOException e) {
        throw new TechnicalException("IOException on cargo deployment : " + e.getMessage(), e);
    } catch (Exception e) {
        throw new TechnicalException("Error on stream processing : " + e.getMessage(), e);
    } finally {
        FileUtils.deleteQuietly(tempFile.getParentFile());
    }
}

From source file:com.linkedin.pinot.core.startree.hll.SegmentWithHllIndexCreateHelper.java

/**
 * must call this to clean up
 */
public void cleanTempDir() {
    if (INDEX_DIR != null) {
        FileUtils.deleteQuietly(INDEX_DIR);
    }
}

From source file:io.github.swagger2markup.internal.component.PathOperationComponentTest.java

@Test
public void testInlineSchema() throws URISyntaxException {
    String COMPONENT_NAME = "path_operation_inline_schema";
    Path outputDirectory = getOutputFile(COMPONENT_NAME);
    FileUtils.deleteQuietly(outputDirectory.toFile());

    //Given/*ww w. j  a v  a 2  s.c o  m*/
    Path file = Paths
            .get(PathOperationComponentTest.class.getResource("/yaml/swagger_inlineSchema.yaml").toURI());
    Swagger2MarkupConverter converter = Swagger2MarkupConverter.from(file).build();
    Swagger swagger = converter.getContext().getSwagger();

    io.swagger.models.Path path = swagger.getPaths().get("/LaunchCommand");
    List<PathOperation> pathOperations = PathUtils.toPathOperationsList("/LaunchCommand", path);

    Swagger2MarkupConverter.Context context = converter.getContext();
    MarkupDocBuilder markupDocBuilder = context.createMarkupDocBuilder();

    //When
    markupDocBuilder = new PathOperationComponent(context, new DefinitionDocumentResolverFromOperation(context),
            new SecurityDocumentResolver(context)).apply(markupDocBuilder,
                    PathOperationComponent.parameters(pathOperations.get(0)));

    markupDocBuilder.writeToFileWithoutExtension(outputDirectory, StandardCharsets.UTF_8);

    //Then
    Path expectedFile = getExpectedFile(COMPONENT_NAME);
    DiffUtils.assertThatFileIsEqual(expectedFile, outputDirectory, getReportName(COMPONENT_NAME));

}

From source file:c3.ops.priam.backup.MetaData.java

@SuppressWarnings("unchecked")
public void set(List<AbstractBackupPath> bps, String snapshotName) throws Exception {
    File metafile = createTmpMetaFile();
    FileWriter fr = new FileWriter(metafile);
    try {/* w w  w.  j ava 2  s.  co  m*/
        JSONArray jsonObj = new JSONArray();
        for (AbstractBackupPath filePath : bps)
            jsonObj.add(filePath.getRemotePath());
        fr.write(jsonObj.toJSONString());
    } finally {
        IOUtils.closeQuietly(fr);
    }
    AbstractBackupPath backupfile = pathFactory.get();
    backupfile.parseLocal(metafile, BackupFileType.META);
    backupfile.time = backupfile.parseDate(snapshotName);
    try {
        upload(backupfile);

        addToRemotePath(backupfile.getRemotePath());
        if (metaRemotePaths.size() > 0) {
            notifyObservers();
        }
    } finally {
        FileUtils.deleteQuietly(metafile);
    }
}