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:eu.openanalytics.rsb.component.DirectoryDepositHandlerTestCase.java

private void testHandleJob(final File jobParentFile, final File zipJobFile) throws IOException {
    final DepositDirectoryConfiguration depositRootDirectoryConfig = mock(DepositDirectoryConfiguration.class);
    when(depositRootDirectoryConfig.getApplicationName()).thenReturn(TEST_APPLICATION_NAME);
    when(configuration.getDepositRootDirectories())
            .thenReturn(Collections.singletonList(depositRootDirectoryConfig));

    final Message<File> message = MessageBuilder.withPayload(zipJobFile)
            .setHeader(DirectoryDepositHandler.DIRECTORY_CONFIG_HEADER_NAME, depositRootDirectoryConfig)
            .build();/*w ww.jav a  2  s  . c  o m*/

    directoryDepositHandler.handleJob(message);

    final ArgumentCaptor<MultiFilesJob> jobCaptor = ArgumentCaptor.forClass(MultiFilesJob.class);
    verify(messageDispatcher).dispatch(jobCaptor.capture());

    final MultiFilesJob job = jobCaptor.getValue();
    assertThat(job.getApplicationName(), is(TEST_APPLICATION_NAME));
    assertThat(job.getMeta().containsKey(DirectoryDepositHandler.DEPOSIT_ROOT_DIRECTORY_META_NAME), is(true));
    assertThat(job.getMeta().containsKey(DirectoryDepositHandler.INBOX_DIRECTORY_META_NAME), is(true));
    assertThat(job.getMeta().containsKey(DirectoryDepositHandler.ORIGINAL_FILENAME_META_NAME), is(true));
    assertThat(job.getSource(), is(Source.DIRECTORY));
    job.destroy();

    FileUtils.forceDelete(jobParentFile);
}

From source file:net.nicholaswilliams.java.teamcity.plugin.linux.TestAbstractLinuxPropertiesLocator.java

@Test
public void testLocateProperties03() throws IOException {
    File pluginRoot = new File(".");
    File versionFile = new File(pluginRoot, "version.properties");
    FileUtils.writeStringToFile(versionFile, LinuxPropertiesLocator.PLUGIN_VERSION_KEY + "=0.9.16-beta");

    final Capture<Map<String, String>> capture = new Capture<Map<String, String>>();

    this.locator.locateLinuxProperties(capture(capture));
    expectLastCall().andAnswer(new IAnswer<Void>() {
        @Override//from  w w w.j  a v a  2 s . c om
        public Void answer() throws Throwable {
            assertFalse("The properties map should not be empty.", capture.getValue().isEmpty());
            assertEquals("The version property is not correct.", "0.9.16-beta",
                    capture.getValue().get(LinuxPropertiesLocator.PLUGIN_VERSION_KEY));

            capture.getValue().put("finalLinuxProperty03", "SuSE");

            return null;
        }
    });

    replay(this.locator);

    try {
        Map<String, String> properties = this.locator.locateProperties(pluginRoot);

        assertNotNull("The properties should not be null.", properties);
        assertEquals("The linux property is not correct.", "SuSE", properties.get("finalLinuxProperty03"));
        assertEquals("The version property is not correct.", "0.9.16-beta",
                properties.get(LinuxPropertiesLocator.PLUGIN_VERSION_KEY));
    } finally {
        FileUtils.forceDelete(versionFile);
    }
}

From source file:fr.gael.dhus.datastore.FileSystemDataStore.java

/**
 * Delete a file or a directory via it path.
 *
 * @param path path of file to delete./*w ww  . jav a2  s  .  co m*/
 * @throws IOException in case deletion is unsuccessful.
 */
private void deleteIncomingFolder(String path) throws IOException {
    if (path == null) {
        return;
    }
    File container = new File(path);
    if (!container.exists() || !incomingManager.isInIncoming(container)) {
        return;
    }
    if (IncomingManager.INCOMING_PRODUCT_DIR.equals(container.getParentFile().getName())) {
        container = container.getParentFile();
    }
    if (HierarchicalDirectoryBuilder.DHUS_ENTRY_NAME.equals(container.getParentFile().getName())) {
        container = container.getParentFile();
    }
    if (container != null) {
        FileUtils.forceDelete(container);
    }
}

From source file:net.ostis.scpdev.builder.scg.SCgFileBuilder.java

