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:net.nicholaswilliams.java.licensing.TestFileLicenseProvider.java

@Test
public void testGetLicenseData04() throws IOException {
    File temp = new File("testGetLicenseData04.lic");
    FileUtils.writeStringToFile(temp, "test get 04");

    this.provider = EasyMock.createMockBuilder(FileLicenseProvider.class).addMockedMethod("getLicenseFile")
            .createStrictMock();/*from  w  w w . ja  v  a  2 s .  co m*/

    EasyMock.expect(this.provider.getLicenseFile("test04")).andReturn(new File("testGetLicenseData04.lic"));
    EasyMock.replay(this.provider);

    byte[] data = this.provider.getLicenseData("test04");

    assertNotNull("The data should not be null.", data);
    assertEquals("The data is not correct.", "test get 04", new String(data));

    FileUtils.forceDelete(temp);
}

From source file:eu.udig.catalog.jgrass.operations.SetActiveRegionToMapsAction.java

/**
 * Given the mapsetpath and the mapname, the map is removed with all its accessor files
 * /*from w  ww  . j  ava2 s . c  o  m*/
 * @param mapsetPath
 * @param mapName
 * @throws IOException 
 */
public void removeGrassRasterMap(String mapsetPath, String mapName) throws IOException {
    // list of files to remove
    String mappaths[] = filesOfRasterMap(mapsetPath, mapName);

    // first delete the list above, which are just files
    for (int j = 0; j < mappaths.length; j++) {
        File filetoremove = new File(mappaths[j]);
        if (filetoremove.exists()) {
            FileUtils.forceDelete(filetoremove);
        }
    }
}

From source file:android.databinding.compilationTest.BaseCompilationTest.java

protected void prepareModule(String moduleName, String packageName, Map<String, String> replacements)
        throws IOException, URISyntaxException {
    replacements = addDefaults(replacements);
    replacements.put(KEY_MANIFEST_PACKAGE, packageName);
    File moduleFolder = new File(testFolder, moduleName);
    if (moduleFolder.exists()) {
        FileUtils.forceDelete(moduleFolder);
    }/*w  w w . j  a  v  a 2  s. c  o  m*/
    FileUtils.forceMkdir(moduleFolder);
    copyResourceTo("/AndroidManifest.xml", new File(moduleFolder, "src/main/AndroidManifest.xml"),
            replacements);
    copyResourceTo("/module_build.gradle", new File(moduleFolder, "build.gradle"), replacements);
}

From source file:architecture.ee.plugin.impl.PluginManagerImpl.java

public void deleteBrokenPlugin(String pluginName) {
    try {//from ww w. jav a  2s  .c o m
        pluginDao.delete(pluginName);
    } catch (Exception e) {
    }
    try {
        File f = new File(pluginDirectory,
                (new StringBuilder()).append(pluginName).append("_broken").toString());
        FileUtils.forceDelete(f);
    } catch (Exception e) {
    }
    brokenPlugins.remove(pluginName);
    brokenPluginUpgradeExceptions.remove(pluginName);
}

From source file:com.jaxio.celerio.util.IOUtil.java

/**
 * force the deletion of a file//from  w w w .  j  a v  a  2 s  . c o m
 */
public void forceDelete(File tempFile) {
    try {
        if (tempFile != null && tempFile.exists()) {
            FileUtils.forceDelete(tempFile);
        }
    } catch (Throwable t) {
        t.printStackTrace();
    }
}

From source file:jenkins.plugins.asqatasun.AsqatasunRunnerBuilder.java

/**
 * /*  w ww .  ja v  a  2s.c  o  m*/
 * @param asqatasunRunner
 * @param scenario
 * @param workspace
 */
private void linkToWebapp(AsqatasunRunner asqatasunRunner, String scenarioName, String scenario,
        File contextDir, PrintStream printStream, boolean isDebug, String projectName)
        throws IOException, InterruptedException {

    File insertProcedureFile = AsqatasunRunnerBuilder.createTempFile(contextDir, SQL_PROCEDURE_SCRIPT_NAME,
            IOUtils.toString(getClass().getResourceAsStream(SQL_PROCEDURE_NAME)));
    if (isDebug) {
        printStream.print("insertProcedureFile created : " + insertProcedureFile.getAbsolutePath());
        printStream.print("with content : " + FileUtils.readFileToString(insertProcedureFile));
    }
    String script = IOUtils.toString(getClass().getResourceAsStream(INSERT_ACT_NAME))
            .replace("$host", AsqatasunInstallation.get().getDatabaseHost())
            .replace("$user", AsqatasunInstallation.get().getDatabaseLogin())
            .replace("$port", AsqatasunInstallation.get().getDatabasePort())
            .replace("$passwd", AsqatasunInstallation.get().getDatabasePassword())
            .replace("$db", AsqatasunInstallation.get().getDatabaseName())
            .replace("$procedureFileName", TMP_FOLDER_NAME + SQL_PROCEDURE_SCRIPT_NAME);

    File insertActFile = AsqatasunRunnerBuilder.createTempFile(contextDir, INSERT_ACT_SCRIPT_NAME, script);

    ProcessBuilder pb = new ProcessBuilder(TMP_FOLDER_NAME + INSERT_ACT_SCRIPT_NAME,
            AsqatasunInstallation.get().getAsqatasunLogin(), projectName.replaceAll("'", QUOTES),
            scenarioName.replaceAll("'", QUOTES),
            AsqatasunRunnerBuilder.forceVersion1ToScenario(scenario.replaceAll("'", QUOTES)),
            asqatasunRunner.getAuditId());

    pb.directory(contextDir);
    pb.redirectErrorStream(true);

    Process p = pb.start();
    p.waitFor();

    FileUtils.forceDelete(insertActFile);
    FileUtils.forceDelete(insertProcedureFile);
}

