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:hoot.services.controllers.ingest.FileUploadResourceTest.java

@Test(expected = Exception.class)
@Category(UnitTest.class)
public void TestBuildNativeRequestFgdbOsm() throws Exception {
    String input = "fgdb_osm.zip";
    String jobId = "test-id-123";
    String wkdirpath = homeFolder + "/upload/" + jobId;
    File workingDir = new File(wkdirpath);
    FileUtils.forceMkdir(workingDir);//  w w  w  .jav a 2 s.  c  om
    org.junit.Assert.assertTrue(workingDir.exists());

    File srcFile = new File(homeFolder + "/test-files/service/FileUploadResourceTest/" + input);
    File destFile = new File(wkdirpath + "/" + input);
    FileUtils.copyFile(srcFile, destFile);
    org.junit.Assert.assertTrue(destFile.exists());

    FileUploadResource res = new FileUploadResource();

    // Let's test zip
    JSONArray results = new JSONArray();
    JSONObject zipStat = new JSONObject();

    try {
        res._buildNativeRequest(jobId, "fgdb_osm", "zip", input, results, zipStat);
    } catch (Exception ex) {
        org.junit.Assert.assertTrue(ex.getMessage().equals("Zip should not contain both osm and ogr types."));
        throw ex;
    }

    FileUtils.forceDelete(workingDir);
}

From source file:com.zaba37.easyreader.actions.menuBar.ImageBackgroundLoader.java

private String createWindowsDirecotry(String mainPath) {
    mainPath = mainPath.substring(0, mainPath.lastIndexOf("/"));
    mainPath = mainPath + "/TmpEasyReaderImageDirectory";
    File file = new File(mainPath);

    try {/*from  w w w  .ja v  a2  s .  c  o m*/
        if (file.exists()) {
            FileUtils.forceDelete(file);
        }

        FileUtils.forceMkdir(file);

        Files.setAttribute(file.toPath(), "dos:hidden", true);

    } catch (IOException ex) {
        Logger.getLogger(ImageBackgroundLoader.class.getName()).log(Level.SEVERE, null, ex);
    }

    return file.getPath();
}

From source file:com.textocat.textokit.corpus.statistics.dao.corpus.XmiFileTreeCorpusDAO.java

@Override
public void persist(URI docUri, String annotatorId, CAS cas) throws IOException, SAXException {
    File annotatorDir = annotatorIdToDir(annotatorId);
    forceMkdir(annotatorDir);//  w  w w  . ja  v a  2 s  .c  o m
    File docFile = new File(annotatorDir, getDocumentFilename(docUri));
    try {
        serializeCAS(cas, docFile);
    } catch (IOException ex) {
        // clean
        FileUtils.forceDelete(docFile);
        throw ex;
    } catch (SAXException ex) {
        // clean
        FileUtils.forceDelete(docFile);
        throw ex;
    }
    // update in-memory state
    fileByURIandAnnotatorId.put(new UriAnnotatorPair(docUri, annotatorId), docFile);
    annotatorsByDocument.put(docUri, annotatorId);
}

From source file:de.xirp.managers.DeleteManager.java

/**
 * Stops the manager, deletes all files which are registered to be
 * deleted on shutdown and writes the the file with the list of
 * files which should be deleted on next startup.<br/><br/>If
 * the manager fails to delete a file on shutdown, it tries to
 * delete the file on next startup./*from  ww w.j a  v a  2 s.c  o m*/
 * 
 * @see de.xirp.managers.AbstractManager#stop()
 */
@Override
protected void stop() throws ManagerException {
    super.stop();
    Properties props = new Properties();
    int cnt = 0;
    for (String path : deleteOnShutdown) {
        try {
            FileUtils.forceDelete(new File(path));
        } catch (IOException e) {
            props.put("File_" + cnt++, path); //$NON-NLS-1$
        }
    }
    File f = new File(Constants.TO_DELETE_FILE);
    if (!f.exists()) {
        try {
            f.createNewFile();
        } catch (IOException e) {
            // do nothing, cause we can't to anything in this case
        }
    }

    for (String path : deleteOnStartup) {
        props.put("File_" + cnt++, path); //$NON-NLS-1$
    }
    try {
        FileWriter w = new FileWriter(f);
        props.store(w, "Files to delete on startup"); //$NON-NLS-1$
    } catch (IOException e) {
        logClass.error("Error: " + e.getMessage() + Constants.LINE_SEPARATOR, e); //$NON-NLS-1$
    }
}