@Override
public void buildImpl(IFolder binroot) throws CoreException {
    // 1. Parse scg file
    if (parseSCgFile() == false)
        return;//from w  ww. jav a  2  s .com

    File converted = null;

    try {
        try {
            if (log.isDebugEnabled()) {
                IFolder folder = source.getProject().getFolder("converted_scs");
                if (folder.exists() == false)
                    folder.create(true, true, null);

                IFile convertedFile = folder.getFile(source.getName() + ".scs");
                converted = convertedFile.getRawLocation().toFile();
            } else {
                converted = File.createTempFile("scg", "builder");
            }

            FileOutputStream out = FileUtils.openOutputStream(converted);
            SCsWriter writer = new SCsWriter(out);
            try {
                // Write includes from SCg-file.
                writer.write("\n");
                for (String include : includes) {
                    writer.write(include);
                    writer.write("\n");
                }

                for (IFile gwfFile : gwfs) {
                    // 2. Parse each gwf file
                    if (parseGwfFile(gwfFile.getRawLocation().toFile()) == false) {
                        // If parsing for one fails then skip other gwfs
                        return;
                    }

                    writer.comment("////////////////////////////////////////////////");
                    writer.comment(String.format("File '%s'", gwfFile.getFullPath().toString()));
                    writer.write("\n");

                    // 3. Use list 'objects' encode all not writed
                    // scg-objects
                    encodeToSCs(writer);
                }
            } finally {
                writer.close();
            }

            InputStream errorStream = convertSCsSource(converted.getAbsolutePath(), binroot);
            if (errorStream != null)
                applySCsErrors(source, errorStream);
        } finally {
            if (log.isDebugEnabled()) {
                source.getProject().getFolder("converted_scs").refreshLocal(IResource.DEPTH_INFINITE, null);
            } else {
                if (converted != null) {
                    FileUtils.forceDelete(converted);
                }
            }
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new CoreException(StatusUtils.makeStatus(IStatus.ERROR, e.getMessage(), e));
    }
}

From source file:com.qualinsight.mojo.cobertura.core.AbstractInstrumentationMojo.java

private void prepareDirectories(final File classesDirectory, final File backupClassesDirectory,
        final File baseDataFile) throws MojoExecutionException {
    getLog().debug("Preparing Cobertura instrumentation directories");
    try {/*  w w  w  .j  a v  a  2 s. co  m*/
        if (backupClassesDirectory.exists()) {
            FileUtils.forceDelete(backupClassesDirectory);
        }
        FileUtils.copyDirectory(classesDirectory, backupClassesDirectory);
        if (baseDataFile.exists() && !FileUtils.deleteQuietly(baseDataFile)) {
            final String message = "Could not delete baseDataFile: " + baseDataFile.getAbsolutePath();
            getLog().error(message);
            throw new MojoExecutionException(message);
        }
    } catch (final IOException e) {
        final String message = "An error occured during directories preparation:";
        getLog().error(message, e);
        throw new MojoExecutionException(message, e);
    }
}

From source file:net.nicholaswilliams.java.licensing.encryption.TestFilePublicKeyDataProvider.java

@Test
public void testGetEncryptedPublicKeyData04() throws IOException {
    final String fileName = "testGetEncryptedPublicKeyData04.key";
    File file = new File(fileName);

    if (file.exists())
        FileUtils.forceDelete(file);

    byte[] data = new byte[] { 0x51, 0x12, 0x23 };

    FileUtils.writeByteArrayToFile(file, data);

    try {//from w w w . j  av a 2s  . co m
        FilePublicKeyDataProvider provider = new FilePublicKeyDataProvider(file);

        byte[] returnedData = provider.getEncryptedPublicKeyData();

        assertNotNull("The data should not be null.", returnedData);
        assertArrayEquals("The data is not correct.", data, returnedData);
    } finally {
        FileUtils.forceDelete(file);
    }
}

From source file:com.adaltas.flume.serialization.TestHeaderAndBodyTextEventSerializer.java

@Test
public void testCSV() throws FileNotFoundException, IOException {
    Map<String, String> headers = new HashMap<String, String>();
    headers.put("header1", "value1");
    headers.put("header2", "value2");

    OutputStream out = new FileOutputStream(testFile);
    Context context = new Context();
    context.put("format", "CSV");
    EventSerializer serializer = EventSerializerFactory.getInstance(
            "com.adaltas.flume.serialization.HeaderAndBodyTextEventSerializer$Builder", context, out);
    serializer.afterCreate();//from   w w w .j  a va  2s .  com
    serializer.write(EventBuilder.withBody("event 1", Charsets.UTF_8, headers));
    serializer.write(EventBuilder.withBody("event 2", Charsets.UTF_8, headers));
    serializer.write(EventBuilder.withBody("event 3", Charsets.UTF_8, headers));
    serializer.flush();
    serializer.beforeClose();
    out.flush();
    out.close();

    BufferedReader reader = new BufferedReader(new FileReader(testFile));
    Assert.assertEquals("value2,value1,event 1", reader.readLine());
    Assert.assertEquals("value2,value1,event 2", reader.readLine());
    Assert.assertEquals("value2,value1,event 3", reader.readLine());
    Assert.assertNull(reader.readLine());
    reader.close();

    FileUtils.forceDelete(testFile);
}

From source file:com.github.nukesparrow.htmlunit.DebuggingWebConnection.java

public DebuggingWebConnection(WebConnection wrapped, String dirName) {
    this(wrapped);
    final File tmpDir = new File(System.getProperty("java.io.tmpdir"));
    File reportFolder_ = new File(tmpDir, dirName);
    try {/*  w  ww.j a va2  s. c  om*/
        if (reportFolder_.exists()) {
            FileUtils.forceDelete(reportFolder_);
        }
        FileUtils.forceMkdir(reportFolder_);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
    logFile = new File(reportFolder_, "log.html");
}

From source file:me.philnate.textmanager.utils.PDFCreator.java

@SuppressWarnings("deprecation")
private void preparePDF() {
    try {//  www. ja v  a2  s.  c om
        File path = new File(SystemUtils.getUserDir(), "template");
        File template = new File(path, Setting.find("template").getValue());

        Velocity.setProperty("file.resource.loader.path", path.getAbsolutePath());
        Velocity.init();
        VelocityContext ctx = new VelocityContext();

        // User data/Settings
        for (Setting setting : ds.find(Setting.class).asList()) {
            ctx.put(setting.getKey(), setting.getValue());
        }

        NumberFormat format = NumberFormat.getNumberInstance(new Locale(Setting.find("locale").getValue()));
        // #60 always show 2 digits for fraction no matter if right most(s)
        // are zero
        format.setMinimumFractionDigits(2);
        format.setMaximumFractionDigits(2);
        ctx.put("number", format);
        // TODO update schema to have separate first and lastname
        // Customer data
        ctx.put("customer", customer);

        // General data
        ctx.put("month", new DateFormatSymbols().getMonths()[month]);
        ctx.put("math", new MathTool());
        // Billing data
        ctx.put("allItems", BillingItem.find(customer.getId(), year, month));
        ctx.put("billNo", bill.getBillNo());

        StringWriter writer = new StringWriter();
        Velocity.mergeTemplate(template.getName(), ctx, writer);
        File filledTemplate = new File(path, bill.getBillNo() + ".tex");
        FileUtils.writeStringToFile(filledTemplate, writer.toString(), "ISO-8859-1");

        ProcessBuilder pdfLatex = new ProcessBuilder(Setting.find("pdfLatex").getValue(),
                "-interaction nonstopmode", "-output-format pdf", filledTemplate.toString());

        // Saving template file (just in case it may be needed later
        GridFSFile texFile = tex.createFile(filledTemplate);
        texFile.put("month", month);
        texFile.put("year", year);
        texFile.put("customerId", customer.getId());
        texFile.save();

        pdfLatex.directory(path);
        String pdfPath = filledTemplate.toString().replaceAll("tex$", "pdf");
        if (0 == printOutputStream(pdfLatex)) {
            // display Bill in DocumentViewer
            new ProcessBuilder(Setting.find("pdfViewer").getValue(), pdfPath).start().waitFor();
            GridFSFile pdfFile = pdf.createFile(new File(pdfPath));
            pdfFile.put("month", month);
            pdfFile.put("year", year);
            pdfFile.put("customerId", customer.getId());
            pdf.remove(QueryBuilder.start("month").is(month).and("year").is(year).and("customerId")
                    .is(customer.getId()).get());
            pdfFile.save();
            File[] files = path.listFiles((FileFilter) new WildcardFileFilter(bill.getBillNo() + ".*"));
            for (File file : files) {
                FileUtils.forceDelete(file);
            }
        } else {
            new JOptionPane(
                    "Bei der Erstellung der Rechnung ist ein Fehler aufgetreten. Es wurde keine Rechnung erstellt.\n Bitte Schauen sie in die Logdatei fr nhere Fehlerinformationen.",
                    JOptionPane.ERROR_MESSAGE).setVisible(true);
        }
    } catch (IOException e) {
        Throwables.propagate(e);
    } catch (InterruptedException e) {
        Throwables.propagate(e);
    }
}

From source file:net.nicholaswilliams.java.licensing.encryption.TestFilePrivateKeyDataProvider.java

@Test
public void testGetEncryptedPrivateKeyData04() throws IOException {
    final String fileName = "testGetEncryptedPrivateKeyData04.key";
    File file = new File(fileName);

    if (file.exists())
        FileUtils.forceDelete(file);

    byte[] data = new byte[] { 0x51, 0x12, 0x23 };

    FileUtils.writeByteArrayToFile(file, data);

    try {// w w w.  ja  v a2s .com
        FilePrivateKeyDataProvider provider = new FilePrivateKeyDataProvider(file);

        byte[] returnedData = provider.getEncryptedPrivateKeyData();

        assertNotNull("The data should not be null.", returnedData);
        assertArrayEquals("The data is not correct.", data, returnedData);
    } finally {
        FileUtils.forceDelete(file);
    }
}