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:it.unimi.di.big.mg4j.document.DocumentCollectionTest.java

protected void tearDown() throws IOException {
    FileUtils.forceDelete(tempDir);
}

From source file:com.taobao.android.builder.tasks.app.databinding.AwbDataBindingRenameTask.java

/**
 * ?so/* w  w w.  j  a va2  s .  com*/
 */
@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()) {

        if (!awbBundle.isDataBindEnabled()) {
            continue;
        }

        runnables.add(new Runnable() {

            @Override
            public void run() {

                try {

                    File dataBindingClazzFolder = appVariantOutputContext.getVariantContext()
                            .getJAwbavaOutputDir(awbBundle);
                    String packageName = awbBundle.getPackageName();
                    String appName = awbBundle.getPackageName() + "._bundleapp_";

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

                    rewriteDataBinderMapper(dataBindingClazzFolder, packageName, dataMapperClazz);
                    //FileUtils.deleteDirectory(new File(dataBindingClazzFolder, packageName.replace(".", "/") +
                    // "/_bundleapp_" ));

                    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);
                        }
                    }

                    //rename DataBindUtils
                    AwbTransform awbTransform = appVariantOutputContext.getAwbTransformMap()
                            .get(awbBundle.getName());

                    List<File> files = awbTransform.getInputLibraries();

                    Map<String, String> replaceMap = new HashMap<>();
                    replaceMap.put("android/databinding/DataBindingUtil",
                            "android/databinding/AtlasDataBindingUtil");

                    List<File> newLibrarys = new ArrayList<>();

                    for (File inputJar : files) {

                        File outputJar = new File(appVariantContext.getAwbLibraryDirForDataBinding(awbBundle),
                                FileNameUtils.getUniqueJarName(inputJar) + ".jar");

                        outputJar.delete();
                        outputJar.getParentFile().mkdirs();
                        outputJar.createNewFile();

                        new ClazzReplacer(inputJar, outputJar, replaceMap).execute();
                        newLibrarys.add(outputJar);
                    }

                    awbTransform.setInputLibraries(newLibrarys);

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

            }
        });

    }

    executorServicesHelper.execute(runnables);

}

From source file:com.tresys.jalop.utils.jnltest.SubscriberImpl.java

/**
 * Helper utility to run through all records that have been transferred,
 * but not yet synced. For log & audit records, this will remove all
 * records that are not synced (even if they are completely downloaded).
 * For journal records, this finds the record after the most recently
 * synced record record, and deletes all the other unsynced records. For
 * example, if the journal records 1, 2, 3, and 4 have been downloaded, and
 * record number 2 is marked as 'synced', then this will remove record
 * number 4, and try to resume the transfer for record number 3.
 *
 * @throws IOException If there is an error reading existing files, or an
 *          error removing stale directories.
 * @throws org.json.simple.parser.ParseException
 * @throws ParseException If there is an error parsing status files.
 * @throws java.text.ParseException If there is an error parsing a
 *          directory name.//  w w  w.  j  a va2s .  com
 */