From source file:com.sustainalytics.crawlerfilter.PDFTitleGeneration.java

/**
 * This method renames the given PDF/*from   w w w  .  ja v a  2  s.  c  om*/
 * @param file is a File object
 * @param finalTitle is a String
 */
public static void renameFile(File pdfFile, File textFile, String finalTitle) {
    String newTitle = pdfFile.getParentFile().getAbsolutePath() + "/" + finalTitle;
    File pdfFileWithTitle = new File(newTitle + ".pdf");
    File textFileWithTitle = new File(newTitle + ".txt");
    if (!pdfFileWithTitle.exists()) {
        logger.info("Renaming " + pdfFile.getName() + "-->" + pdfFileWithTitle.getName());
        logger.info("\n\n");
        pdfFile.renameTo(pdfFileWithTitle);
        textFile.renameTo(textFileWithTitle);
    } else {
        logger.info("Renaming failed. File " + pdfFileWithTitle + " already exists");
        try {
            logger.info("Deleting " + pdfFile.getName());
            FileUtils.forceDelete(pdfFile);
            FileUtils.forceDelete(textFile);
        } catch (IOException e) {
            logger.info(pdfFile.getName() + "could not be force deleted");
        }
    }
}

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

public void afterUpdate() throws ClientException, IOException {
    switch (action) {
    case UNKNOWN:
        // client did not set a conflict resolution
        log.error("DeleteWithModificationConflict with no action set: " + status.getPath());
        break;//from w  w w  . ja  v a2  s. co  m

    case DELETE:
        log.info("now deleting again " + status.getPath());

        // Delete file or directory -- works in all cases:
        // 1. Local container delete with remote updates:
        //    Update operation makes sure that the remote updates are
        //    adopted locally, re-creating the affected files if necessary.
        //    So they need to be deleted again. Commit deletes remote
        //    directory.
        //
        // 2. Remote container delete with local updates:
        //    Update operation deletes everything in the remotely deleted
        //    directory apart from files affected by local changes, which
        //    are left unversioned and need to be deleted locally.
        //
        // 3. Remotely modified file deleted locally:
        //    Update operation makes sure that the remote update is adopted
        //    locally, re-creating the affected file if necessary. Hence
        //    need to delete the local file again.
        //
        // 4. Locally modified file deleted remotely:
        //    Update operation leaves the affected file as unversioned which
        //    is therefore deleted.
        File file = new File(status.getPath());
        FileUtils.forceDelete(file);

        break;

    case ONLYKEEPMODIFIED:
        log.info("keeping added/modified from remote: " + status.getPath());

        if (localDelete) {
            // revert deletion status for local deletions
            client.revert(status.getPath(), true);
        } else {
            // only re-add files/directories that were added/modified
            client.add(status.getPath(), false);
            if (otherMods != null) {
                for (Status s : otherMods) {
                    client.add(s.getPath(), false);
                }
            }
        }

        break;

    case REVERTDELETE:
        if (localDelete == false) {
            log.info("reverting remote delete: " + status.getPath());
            // Revert remote deletes in three steps:
            // 1. Restore last revision before deletion (incl. history)
            // 2. Redo changes by replacing with local files
            // 3. Re-add locally added files

            // 1. Restore last revision before deletion (incl. history)
            File targetFile = new File(status.getPath());
            String parent = targetFile.getParent();
            Number restoreRev = null;
            String delFile = null;

            // Get all log messages since last update
            LogMessage[] logMessages = client.logMessages(parent, Revision.BASE, Revision.HEAD, false, true);

            // need to translate svn URLs from ChangePath to wc paths, so we
            // have to find out about the working copy root to see what the
            // URL prefix of the checkout is
            File wcDir = new File(status.getPath());
            if (tempCopy.isFile()) {
                wcDir = wcDir.getParentFile();
            }
            File wcRoot = SVNAdminDirectoryLocator.findWCRoot(wcDir);
            Info info = client.info(wcRoot.getPath());

            // eg. http://svn.server.com/team1/trunk/my%20path
            String wcRootURL = info.getUrl();
            // eg. http://svn.server.com/team1
            String repoRootURL = info.getRepository();
            // eg. /trunk/my%20path
            String checkoutPrefixURL = wcRootURL.substring(repoRootURL.length());
            // eg. /trunk/my path
            String checkoutPrefix = SVNEncodingUtil.uriDecode(checkoutPrefixURL);

            // eg. /home/peter/checkout/team1
            String wcRootPath = wcRoot.getPath();
            // eg. /home/peter/checkout/team1/dir/file.txt
            String currentPath = status.getPath();
            // eg. /dir/file.txt (the one to look for in the ChangePaths below)
            String relativePath = currentPath.substring(wcRootPath.length());

            // Look for revision in which the file/dir was (last) deleted
            for (LogMessage logMessage : logMessages) {
                for (ChangePath changePath : logMessage.getChangedPaths()) {

                    // eg. /trunk/my path/dir/file.txt
                    String cp = changePath.getPath();
                    // eg. /dir/file.txt
                    String relativeChangePath = cp.substring(checkoutPrefix.length());

                    if (relativePath.equals(relativeChangePath) && changePath.getAction() == 'D') {
                        // want to restore last revision before deletion
                        restoreRev = new Number(logMessage.getRevision().getNumber() - 1);
                        delFile = cp;
                        log.debug("found revision of deletion: '" + changePath.getPath()
                                + "' was deleted in revision " + logMessage.getRevision().toString());
                    }
                }
            }

            // Restore deleted version with version history
            if (restoreRev != null) {
                log.debug("copy " + repoRootURL + delFile + " to " + status.getPath() + ", restoreRev "
                        + restoreRev);

                client.copy(repoRootURL + delFile, status.getPath(), null, restoreRev);
            } else {
                log.error("Failed to restore deleted version of " + status.getPath());
            }

            // 2. Redo changes by replacing with local files (move B => A)
            File destination = new File(status.getPath());
            if (tempCopy.isFile()) {
                log.debug("copy file from " + tempCopy + " to " + destination);
                FileUtils.copyFile(tempCopy, destination);
                tempCopy.delete();
            } else {
                log.debug("copy dir from " + tempCopy + " to " + destination);
                FileUtils.copyDirectory(tempCopy, destination);
                FileUtils.deleteDirectory(tempCopy);
            }

            // 3. Re-add locally added files
            // Cannot just add directories recursively since the copy
            // operation above automatically adds them and adding them twice
            // results in an error. So just add files that were added
            // locally.
            if (otherMods != null) {
                for (Status s : otherMods) {
                    if (s.getTextStatus() == StatusKind.added) {
                        log.debug("re-adding " + s.getPath());
                        client.add(s.getPath(), false);
                    }
                }
            }
        }

        break;
    }
}

