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:com.taobao.android.builder.tasks.app.databinding.DataBindingRenameTask.java

/**
 * ?so/* w w  w  .  j  a v a 2  s.c  om*/
 */
@TaskAction
void createAwbPackages() throws ExecutionException, InterruptedException {

    AtlasDependencyTree atlasDependencyTree = AtlasBuildContext.androidDependencyTrees.get(getVariantName());

    if (null == atlasDependencyTree) {
        return;
    }

    ExecutorServicesHelper executorServicesHelper = new ExecutorServicesHelper(taskName, getLogger(), 0);
    List<Runnable> runnables = new ArrayList<>();

    for (final AwbBundle awbBundle : atlasDependencyTree.getAwbBundles()) {

        runnables.add(new Runnable() {
            @Override
            public void run() {

                try {

                    File dataBindingClazzFolder = appVariantOutputContext.getVariantContext()
                            .getJAwbavaOutputDir(awbBundle);
                    String packageName = ManifestFileUtils
                            .getPackage(ManifestHelper.getOrgManifestFile(awbBundle.getAndroidLibrary()));
                    String appName = appVariantContext.getVariantConfiguration().getOriginalApplicationId();

                    //?
                    File dataMapperClazz = new File(dataBindingClazzFolder,
                            "android/databinding/DataBinderMapper.class");
                    if (!dataMapperClazz.exists()) {
                        throw new GradleException("missing datamapper class");
                    }

                    FileInputStream fileInputStream = new FileInputStream(dataMapperClazz);
                    ClassReader in1 = new ClassReader(fileInputStream);
                    ClassWriter cw = new ClassWriter(0);

                    Map<String, String> reMapping = new HashMap();
                    reMapping.put(appName.replace(".", "/") + "/BR", packageName.replace(".", "/") + "/BR");
                    RemappingClassAdapter remappingClassAdapter = new RemappingClassAdapter(cw,
                            new SimpleRemapper(reMapping));
                    in1.accept(remappingClassAdapter, 8);

                    ClassReader in2 = new ClassReader(cw.toByteArray());
                    ClassWriter cw2 = new ClassWriter(0);
                    Set<String> renames = new HashSet<String>();
                    renames.add("android/databinding/DataBinderMapper");
                    in2.accept(
                            new ClassRenamer(cw2, renames, packageName.replace(".", "/") + "/DataBinderMapper"),
                            8);

                    File destClass = new File(dataBindingClazzFolder,
                            packageName.replace(".", "/") + "/DataBinderMapper.class");
                    destClass.getParentFile().mkdirs();
                    FileOutputStream fileOutputStream = new FileOutputStream(destClass);
                    fileOutputStream.write(cw2.toByteArray());
                    IOUtils.closeQuietly(fileOutputStream);
                    IOUtils.closeQuietly(fileInputStream);

                    FileUtils.deleteDirectory(new File(dataBindingClazzFolder, "android/databinding"));
                    FileUtils.deleteDirectory(new File(dataBindingClazzFolder, "com/android/databinding"));

                    File appDir = new File(dataBindingClazzFolder, appName.replace(".", "/"));
                    if (appDir.exists()) {

                        File[] files = appDir.listFiles(new FileFilter() {
                            @Override
                            public boolean accept(File pathname) {
                                return pathname.isFile() && !pathname.isDirectory();
                            }
                        });

                        for (File tmp : files) {
                            FileUtils.forceDelete(tmp);
                        }

                    }

                } catch (Throwable e) {
                    e.printStackTrace();
                    throw new GradleException("package awb failed");
                }

            }
        });

    }

    executorServicesHelper.execute(runnables);

}

From source file:com.ephesoft.dcma.fuzzydb.FuzzyLuceneEngine.java

public void deleteIndexes(final String fuzzyIndexFolder, final String batchClassId) {
    File oldIndexes = new File(fuzzyIndexFolder);
    if (oldIndexes.exists()) {
        try {/*  w w  w  .  ja v a 2s.c o  m*/
            FileUtils.forceDelete(oldIndexes);
        } catch (IOException e) {
            LOGGER.error("Problem deleting fuzzy DB indexes for batch class : " + batchClassId, e);
        }
    } else {
        LOGGER.info("Fuzzy Db index folder does not exist");
    }
}

From source file:hoot.services.controllers.ingest.FileUploadResourceTest.java