final void prepareForSubscribe() throws IOException, ParseException, java.text.ParseException {

    final File[] outputRecordDirs = this.outputRoot.listFiles(SubscriberImpl.FILE_FILTER);
    long lastSerial = 0;
    if (outputRecordDirs.length >= 1) {
        Arrays.sort(outputRecordDirs);
        final List<File> sortedOutputRecords = java.util.Arrays.asList(outputRecordDirs);
        final File lastRecord = sortedOutputRecords.get(sortedOutputRecords.size() - 1);
        lastSerial = Long.valueOf(lastRecord.getName());
    }

    switch (this.recordType) {
    case Audit:
        this.jnlTest.setLatestAuditSID(lastSerial++);
        break;
    case Journal:
        this.jnlTest.setLatestJournalSID(lastSerial++);
        break;
    case Log:
        this.jnlTest.setLatestLogSID(lastSerial++);
        break;
    }

    this.lastSerialFromRemote = SubscribeRequest.EPOC;
    this.journalOffset = 0;
    final JSONParser p = new JSONParser();
    final File[] recordDirs = this.outputIpRoot.listFiles(SubscriberImpl.FILE_FILTER);

    if (this.lastConfirmedFile.length() > 0) {
        final JSONObject lastConfirmedJson = (JSONObject) p.parse(new FileReader(this.lastConfirmedFile));

        this.lastSerialFromRemote = (String) lastConfirmedJson.get(LAST_CONFIRMED_SID);
    }

    final Set<File> deleteDirs = new HashSet<File>();

    if (this.recordType == RecordType.Journal && recordDirs.length > 0) {
        // Checking the first record to see if it can be resumed, the rest will be deleted
        Arrays.sort(recordDirs);
        final List<File> sortedRecords = new ArrayList<File>(java.util.Arrays.asList(recordDirs));

        final File firstRecord = sortedRecords.remove(0);
        deleteDirs.addAll(sortedRecords);

        JSONObject status;
        try {
            status = (JSONObject) p.parse(new FileReader(new File(firstRecord, STATUS_FILENAME)));

            final Number progress = (Number) status.get(PAYLOAD_PROGRESS);
            if (!CONFIRMED.equals(status.get(DGST_CONF)) && progress != null) {
                // journal record can be resumed
                this.lastSerialFromRemote = (String) status.get(REMOTE_SID);
                this.journalOffset = progress.longValue();
                FileUtils.forceDelete(new File(firstRecord, APP_META_FILENAME));
                FileUtils.forceDelete(new File(firstRecord, SYS_META_FILENAME));
                status.remove(APP_META_PROGRESS);
                status.remove(SYS_META_PROGRESS);
                this.sid = SID_FORMATER.parse(firstRecord.getName()).longValue();
                this.journalInputStream = new FileInputStream(new File(firstRecord, PAYLOAD_FILENAME));
            } else {
                deleteDirs.add(firstRecord);
            }

        } catch (final FileNotFoundException e) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Deleting " + firstRecord + ", because it is missing the '" + STATUS_FILENAME
                        + "' file");
            }
            deleteDirs.add(firstRecord);
        } catch (final ParseException e) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(
                        "Deleting " + firstRecord + ", because failed to parse '" + STATUS_FILENAME + "' file");
            }
            deleteDirs.add(firstRecord);
        }

    } else {
        // Any confirmed record should have been moved so deleting all that are left
        deleteDirs.addAll(java.util.Arrays.asList(recordDirs));
    }

    for (final File f : deleteDirs) {
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Removing directory for unsynced record: " + f.getAbsolutePath());
        }
        FileUtils.forceDelete(f);
    }
}

From source file:gui.DownloadPanel.java

public void actionClear() {
    int action = JOptionPane.showConfirmDialog(parent, "Do you realy want to delete selected file?",
            "Confirm delete", JOptionPane.OK_CANCEL_OPTION);
    if (action == JOptionPane.OK_OPTION) {
        if (selectedDownload == null)
            return;
        //     download download = selectedDownloadDialog.getDownload();

        clearing = true;//from  w  ww.j  av a  2 s.co  m
        downloadsTableModel.clearDownload(selectedDownload);
        if (downloadList.contains(selectedDownload))
            downloadList.remove(selectedDownload);
        clearing = false;

        //    selectedDownloadDialog = null;
        DownloadDialog downloadDialog = getDownloadDialogByDownload(selectedDownload);
        downloadDialogs.remove(downloadDialog);
        downloadDialog.dispose();
        downloadDialog.removeDownloadInfoListener(this);
        downloadDialog = null;

        try {
            databaseController.delete(selectedDownload.getId());
        } catch (SQLException e) {
            //      e.printStackTrace();
        }

        try {
            FileUtils.forceDelete(new File(selectedDownload.getDownloadRangePath() + File.separator
                    + selectedDownload.getDownloadName())); // todo must again
        } catch (IOException e) {
            //      e.printStackTrace();
        }

        selectedDownload = null;
        tableSelectionChanged();
    }
}

From source file:com.ibm.soatf.component.soap.SOAPComponent.java