From source file:eu.openanalytics.rsb.component.AdminResource.java

@Path("/" + SYSTEM_SUBPATH + "/r_packages")
@POST/*from  w ww  .  ja va2  s  . co  m*/
@Consumes({ Constants.GZIP_CONTENT_TYPE })
public void installRPackage(@QueryParam("rServiPoolUri") final String rServiPoolUri,
        @QueryParam("sha1hexsum") final String sha1HexSum, @QueryParam("packageName") final String packageName,
        final InputStream input) throws Exception {
    Validate.notBlank(rServiPoolUri, "missing query param: rServiPoolUri");
    Validate.notBlank(sha1HexSum, "missing query param: sha1hexsum");

    // store the package and tar files in temporary files
    final File tempDirectory = new File(FileUtils.getTempDirectory(), UUID.randomUUID().toString());
    FileUtils.forceMkdir(tempDirectory);

    final File packageSourceFile = new File(tempDirectory, packageName);

    try {
        final FileOutputStream output = new FileOutputStream(packageSourceFile);
        IOUtils.copyLarge(input, output);
        IOUtils.closeQuietly(output);

        // validate the checksum
        final FileInputStream packageSourceInputStream = new FileInputStream(packageSourceFile);
        final String calculatedSha1HexSum = DigestUtils.sha1Hex(packageSourceInputStream);
        IOUtils.closeQuietly(packageSourceInputStream);
        Validate.isTrue(calculatedSha1HexSum.equals(sha1HexSum), "Invalid SHA-1 HEX checksum");

        // upload to RServi
        rServiPackageManager.install(packageSourceFile, rServiPoolUri);

        // extract catalog files from $PKG_ROOT/inst/rsb/catalog
        extractCatalogFiles(packageSourceFile);

        getLogger().info("Package with checksum " + sha1HexSum + " installed to " + rServiPoolUri);
    } finally {
        try {
            FileUtils.forceDelete(tempDirectory);
        } catch (final Exception e) {
            getLogger().warn("Failed to delete temporary directory: " + tempDirectory, e);
        }
    }
}

From source file:atg.tools.dynunit.util.ComponentUtil.java

private static void recreateFile(@Nullable final File file) throws IOException {
    logger.entry(file);//from w w  w.j  ava 2s.co m
    if (file != null) {
        if (file.exists()) {
            FileUtils.forceDelete(file);
        }
        if (!file.createNewFile()) {
            throw logger.throwing(new IOException("File already exists but can't be deleted."));
        }
    }
    logger.exit();
}