@Test
@Category(UnitTest.class)
public void TestCreateNativeRequestOgrZip() throws Exception {
    String input = "ogr.zip";
    String jobId = "test-id-123";
    String wkdirpath = homeFolder + "/upload/" + jobId;
    File workingDir = new File(wkdirpath);
    FileUtils.forceMkdir(workingDir);//from w  w w.  j  a  v  a2  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();
    List<String> inputsList = new ArrayList<String>();
    inputsList.add(input);

    res._buildNativeRequest(jobId, "ogr", "zip", input, results, zipStat);

    int shpCnt = 0;
    int osmCnt = 0;
    int fgdbCnt = 0;

    int zipCnt = 0;
    int shpZipCnt = 0;
    int osmZipCnt = 0;
    int fgdbZipCnt = 0;
    List<String> zipList = new ArrayList<String>();

    shpZipCnt += (Integer) zipStat.get("shpzipcnt");
    fgdbZipCnt += (Integer) zipStat.get("fgdbzipcnt");
    osmZipCnt += (Integer) zipStat.get("osmzipcnt");

    zipList.add("ogr");
    zipCnt++;

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

    inputsList.add("zip1");

    res._buildNativeRequest(jobId, "zip1", "zip", input, results, zipStat);

    shpZipCnt += (Integer) zipStat.get("shpzipcnt");
    fgdbZipCnt += (Integer) zipStat.get("fgdbzipcnt");
    osmZipCnt += (Integer) zipStat.get("osmzipcnt");

    zipList.add("zip1");
    zipCnt++;

    // Test zip containing fgdb + shp
    JSONArray resA = res._createNativeRequest(results, zipCnt, shpZipCnt, fgdbZipCnt, osmZipCnt, shpCnt,
            fgdbCnt, osmCnt, zipList, "TDSv61.js", jobId, "ogr", inputsList);

    JSONObject req = (JSONObject) resA.get(0);
    JSONArray params = (JSONArray) req.get("params");

    int nP = 0;

    for (Object o : params) {
        JSONObject oJ = (JSONObject) o;

        if (oJ.get("INPUT") != null) {
            org.junit.Assert.assertTrue(oJ.get("INPUT").toString().equals("ogr.zip;zip1.zip"));
            nP++;
        }

        if (oJ.get("INPUT_PATH") != null) {
            org.junit.Assert.assertTrue(oJ.get("INPUT_PATH").toString().equals("upload/test-id-123"));
            nP++;
        }

        if (oJ.get("INPUT_TYPE") != null) {
            org.junit.Assert.assertTrue(oJ.get("INPUT_TYPE").toString().equals("ZIP"));
            nP++;
        }

    }
    org.junit.Assert.assertTrue(nP == 3);
    FileUtils.forceDelete(workingDir);
}

From source file:gui.DownloadPanel.java

public void actionClearAllCompleted() {
    int action = JOptionPane.showConfirmDialog(parent, "Do you realy want to delete all completed files?",
            "Confirm delete all", JOptionPane.OK_CANCEL_OPTION);
    if (action == JOptionPane.OK_OPTION) {
        List<Download> selectedDownloads = downloadsTableModel.getDownloadsByStatus(DownloadStatus.COMPLETE);

        clearing = true;//from  w  ww . j ava  2  s .c om
        downloadsTableModel.clearDownloads(selectedDownloads);
        downloadList.removeAll(selectedDownloads);
        clearing = false;

        try {
            for (Download download : selectedDownloads) {
                if (selectedDownload == download)
                    selectedDownload = null;
                DownloadDialog downloadDialog = getDownloadDialogByDownload(download);
                downloadDialogs.remove(downloadDialog);
                downloadDialog.removeDownloadInfoListener(this);
                downloadDialog.dispose();
                databaseController.delete(download.getId());
                FileUtils.forceDelete(new File(
                        download.getDownloadRangePath() + File.separator + download.getDownloadName())); // todo must again
            }
        } catch (SQLException | IOException e) {
            e.printStackTrace();
        }
        tableSelectionChanged();
    }
}

From source file:de.mendelson.comm.as2.server.AS2ServerProcessing.java

/**A client performed a file delete request
 *
 *///from   w  w  w  .j  a v  a2 s .  c  o m
private void processFileDeleteRequest(IoSession session, FileDeleteRequest request) {
    FileDeleteResponse response = new FileDeleteResponse(request);
    boolean success = false;
    File fileToDelete = new File(request.getFilename());
    try {
        if (fileToDelete.isDirectory()) {
            FileUtils.deleteDirectory(fileToDelete);
        } else {
            FileUtils.forceDelete(fileToDelete);
        }
        success = true;
    } catch (Exception e) {
    }
    response.setSuccess(success);
    session.write(response);
}