private void invokeServiceWithProvidedSOAPRequest() throws SoapComponentException {
    try {/*  www  .  j av a 2s.  c  om*/
        final String filename = new StringBuilder(serviceName).append(NAME_DELIMITER).append(operationName)
                .append(NAME_DELIMITER).toString();
        final File requestFile = new File(workingDir, filename + REQUEST_FILE_SUFFIX);
        final File responseFile = new File(workingDir, filename + RESPONSE_FILE_SUFFIX);

        String delimiter = "";
        if (!serviceURI.startsWith("/")) {
            delimiter = "/";
        }
        final ManagedServer managedServer = osbCluster.getManagedServer().get(0);
        final URL url = new URL(DEFAULT_PROTO, managedServer.getHostName(), managedServer.getPort(),
                delimiter + serviceURI);
        final String requestEnvelope = FileUtils.readFileToString(requestFile);
        JAXWSDispatch jaxwsDispatch = new JAXWSDispatch();
        ProgressMonitor.init(3, "Connecting to service..."); //1 progress event in jaxwsDispatch.invoke()
        final SOAPMessage res = jaxwsDispatch.invoke(url, requestEnvelope);

        String msg = "Successfuly received response of operation: " + operationName;
        logger.debug(msg);
        cor.addMsg(msg);

        ProgressMonitor.increment("Saving response to disk...");
        if (responseFile.exists()) {
            FileUtils.forceDelete(responseFile);
        }
        try (FileOutputStream fos = new FileOutputStream(responseFile)) {
            res.writeTo(fos);
        }
        msg = "Response of operation: " + operationName + " was stored in [FILE: %s]";
        logger.debug(String.format(msg, responseFile.getAbsolutePath()));
        cor.addMsg(msg, "<a href='file://" + responseFile.getAbsolutePath() + "'>"
                + responseFile.getAbsolutePath() + "</a>", FileSystem.getRelativePath(responseFile));
        cor.markSuccessful();
    } catch (IOException | SOAPException ex) {
        throw new SoapComponentException(ex);
    }
}

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