From source file:com.temenos.interaction.loader.classloader.CachingParentLastURLClassloaderFactory.java

private void cleanupClassloaderResources(URLClassLoader previousCL, File previousTempDir) {
    try {//from   www.j a  v  a 2  s.  c  om
        if (previousCL != null) {
            previousCL.close();
        }
    } catch (IOException ex) {
        LOGGER.error("Failed to close classloader - potential resource and memory leak!", ex);
    }
    try {
        if (previousTempDir != null) {
            FileUtils.forceDelete(previousTempDir);
        }
    } catch (IOException ex) {
        LOGGER.error("Failed to delete temporary directory, possible resource leak!", ex);
    }
}

From source file:com.github.ipaas.ideploy.agent.handler.RollbackCodeHandlerTest.java

/**
 * , USING_VERSION,? ROLLBACKTO_VERSION 
 * /*  ww  w .  ja v a 2 s.c o m*/
 * @throws Exception
 */
@Test
public void rollbackCodeTest() throws Exception {
    String deployRoot = "/www/app" + APP_NAME;

    File usingfile = new File(deployRoot);

    RollbackCodeHandler rollback = new RollbackCodeHandler();

    String localBkPath = "/www/appbk" + APP_NAME + "/firstVer0";
    Map<String, Object> cantRollBackParams = new HashMap<String, Object>();
    cantRollBackParams.put("localBkPath", localBkPath);
    cantRollBackParams.put("deployPath", deployRoot);
    try {
        rollback.execute(null, null, cantRollBackParams, null); // :
        // ,?,?!
        fail("Created fraction 1/0! That's undefined!");
    } catch (Exception e) {
        assertEquals("?,?!", e.getMessage());
    }
    File localBkFile = new File(localBkPath);
    if (!localBkFile.exists()) {
        localBkFile.mkdirs();
    }
    rollback.execute(null, null, cantRollBackParams, null);

    Integer hostStatus4New = 1;
    String savePath = "/www/apptemp/" + USING_VERSION;
    Map<String, Object> firstRollbackParams = new HashMap<String, Object>();
    firstRollbackParams.put("usingCodeVerPath", TEST_GROUP + TAGS + "/" + USING_VERSION);
    firstRollbackParams.put("hostStatus", hostStatus4New);
    firstRollbackParams.put("savePath", savePath);
    firstRollbackParams.put("deployPath", deployRoot);
    rollback.execute(null, null, firstRollbackParams, null); // ,,?

    DownloadCodeHandler downLoadHandler = new DownloadCodeHandler();
    Integer notUpdateAll = 2;
    Integer hostStatus4Old = 2;
    Map<String, Object> secondDownLoadParams = new HashMap<String, Object>();
    secondDownLoadParams.put("doingCodeVerPath", TEST_GROUP + TAGS + "/" + ROLLBACKTO_VERSION);
    secondDownLoadParams.put("usingCodeVerPath", TEST_GROUP + TAGS + "/" + USING_VERSION);
    secondDownLoadParams.put("hostStatus", hostStatus4Old);
    secondDownLoadParams.put("savePath", "/www/apptemp/rollback_test_vaild");// ??
    secondDownLoadParams.put("updateAll", notUpdateAll);
    downLoadHandler.execute(null, null, secondDownLoadParams, null);
    File updateFile = new File("/www/apptemp/rollback_test_vaild/update.txt");
    List<String> updateList = FileUtils.readLines(updateFile);// ??,?

    String savePath2 = "/www/apptemp/" + ROLLBACKTO_VERSION;
    Map<String, Object> secondRollbackParams = new HashMap<String, Object>();
    secondRollbackParams.put("usingCodeVerPath", TEST_GROUP + TAGS + "/" + ROLLBACKTO_VERSION);
    secondRollbackParams.put("doingCodeVerPath", TEST_GROUP + TAGS + "/" + USING_VERSION);
    secondRollbackParams.put("hostStatus", hostStatus4Old);
    secondRollbackParams.put("savePath", savePath2);
    secondRollbackParams.put("deployPath", deployRoot);
    rollback.execute(null, null, secondRollbackParams, null); // ,

    // ?
    for (String str : updateList) {
        if (str.startsWith("+")) {
            // 
            Assert.assertTrue(new File(deployRoot + StringUtils.removeStart(str, "+").trim()).exists());
        } else if (str.startsWith("-")) {
            // 
            String f = deployRoot + StringUtils.removeStart(str, "-").trim();
            Assert.assertFalse(new File(f).exists());
        }
    }

    FileUtils.cleanDirectory(usingfile);
    FileUtils.forceDelete(localBkFile);
    FileUtils.cleanDirectory(new File("/www/apptemp"));
}

