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.lmxm.ute.executers.tasks.FileSystemDeleteTaskExecuter.java

/**
 * Force delete./*from w w w  .jav a 2  s.  c  o  m*/
 *
 * @param pathFile    the path file
 * @param stopOnError the stop on error
 * @return true, if successful
 */
protected boolean forceDelete(final File pathFile, final boolean stopOnError) {
    final String prefix = "forceDelete() :";

    boolean successful = false;

    try {
        FileUtils.forceDelete(pathFile);

        successful = true;
    } catch (final FileNotFoundException e) {
        if (stopOnError) {
            LOGGER.error(prefix + " file not found " + pathFile.getName(), e);
            StatusChangeEventBus.error(FILE_DELETE_FILE_DOES_NOT_EXIST_ERROR, getJob(),
                    pathFile.getAbsolutePath());
            throw new TaskExecuterException(ExceptionResourceType.FILE_NOT_FOUND, e,
                    pathFile.getAbsoluteFile());
        } else {
            LOGGER.debug("{} ignoring error deleting file", prefix);
            StatusChangeEventBus.info(FILE_DELETE_FILE_DOES_NOT_EXIST_ERROR, getJob(),
                    pathFile.getAbsolutePath());
        }
    } catch (final IOException e) {
        if (stopOnError) {
            LOGGER.error(prefix + " error deleting file " + pathFile.getName(), e);
            StatusChangeEventBus.error(FILE_DELETE_ERROR, getJob(), pathFile.getAbsolutePath());
            throw new TaskExecuterException(ExceptionResourceType.FILE_DELETE_ERROR, e,
                    pathFile.getAbsoluteFile());
        } else {
            LOGGER.debug("{} ignoring error deleting file", prefix);
            StatusChangeEventBus.info(FILE_DELETE_ERROR, getJob(), pathFile.getAbsolutePath());
        }
    }

    return successful;
}

From source file:info.donsun.cache.filecache.FileCache.java

@Override
public List<Object> keys() throws CacheException {
    synchronized (LOCK) {
        List<Object> keys = new ArrayList<Object>();
        for (String fileName : listFileNames()) {
            try {
                File file = FileUtils.getFile(config.getDir(), fileName);

                if (!file.exists()) {
                    continue;
                }/*from  w w  w.ja v  a 2 s .  c o m*/

                FileInputStream fileStream = new FileInputStream(file);
                ObjectInputStream in = new ObjectInputStream(fileStream);
                boolean isExpire = false;
                try {

                    CachedObject cachedObject = (CachedObject) in.readObject();
                    // 
                    if (cachedObject.getExpire() > 0 && cachedObject.getExpire() < System.currentTimeMillis()) {
                        isExpire = true;
                        continue;
                    }

                    keys.add(cachedObject.getKey());
                } finally {
                    in.close();
                    fileStream.close();
                    if (isExpire) {
                        FileUtils.forceDelete(file);
                    }
                }
            } catch (Exception e) {
                throw new CacheException("Get cache file fail.", e);
            }

        }

        return keys;

    }
}

From source file:com.universal.storage.UniversalFileStorage.java

/**
 * This method removes a file from the storage.  This method will use the path parameter 
 * to localte the file and remove it from the storage.
 * /*  w w  w  .  j  a v  a2s .co m*/
 * Root = /storage/
 * path = myfile.txt
 * Target = /storage/myfile.txt
 * 
 * Root = /storage/
 * path = myfolder/myfile.txt
 * Target = /storage/myfolder/myfile.txt 
 * 
 * @param path is the file's path within the storage.  
 * @throws UniversalIOException when a specific IO error occurs.
 */
void removeFile(String path) throws UniversalIOException {
    PathValidator.validatePath(path);

    validateRoot(this.settings);

    File file = new File(this.settings.getRoot() + path);

    if (file.isDirectory()) {
        UniversalIOException error = new UniversalIOException(
                file.getName() + " is a folder.  You should call the removeFolder method.");
        this.triggerOnErrorListeners(error);
        throw error;
    }

    try {
        this.triggerOnRemoveFileListeners();
        FileUtils.forceDelete(file);
        this.triggerOnFileRemovedListeners();
    } catch (Exception e) {
        UniversalIOException error = new UniversalIOException(e.getMessage());
        this.triggerOnErrorListeners(error);
        throw error;
    }
}