@Test
public void testInitializeLicenseCreator01() throws Exception {
    this.resetLicenseCreator();

    String fileName = "testInitializeLicenseCreator01.properties";
    File file = new File(fileName);
    if (file.exists())
        FileUtils.forceDelete(file);

    this.console.cli = EasyMock.createMockBuilder(CommandLine.class).withConstructor()
            .addMockedMethod("hasOption", String.class).addMockedMethod("getOptionValue", String.class)
            .createStrictMock();//w  w  w.ja  v  a  2  s .  c  om

    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 FileNotFoundException.");
    } catch (FileNotFoundException ignore) {
    } finally {
        this.resetLicenseCreator();

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

From source file:com.kegare.caveworld.client.config.GuiVeinsEntry.java

@Override
protected void actionPerformed(GuiButton button) {
    if (button.enabled) {
        switch (button.id) {
        case 0:/*  w  w  w . j a  v  a  2s .  com*/
            if (editMode) {
                if (Strings.isNullOrEmpty(blockField.getText()) || NumberUtils.toInt(countField.getText()) <= 0
                        || NumberUtils.toInt(weightField.getText()) <= 0
                        || NumberUtils.toInt(rateField.getText()) <= 0) {
                    return;
                }

                veinList.selected.setBlock(
                        new BlockEntry(blockField.getText(), NumberUtils.toInt(blockMetaField.getText())));
                veinList.selected.setGenBlockCount(
                        NumberUtils.toInt(countField.getText(), veinList.selected.getGenBlockCount()));
                veinList.selected.setGenWeight(
                        NumberUtils.toInt(weightField.getText(), veinList.selected.getGenWeight()));
                veinList.selected
                        .setGenRate(NumberUtils.toInt(rateField.getText(), veinList.selected.getGenRate()));
                veinList.selected.setGenMinHeight(
                        NumberUtils.toInt(minHeightField.getText(), veinList.selected.getGenMinHeight()));
                veinList.selected.setGenMaxHeight(
                        NumberUtils.toInt(maxHeightField.getText(), veinList.selected.getGenMaxHeight()));
                veinList.selected.setGenTargetBlock(
                        new BlockEntry(targetField.getText(), NumberUtils.toInt(targetMetaField.getText())));

                List<Integer> ids = Lists.newArrayList();

                for (String str : Splitter.on(',').trimResults().omitEmptyStrings()
                        .split(biomesField.getText())) {
                    if (NumberUtils.isNumber(str)) {
                        ids.add(Integer.parseInt(str));
                    }
                }

                Collections.sort(ids);

                veinList.selected.setGenBiomes(Ints.toArray(ids));

                hoverCache.remove(veinList.selected);

                actionPerformed(cancelButton);

                veinList.scrollToSelected();
            } else {
                boolean flag = CaveworldAPI.getCaveVeins().size() != veinList.veins.size();

                CaveworldAPI.clearCaveVeins();

                if (flag) {
                    try {
                        FileUtils.forceDelete(new File(Config.veinsCfg.toString()));

                        Config.veinsCfg.load();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                for (ICaveVein vein : veinList.veins) {
                    CaveworldAPI.addCaveVein(vein);
                }

                if (Config.veinsCfg.hasChanged()) {
                    Config.veinsCfg.save();
                }

                actionPerformed(cancelButton);
            }

            break;
        case 1:
            if (editMode) {
                actionPerformed(cancelButton);
            } else {
                editMode = true;
                initGui();

                veinList.scrollToSelected();

                blockField.setText(
                        GameData.getBlockRegistry().getNameForObject(veinList.selected.getBlock().getBlock()));
                blockMetaField.setText(Integer.toString(veinList.selected.getBlock().getMetadata()));
                countField.setText(Integer.toString(veinList.selected.getGenBlockCount()));
                weightField.setText(Integer.toString(veinList.selected.getGenWeight()));
                rateField.setText(Integer.toString(veinList.selected.getGenRate()));
                minHeightField.setText(Integer.toString(veinList.selected.getGenMinHeight()));
                maxHeightField.setText(Integer.toString(veinList.selected.getGenMaxHeight()));
                targetField.setText(GameData.getBlockRegistry()
                        .getNameForObject(veinList.selected.getGenTargetBlock().getBlock()));
                targetMetaField.setText(Integer.toString(veinList.selected.getGenTargetBlock().getMetadata()));
                biomesField.setText(Ints.join(", ", veinList.selected.getGenBiomes()));
            }

            break;
        case 2:
            if (editMode) {
                editMode = false;
                initGui();
            } else {
                mc.displayGuiScreen(parentScreen);
            }

            break;
        case 3:
            mc.displayGuiScreen(new GuiSelectBlock(this));
            break;
        case 4:
            if (veinList.veins.remove(veinList.selected)) {
                int i = veinList.contents.indexOf(veinList.selected);

                veinList.contents.remove(i);
                veinList.selected = veinList.contents.get(i, veinList.contents.get(--i, null));
            }

            break;
        case 5:
            for (Object entry : veinList.veins.toArray()) {
                veinList.selected = (ICaveVein) entry;

                actionPerformed(removeButton);
            }

            break;
        case 6:
            CaveConfigGui.detailInfo = detailInfo.isChecked();
            break;
        case 7:
            CaveConfigGui.instantFilter = instantFilter.isChecked();
            break;
        }
    }
}

From source file:com.willwinder.universalgcodesender.AbstractControllerTest.java

/**
 * Test of queueStream method, of class AbstractController.
 *//*  www  . j a  v a  2 s .  c o m*/
@Test
public void testQueueStreamForComm() throws Exception {
    System.out.println("queueStream");

    String command = "command";
    Collection<String> commands = Arrays.asList(command, command);
    String port = "/some/port";
    int rate = 1234;

    File f = new File(tempDir, "gcodeFile");
    try {
        try (GcodeStreamWriter gsw = new GcodeStreamWriter(f)) {
            for (String i : commands) {
                gsw.addLine("blah", command, null, -1);
            }
        }

        try (GcodeStreamReader gsr = new GcodeStreamReader(f)) {
            openInstanceExpectUtility(port, rate);
            streamInstanceExpectUtility();

            // TODO Fix this
            // Making sure the commands get queued.
            mockCommunicator.queueStreamForComm(gsr);

            EasyMock.expect(EasyMock.expectLastCall()).times(1);

            EasyMock.replay(instance, mockCommunicator);

            // Open port, send some commands, make sure they are streamed.
            instance.openCommPort(port, rate);
            instance.queueStream(gsr);
            instance.beginStreaming();
        }

        EasyMock.verify(mockCommunicator, instance);
    } finally {
        FileUtils.forceDelete(f);
    }
}

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

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

    // ?/*from   ww  w .j  a  v a 2s .  c  om*/
    File backupDir = new File(manifestDir, "backup");
    File backupFile = new File(backupDir, manifestFile.getName());

    if (!backupFile.exists()) {
        return;
    }

    try {
        if (manifestFile.exists()) {
            FileUtils.forceDelete(manifestFile);
        }
        FileUtils.moveFile(backupFile, manifestFile);
    } catch (IOException e) {
        // ?
        log.warn(e.getMessage());
    }
}

From source file:kr.co.leem.system.FileSystemUtils.java

/**
 * ? /  ./*from   www .  ja va2s  .  co  m*/
 *
 * @param path ? /  .
 * @see FileUtils#forceDelete(File)
 */
public static void deleteFileDirectory(final String path) {
    processIO(new IOCallback<Object>() {
        public Object doInProcessIO() throws IOException, NullPointerException {
            FileUtils.forceDelete(new File(path));
            return null;
        }
    });
}