From source file:ml.shifu.shifu.core.processor.ManageModelProcessor.java

/**
 * switch to different model/*from w  w w.  j a  v  a2s . co  m*/
 *
 * @param modelName
 * @throws IOException
 */
private void switchModel(String modelName) throws IOException {
    //get current branch
    String currentModelName = null;
    try {
        currentModelName = getCurrentModelName();
    } catch (IOException e) {
        log.info("Could not get the current model name");
        currentModelName = "master";
    }

    //log.info("The current model will backup to {} folder", currentModelName);

    //first, backup to currentModelName
    saveModel(currentModelName);

    //is it new ?
    File thisModel = new File(Constants.BACKUPNAME + File.separator + modelName);
    if (!thisModel.exists()) {
        //no exist

    } else {
        //exist
        //copy files
        File modelFile = new File(String.format("%s/%s/ModelConfig.json", Constants.BACKUPNAME, modelName));
        File columnFile = new File(String.format("%s/%s/ModelConfig.json", Constants.BACKUPNAME, modelName));
        File workspace = new File("./");

        try {
            FileUtils.copyFileToDirectory(modelFile, workspace);
            if (columnFile.exists()) {
                FileUtils.copyFileToDirectory(columnFile, workspace);
            }
        } catch (IOException e) {
            //TODO
            e.printStackTrace();
        }

        //copy models
        File sourceModelFolder = new File(String.format("./%s/%s/models/", Constants.BACKUPNAME, modelName));
        File workspaceFolder = new File("./models");
        if (sourceModelFolder.isDirectory()) {
            File[] files = sourceModelFolder.listFiles(new FileFilter() {
                @Override
                public boolean accept(File file) {
                    return file.isFile() && file.getName().startsWith("model");
                }
            });

            if (files != null) {
                for (File model : files) {
                    try {
                        FileUtils.copyFileToDirectory(model, workspaceFolder);
                    } catch (IOException e) {
                        log.info("Fail to copy models file");
                    }
                }
            } else {
                throw new IOException(
                        String.format("Failed to list files in %s", sourceModelFolder.getAbsolutePath()));
            }
        } else {
            log.error("{} does not exist or is not a directory!", sourceModelFolder.getAbsoluteFile());
        }

    }

    File file = new File("./.HEAD");
    BufferedWriter writer = null;
    try {
        FileUtils.forceDelete(file);
        writer = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(file), Constants.DEFAULT_CHARSET));
        writer.write(modelName);
    } catch (IOException e) {
        log.info("Fail to rewrite HEAD file");
    } finally {
        if (writer != null) {
            writer.close();
        }
    }

    log.info("Switch model: {} successfully", modelName);
}

From source file:com.blackducksoftware.tools.scmconnector.integrations.ftp.FTPConnector.java