From source file:net.sourceforge.jweb.maven.mojo.InWarMinifyMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    if (disabled)
        return;/*from   w  w w .ja  va 2  s.c o m*/
    processConfiguration();
    String name = this.getBuilddir().getAbsolutePath() + File.separator + this.getFinalName() + "."
            + this.getPacking();
    this.getLog().info(name);
    MinifyFileFilter fileFilter = new MinifyFileFilter();
    int counter = 0;
    try {
        File finalWarFile = new File(name);
        File tempFile = File.createTempFile(finalWarFile.getName(), null);
        tempFile.delete();//check deletion
        boolean renameOk = finalWarFile.renameTo(tempFile);
        if (!renameOk) {
            getLog().error("Can not rename file, please check.");
        }

        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(finalWarFile));
        ZipFile zipFile = new ZipFile(tempFile);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            //no compress, just transfer to war
            if (!fileFilter.accept(entry)) {
                getLog().debug("nocompress entry: " + entry.getName());
                out.putNextEntry(entry);
                InputStream inputStream = zipFile.getInputStream(entry);
                byte[] buf = new byte[512];
                int len = -1;
                while ((len = inputStream.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                inputStream.close();
                continue;
            }

            File sourceTmp = new File(FileUtils.getUserDirectoryPath() + File.separator + ".mvntmp"
                    + File.separator + counter + ".tmp");
            File destTmp = new File(FileUtils.getUserDirectoryPath() + File.separator + ".mvntmp"
                    + File.separator + counter + ".min.tmp");
            FileUtils.writeStringToFile(sourceTmp, "");
            FileUtils.writeStringToFile(destTmp, "");

            //assemble arguments
            String[] provied = getYuiArguments();
            int length = (provied == null ? 0 : provied.length);
            length += 5;
            int i = 0;

            String[] ret = new String[length];

            ret[i++] = "--type";
            ret[i++] = (entry.getName().toLowerCase().endsWith(".css") ? "css" : "js");

            if (provied != null) {
                for (String s : provied) {
                    ret[i++] = s;
                }
            }

            ret[i++] = sourceTmp.getAbsolutePath();
            ret[i++] = "-o";
            ret[i++] = destTmp.getAbsolutePath();

            try {
                InputStream in = zipFile.getInputStream(entry);
                FileUtils.copyInputStreamToFile(in, sourceTmp);
                in.close();

                YUICompressorNoExit.main(ret);
            } catch (Exception e) {
                this.getLog().warn("compress error, this file will not be compressed:" + buildStack(e));
                FileUtils.copyFile(sourceTmp, destTmp);
            }

            out.putNextEntry(new ZipEntry(entry.getName()));
            InputStream compressedIn = new FileInputStream(destTmp);
            byte[] buf = new byte[512];
            int len = -1;
            while ((len = compressedIn.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            compressedIn.close();

            String sourceSize = decimalFormat.format(sourceTmp.length() * 1.0d / 1024) + " KB";
            String destSize = decimalFormat.format(destTmp.length() * 1.0d / 1024) + " KB";
            getLog().info("compressed entry:" + entry.getName() + " [" + sourceSize + " ->" + destSize + "/"
                    + numberFormat.format(1 - destTmp.length() * 1.0d / sourceTmp.length()) + "]");

            counter++;
        }
        zipFile.close();
        out.close();

        FileUtils.cleanDirectory(new File(FileUtils.getUserDirectoryPath() + File.separator + ".mvntmp"));
        FileUtils.forceDelete(new File(FileUtils.getUserDirectoryPath() + File.separator + ".mvntmp"));
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:fr.inria.atlanmod.neo4emf.neo4jresolver.runtimes.internal.Neo4JRuntimesManager.java

public void uninstall(String id) throws IOException {
    INeo4jRuntime runtime = getRuntime(id);
    try {/*  w w w . j  av a2 s.c om*/
        FileUtils.forceDelete(runtime.getPath().toFile());
    } catch (FileNotFoundException e) {
    }
    load();
}

From source file:algorithm.OpenStegoRandomLSBSteganography.java

@Override
public File encapsulate(File carrier, List<File> payloadList) throws IOException {
    String cover = getCover(carrier);
    String message = getPayload(carrier, payloadList.get(0));
    String output = getOutputFileName(carrier);
    if (trueCompressionButton.isSelected()) {
        encapsulateAndCompress(cover, message, output);
    } else {/*from   w w w  .  j  ava  2 s.  c  om*/
        encapsulate(cover, message, output);
    }
    FileUtils.forceDelete(new File(message));// tmp
    File outputFile = new File(output);
    if (outputFile.isFile()) {
        return outputFile;
    }
    return null;
}

From source file:com.collective.celos.ci.mode.test.TestRun.java

private void doCleanup() throws Exception {
    if (testCaseTempDir.exists()) {
        FileUtils.forceDelete(testCaseTempDir);
    }/*from w  w w  .j a  v  a  2 s .c om*/
    for (FixtureDeployer fixtureDeployer : testCase.getInputs()) {
        fixtureDeployer.undeploy(this);
    }
    ciContext.getFileSystem().delete(new org.apache.hadoop.fs.Path(ciContext.getHdfsPrefix()), true);
}

From source file:com.huawei.streaming.storm.KerberosSecurity.java

/**
 * jaas//  www .ja  v  a 2  s  .c  o  m
 *
 * @throws StreamingException 
 */
private void deleteJaasFile() throws StreamingException {
    try {
        String tmpDir = new File(conf.getStringValue(StreamingConfig.STREAMING_TEMPLATE_DIRECTORY))
                .getCanonicalPath();
        File file = new File(jaasPath).getCanonicalFile();
        if (!file.getPath().startsWith(tmpDir)) {
            LOG.error("Invalid jaas path, not in config tmp path.");
            throw new StreamingException(ErrorCode.SECURITY_INNER_ERROR);
        }

        if (file.isFile()) {
            FileUtils.forceDelete(new File(jaasPath));
        }

    } catch (IOException e) {
        LOG.error("Failed to delete jaas file.");
        throw new StreamingException(ErrorCode.UNKNOWN_SERVER_COMMON_ERROR);
    } catch (SecurityException e1) {
        StreamingException exception = new StreamingException(ErrorCode.SECURITY_INNER_ERROR);
        LOG.error("Failed to get canonical pathname for cannot be accessed.", exception);
        throw exception;
    }
}

From source file:hoot.services.controllers.info.ReportsResourceTest.java

@Test
@Category(UnitTest.class)
public void testGetReportFile() throws Exception {
    String storePath = _rps._homeFolder + "/" + _rps._rptStorePath;
    File f = new File(storePath);
    File fWks = new File(storePath + "/123_test_file");
    if (fWks.exists()) {
        FileUtils.forceDelete(fWks);
    }/*from   ww  w  .  j a v  a2  s .com*/
    FileUtils.forceMkdir(f);

    FileUtils.forceMkdir(fWks);
    String currTime = "" + System.currentTimeMillis();
    JSONObject metaData = new JSONObject();
    metaData.put("name", "Test Report1");
    metaData.put("description", "This is test report 1");
    metaData.put("created", currTime);
    metaData.put("reportpath", _rps._homeFolder + "/test-files/test_report1.pdf");
    File meta = new File(storePath + "/123_test_file/meta.data");
    FileUtils.write(meta, metaData.toJSONString());

    File fout = _rps._getReportFile("123_test_file");

    assertNotNull(fout);

    fout = _rps._getReportFile("123_test_file_not_there");

    assertNull(fout);

    FileUtils.forceDelete(fWks);
}

From source file:net.nicholaswilliams.java.licensing.TestFileLicenseProvider.java

@Test
public void testGetLicenseFile03() throws IOException {
    URL url = this.getClass().getClassLoader().getResource("");
    assertNotNull("The URL should not be null.", url);

    File temp;/* w  w w . j  a  v  a  2  s  .c  o  m*/
    try {
        temp = new File(url.toURI());
    } catch (URISyntaxException e) {
        temp = new File(url.getPath());
    }

    temp = new File(temp, "net/nicholaswilliams/java/licensing/testGetLicenseFile03.lic");

    FileUtils.writeStringToFile(temp, "temp");

    this.provider.setFilePrefix("net/nicholaswilliams/java/licensing/");
    this.provider.setFileSuffix(".lic");
    this.provider.setFileOnClasspath(true);
    File file = this.provider.getLicenseFile("testGetLicenseFile03");

    assertNotNull("The file should not null.", file);
    assertEquals("The file name is not correct.", temp.getPath(), file.getPath());

    FileUtils.forceDelete(temp);
}