From source file:com.streamsets.datacollector.restapi.StageLibraryResource.java

@POST
@Path("/stageLibraries/extras/delete")
@ApiOperation(value = "Delete additional drivers", response = Object.class, authorizations = @Authorization(value = "basic"))
@RolesAllowed({ AuthzRole.ADMIN, AuthzRole.ADMIN_REMOTE })
public Response deleteExtras(List<StageLibraryExtrasJson> extrasList) throws IOException {
    String libsExtraDir = runtimeInfo.getLibsExtraDir();
    if (StringUtils.isEmpty(libsExtraDir)) {
        throw new RuntimeException(ContainerError.CONTAINER_01300.getMessage());
    }//from  w ww.  j a  va  2s. c om
    for (StageLibraryExtrasJson extrasJson : extrasList) {
        File additionalLibraryFile = new File(
                libsExtraDir + "/" + extrasJson.getLibraryId() + "/" + STAGE_LIB_JARS_DIR,
                extrasJson.getFileName());
        if (additionalLibraryFile.exists()) {
            FileUtils.forceDelete(additionalLibraryFile);
        }
    }
    return Response.ok().build();
}

From source file:net.nicholaswilliams.java.licensing.licensor.interfaces.cli.TestConsoleLicenseGenerator.java

@Test
@Ignore("canRead()/canWrite() do not work on Win; setReadable()/setWritable() do not work on some Macs.")
public void testInitializeLicenseCreator02() throws Exception {
    this.resetLicenseCreator();

    String fileName = "testInitializeLicenseCreator02.properties";
    File file = new File(fileName);
    file = file.getCanonicalFile();//  w  w  w.j  a  v a  2 s .  c o m
    if (file.exists())
        FileUtils.forceDelete(file);

    FileUtils.writeStringToFile(file, "test");

    assertTrue("Setting the file to not readable should have returned true.", file.setReadable(false, false));
    assertTrue("The file should be writable.", file.canWrite());
    assertFalse("The file should not be readable.", file.canRead());

    this.console.cli = EasyMock.createMockBuilder(CommandLine.class).withConstructor()
            .addMockedMethod("hasOption", String.class).addMockedMethod("getOptionValue", String.class)
            .createStrictMock();

    EasyMock.expect(this.console.cli.hasOption("config")).andReturn(true);
    EasyMock.expect(this.console.cli.getOptionValue("config")).andReturn(fileName);

    EasyMock.replay(this.console.cli, this.device);

    try {
        this.console.initializeLicenseCreator();
        fail("Expected exception IOException.");
    } catch (IOException ignore) {
    } finally {
        this.resetLicenseCreator();

        FileUtils.forceDelete(file);

        EasyMock.verify(this.console.cli);
    }
}

From source file:com.linkedin.pinot.core.startree.StarTreeSegmentCreator.java