private void deleteFileInTargetDirectoryNotExistingInSource(File dir, FTPFile[] list) throws IOException {
    File[] children = dir.listFiles();

    for (File element : children) {
        boolean found = false;

        for (FTPFile element2 : list) {
            if (element2.getName().equals(element)) {
                found = true;//from   w ww .j a  va 2 s. c  o m
            }

        }

        if (!found) {
            log.info("Deleting local file/folder " + element.getAbsolutePath()
                    + " because does not exist anymore in repository");
            FileUtils.forceDelete(element);
        }
    }

}

From source file:hoot.services.utils.MultipartSerializerTest.java

@Ignore
@Test/*  w w  w  .  j  a v  a2  s.  c  om*/
@Category(UnitTest.class)
public void TestserializeUploadedFiles() throws Exception {
    // homeFolder + "/upload/" + jobId + "/" + relPath;
    // Create dummy FGDB

    String jobId = "123-456-789-testosm";
    String wkdirpath = HOME_FOLDER + "/upload/" + jobId;
    File workingDir = new File(wkdirpath);
    FileUtils.forceMkdir(workingDir);
    Assert.assertTrue(workingDir.exists());

    FileItemFactory factory = new DiskFileItemFactory(16, null);
    String textFieldName = "textField";

    FileItem item = factory.createItem(textFieldName, "application/octet-stream", true, "dummy1.osm");

    String textFieldValue = "0123456789";
    byte[] testFieldValueBytes = textFieldValue.getBytes();

    try (OutputStream os = item.getOutputStream()) {
        os.write(testFieldValueBytes);
    }

    File out = new File(wkdirpath + "/buffer.tmp");
    item.write(out);

    List<FileItem> fileItemsList = new ArrayList<>();
    fileItemsList.add(item);
    Assert.assertTrue(out.exists());

    Map<String, String> uploadedFiles = new HashMap<>();
    Map<String, String> uploadedFilesPaths = new HashMap<>();

    //        MultipartSerializer.serializeUploadedFiles(fileItemsList, uploadedFiles, uploadedFilesPaths, wkdirpath);

    Assert.assertEquals("OSM", uploadedFiles.get("dummy1"));
    Assert.assertEquals("dummy1.osm", uploadedFilesPaths.get("dummy1"));

    File content = new File(wkdirpath + "/dummy1.osm");
    Assert.assertTrue(content.exists());

    FileUtils.forceDelete(workingDir);
}

From source file:com.ss.language.model.gibblda.LDADataset.java

private static void readFromDatabase(int total, LDADataset data) throws IOException {
    // ?id/*from   w  w w.  j  av  a 2  s .co  m*/
    File docIdxFile = new File(LDACmdOption.curOption.get().dir, LDACmdOption.curOption.get().docIdFile);
    if (docIdxFile.isFile()) {
        FileUtils.forceDelete(docIdxFile);
    }
    if (!docIdxFile.getParentFile().isDirectory()) {
        FileUtils.forceMkdir(docIdxFile.getParentFile());
    }
    docIdxFile.createNewFile();
    BufferedWriter br = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docIdxFile),
            LDACmdOption.curOption.get().fileEncoding));
    int perPage = 100;
    int totalPage = (total / perPage) + (total % perPage == 0 ? 0 : 1);
    int index = -1;
    for (int curPage = 0; curPage < totalPage; ++curPage) {
        // ?
        String titleSql = "select document_title,document_content from " + tableName
                + " order by rec_id asc limit " + (curPage * perPage) + "," + perPage;
        List<Map<String, Object>> result = DatabaseConfig.query(titleSql);
        if (result == null || result.isEmpty()) {
            break;
        }
        for (Map<String, Object> record : result) {
            String title = (String) record.get("document_title");
            String content = (String) record.get("document_content");
            if (content == null || content.trim().isEmpty()) {
                continue;
            }
            ++index;
            System.out.println("??" + (curPage + 1) + "" + (index + 1)
                    + "?/" + total + "?");
            data.setDoc(content, index);
            br.write(title + IOUtils.LINE_SEPARATOR);
        }
    }
    br.flush();
    br.close();
}