@Override
public void seal() throws ConfigurationException, IOException {
    // Write all the aggregate rows to the aggregate segment
    LOG.info("Writing aggregate segment...");
    long startMillis = System.currentTimeMillis();
    int currentAggregateDocumentId = starTreeBuilder.getTotalRawDocumentCount();
    Iterator<StarTreeTableRow> itr = starTreeBuilder.getTable().getAllCombinations();
    while (itr.hasNext()) {
        StarTreeTableRow next = itr.next();
        if (next.getDimensions().contains(StarTreeIndexNode.all())) {
            // Write using that document ID to all columns
            for (final String column : dictionaryCreatorMap.keySet()) {
                Object dictionaryIndex = null; // TODO: Is this okay?

                if (starTreeDimensionDictionary.containsKey(column)) {
                    // Index the dimension value
                    Integer dimensionId = starTreeDimensionDictionary.get(column);
                    Integer dimensionValue = next.getDimensions().get(dimensionId);
                    if (dimensionValue == StarTreeIndexNode.all()) {
                        // Use all value
                        Object allValue = StarTreeIndexNode.getAllValue(schema.getFieldSpecFor(column));
                        if (schema.getFieldSpecFor(column).isSingleValueField()) {
                            dictionaryIndex = dictionaryCreatorMap.get(column).indexOfSV(allValue);
                        } else {
                            dictionaryIndex = dictionaryCreatorMap.get(column).indexOfMV(allValue);
                        }/*from  ww  w.  j a  va2  s .  co m*/
                    } else {
                        dictionaryIndex = dimensionValue;
                    }
                } else if (starTreeMetricDictionary.containsKey(column)) {
                    // Index the aggregate metric
                    Integer metricId = starTreeMetricDictionary.get(column);
                    Object columnValueToIndex = next.getMetrics().get(metricId);
                    if (schema.getFieldSpecFor(column).isSingleValueField()) {
                        dictionaryIndex = dictionaryCreatorMap.get(column).indexOfSV(columnValueToIndex);
                    } else {
                        dictionaryIndex = dictionaryCreatorMap.get(column).indexOfMV(columnValueToIndex);
                    }
                } else {
                    // Just index the raw value
                    Object columnValueToIndex = StarTreeIndexNode.getAllValue(schema.getFieldSpecFor(column));
                    if (schema.getFieldSpecFor(column).isSingleValueField()) {
                        dictionaryIndex = dictionaryCreatorMap.get(column).indexOfSV(columnValueToIndex);
                    } else {
                        dictionaryIndex = dictionaryCreatorMap.get(column).indexOfMV(columnValueToIndex);
                    }
                }

                if (schema.getFieldSpecFor(column).isSingleValueField()) {
                    ((SingleValueForwardIndexCreator) forwardIndexCreatorMap.get(column))
                            .index(currentAggregateDocumentId, (Integer) dictionaryIndex);
                } else {
                    ((MultiValueForwardIndexCreator) forwardIndexCreatorMap.get(column))
                            .index(currentAggregateDocumentId, (int[]) dictionaryIndex);
                }

                if (config.isCreateInvertedIndexEnabled()) {
                    invertedIndexCreatorMap.get(column).add(currentAggregateDocumentId, dictionaryIndex);
                }
            }
            currentAggregateDocumentId++;
        }
    }
    long endMillis = System.currentTimeMillis();
    LOG.info("Done writing aggregate segment (took {} ms)", endMillis - startMillis);

    for (final String column : forwardIndexCreatorMap.keySet()) {
        forwardIndexCreatorMap.get(column).close();
        if (config.isCreateInvertedIndexEnabled()) {
            invertedIndexCreatorMap.get(column).seal();
        }
        dictionaryCreatorMap.get(column).close();
    }

    writeMetadata(outDir,
            starTreeBuilder.getTotalRawDocumentCount() + starTreeBuilder.getTotalAggregateDocumentCount(),
            starTreeBuilder.getTotalAggregateDocumentCount(), true /* raw segment has star tree */);

    // Write star tree
    LOG.info("Writing " + V1Constants.STARTREE_FILE);
    startMillis = System.currentTimeMillis();
    File starTreeFile = new File(outDir, V1Constants.STARTREE_FILE);
    OutputStream starTreeOutputStream = new FileOutputStream(starTreeFile);
    starTreeBuilder.getTree().writeTree(starTreeOutputStream);
    starTreeOutputStream.close();
    endMillis = System.currentTimeMillis();
    LOG.info("Wrote StarTree file (took {} ms)", endMillis - startMillis);

    // Delete tmp star tree data
    LOG.info("Deleting StarTree table file {}", starTreeTableFile);
    FileUtils.forceDelete(starTreeTableFile);
}

From source file:ZipUtilTest.java

public void testUnwrapFile() throws Exception {
    File dest = File.createTempFile("temp", null);
    File destDir = File.createTempFile("tempDir", null);
    try {//from w  ww  .  ja  v  a  2 s  .com
        destDir.delete();
        destDir.mkdir();
        String child = "TestFile.txt";
        File parent = new File(getClass().getResource(child).getPath()).getParentFile();
        ZipUtil.pack(parent, dest, true);
        ZipUtil.unwrap(dest, destDir);
        assertTrue((new File(destDir, child)).exists());
    } finally {
        FileUtils.forceDelete(destDir);
    }
}

From source file:jp.primecloud.auto.process.puppet.PuppetNodeProcess.java

protected void backupManifest(Long instanceNo) {
    Instance instance = instanceDao.read(instanceNo);
    File manifestFile = new File(manifestDir, instance.getFqdn() + ".base.pp");

    if (!manifestFile.exists()) {
        return;/*  w w  w .j  a v a  2 s.co  m*/
    }

    // ??
    File backupDir = new File(manifestDir, "backup");
    File backupFile = new File(backupDir, manifestFile.getName());
    try {
        if (!backupDir.exists()) {
            backupDir.mkdir();
        }
        if (backupFile.exists()) {
            FileUtils.forceDelete(backupFile);
        }
        FileUtils.moveFile(manifestFile, backupFile);
    } catch (IOException e) {
        // ??
        log.warn(e.getMessage());
    }
}