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.hydrologis.jgrass.geonotes.util.ExifHandler.java

/**
 * Writes the supplied gps tags to the image file.
 * /*from  ww  w. java2s.c om*/
 * <p>The tags are written to a new image which then
 * replaces the old image and is then removed.
 * 
 * @param lat the latitude gps entry to add.
 * @param lon the longitude gps entry to add.
 * @param jpegImageFile the image file to update.
 * @throws Exception
 */
public static void writeGPSTagsToImage(double lat, double lon, File jpegImageFile) throws Exception {
    OutputStream os = null;
    try {
        TiffOutputSet outputSet = null;

        // note that metadata might be null if no metadata is found.
        IImageMetadata metadata = Sanselan.getMetadata(jpegImageFile);
        JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;
        if (null != jpegMetadata) {
            TiffImageMetadata exif = jpegMetadata.getExif();
            if (null != exif) {
                outputSet = exif.getOutputSet();
            }
        }

        if (null == outputSet)
            outputSet = new TiffOutputSet();

        outputSet.setGPSInDegrees(lon, lat);

        File destinationImageFile = new File(jpegImageFile.getAbsolutePath() + ".jpg"); //$NON-NLS-1$

        os = new FileOutputStream(destinationImageFile);
        os = new BufferedOutputStream(os);

        new ExifRewriter().updateExifMetadataLossless(jpegImageFile, os, outputSet);

        os.close();

        FileUtils.copyFile(destinationImageFile, jpegImageFile);
        FileUtils.forceDelete(destinationImageFile);
    } finally {
        if (os != null)
            os.close();
    }
}

From source file:com.hs.mail.imap.user.DefaultUserManager.java

private void deletePhysicalMessage(PhysMessage pm) {
    MessageDao dao = DaoFactory.getMessageDao();
    dao.deletePhysicalMessage(pm.getPhysMessageID());
    try {//from  w  w w  .  j  a  v  a2s .c o  m
        File file = Config.getDataFile(pm.getInternalDate(), pm.getPhysMessageID());
        FileUtils.forceDelete(file);
    } catch (IOException ex) {
        logger.warn(ex.getMessage(), ex); // Ignore - What we can do?
    }
}

From source file:com.bibisco.test.ImageManagerTest.java

@Test
public void testInsertImage() throws IOException {

    ContextManager.getInstance().setIdProject(AllTests.TEST_PROJECT_ID);

    File lFile = new File(AllTests.getImage1FilePath());
    ImageDTO lImageDTO = new ImageDTO();
    lImageDTO.setInputStream(new FileInputStream(lFile));
    lImageDTO.setSourceFileName(lFile.getName());
    lImageDTO.setDescription("description");
    lImageDTO.setElementType(ElementType.CHARACTERS);
    lImageDTO.setIdElement(67);//w  ww. ja va 2  s  .  c  om
    lImageDTO = ImageManager.insert(lImageDTO);

    File lFileInserted = new File(AllTests.BIBISCO_INTERNAL_PROJECTS_DIR + AllTests.getPathSeparator()
            + AllTests.TEST_PROJECT_ID + AllTests.getPathSeparator() + lImageDTO.getTargetFileName());
    Assert.assertTrue(lFileInserted.exists());

    SqlSessionFactory lSqlSessionFactory = AllTests.getProjectSqlSessionFactoryById(AllTests.TEST_PROJECT_ID);
    SqlSession lSqlSession = lSqlSessionFactory.openSession();
    try {
        ImagesMapper lImagesMapper = lSqlSession.getMapper(ImagesMapper.class);
        Images lImages = lImagesMapper.selectByPrimaryKey(new Long(lImageDTO.getIdImage()));
        Assert.assertEquals("description", lImages.getDescription());
        Assert.assertEquals(ElementType.CHARACTERS.getValue(), lImages.getElementType());
        Assert.assertEquals(lImageDTO.getTargetFileName(), lImages.getFileName());
        Assert.assertEquals(new Integer(67), lImages.getIdElement());
        Assert.assertEquals(lImageDTO.getIdImage(), new Integer(lImages.getIdImage().intValue()));

    } finally {
        lSqlSession.close();
    }

    AllTests.cleanTestProjectDB();
    FileUtils.forceDelete(lFileInserted);
}

From source file:de.egore911.versioning.deployer.performer.PerformCopy.java

private boolean copy(String uri, String target, String targetFilename) {
    URL url;/*from   ww  w .j  av  a  2s .c om*/
    try {
        url = new URL(uri);
    } catch (MalformedURLException e) {
        LOG.error("Invalid URI: {}", e.getMessage(), e);
        return false;
    }
    try {
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        int response = connection.getResponseCode();

        int lastSlash = uri.lastIndexOf('/');
        if (lastSlash < 0) {
            LOG.error("Invalid URI: {}", uri);
            return false;
        }

        int lastDot = uri.lastIndexOf('.');
        if (lastDot < 0) {
            LOG.error("Invalid URI: {}", uri);
            return false;
        }

        String filename;
        if (StringUtils.isEmpty(targetFilename)) {
            filename = uri.substring(lastSlash + 1);
        } else {
            filename = targetFilename;
        }

        XmlHolder xmlHolder = XmlHolder.getInstance();
        XPathExpression finalNameXpath = xmlHolder.xPath.compile("/project/build/finalName/text()");

        if (response == HttpURLConnection.HTTP_OK) {
            String downloadFilename = UrlUtil.concatenateUrlWithSlashes(target, filename);

            File downloadFile = new File(downloadFilename);
            FileUtils.forceMkdir(downloadFile.getParentFile());
            try (InputStream in = connection.getInputStream();
                    FileOutputStream out = new FileOutputStream(downloadFilename)) {
                IOUtils.copy(in, out);
            }
            LOG.debug("Downloaded {} to {}", url, downloadFilename);

            if (StringUtils.isEmpty(targetFilename)) {
                // Check if finalName if exists in pom.xml
                String destFile = null;
                try (ZipFile zipFile = new ZipFile(downloadFilename)) {
                    Enumeration<? extends ZipEntry> entries = zipFile.entries();
                    while (entries.hasMoreElements()) {
                        ZipEntry entry = entries.nextElement();
                        if (entry.getName().endsWith("/pom.xml")) {

                            String finalNameInPom;
                            try (InputStream inputStream = zipFile.getInputStream(entry)) {
                                try {
                                    MavenXpp3Reader mavenreader = new MavenXpp3Reader();
                                    Model model = mavenreader.read(inputStream);
                                    finalNameInPom = model.getBuild().getFinalName();
                                } catch (Exception e) {
                                    Document doc = xmlHolder.documentBuilder.parse(inputStream);
                                    finalNameInPom = (String) finalNameXpath.evaluate(doc,
                                            XPathConstants.STRING);
                                }
                            }

                            if (StringUtils.isNotEmpty(finalNameInPom)) {
                                destFile = UrlUtil.concatenateUrlWithSlashes(target,
                                        finalNameInPom + "." + uri.substring(lastDot + 1));
                            }
                            break;
                        }
                    }
                }

                // Move file to finalName if existed in pom.xml
                if (destFile != null) {
                    try {
                        File dest = new File(destFile);
                        if (dest.exists()) {
                            FileUtils.forceDelete(dest);
                        }
                        FileUtils.moveFile(downloadFile.getAbsoluteFile(), dest.getAbsoluteFile());
                        LOG.debug("Moved file from {} to {}", downloadFilename, destFile);
                    } catch (IOException e) {
                        LOG.error("Failed to move file to it's final name: {}", e.getMessage(), e);
                    }
                }
            }

            return true;
        } else {
            LOG.error("Could not download file: {}", uri);
            return false;
        }
    } catch (SAXException | IOException | XPathExpressionException e) {
        LOG.error("Could not download file ({}): {}", uri, e.getMessage(), e);
        return false;
    }
}

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

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

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

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

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

            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.", "RedHat", properties.get("finalLinuxProperty03"));
        assertEquals("The version property is not correct.", "1.0.1",
                properties.get(LinuxPropertiesLocator.PLUGIN_VERSION_KEY));
    } finally {
        FileUtils.forceDelete(versionFile);
    }
}

From source file:com.blackducksoftware.integration.hub.detect.lifecycle.shutdown.ShutdownManager.java

public void cleanup(File directory, List<File> skip) throws IOException {
    IOException exception = null;
    for (final File file : directory.listFiles()) {
        try {//from  w  ww .ja  v a2 s  . c  o m
            if (skip.contains(file)) {
                logger.debug("Skipping cleanup for: " + file.getAbsolutePath());
            } else {
                logger.debug("Cleaning up: " + file.getAbsolutePath());
                FileUtils.forceDelete(file);
            }
        } catch (final IOException ioe) {
            exception = ioe;
        }
    }

    if (null != exception) {
        throw exception;
    }
}

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

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

    OutputStream out = new FileOutputStream(testFile);
    Context context = new Context();
    context.put("format", "CSV");
    context.put("columns", "header3 header2");
    EventSerializer serializer = EventSerializerFactory.getInstance(
            "com.adaltas.flume.serialization.HeaderAndBodyTextEventSerializer$Builder", context, out);
    serializer.afterCreate();/*w ww .ja  v  a  2  s .  co  m*/
    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("value3,value2,event 1", reader.readLine());
    Assert.assertEquals("value3,value2,event 2", reader.readLine());
    Assert.assertEquals("value3,value2,event 3", reader.readLine());
    Assert.assertNull(reader.readLine());
    reader.close();

    FileUtils.forceDelete(testFile);
}

From source file:algorithm.F5Steganography.java

@Override
public List<RestoredFile> restore(File carrier) throws IOException {
    List<RestoredFile> restoredFiles = new ArrayList<RestoredFile>();
    File tmpPayload = new File("tmp");
    tmpPayload.delete(); // F5 won't override existing files!
    restore("" + tmpPayload.toPath(), "" + carrier.toPath());
    RestoredFile copiedCarrier = new RestoredFile(RESTORED_DIRECTORY + carrier.getName());
    copiedCarrier.wasCarrier = true;//from  www  .j  a v a2s.co  m
    copiedCarrier.checksumValid = false;
    copiedCarrier.restorationNote = "The carrier can't be restored with this steganography algorithm. It still contains the embedded payload file(s).";
    FileUtils.copyFile(carrier, copiedCarrier);
    byte[] payloadSegmentBytes = FileUtils.readFileToByteArray(tmpPayload);
    PayloadSegment payloadSegment = PayloadSegment.getPayloadSegment(payloadSegmentBytes);
    RestoredFile restoredPayload = new RestoredFile(RESTORED_DIRECTORY + payloadSegment.getPayloadName());
    FileUtils.writeByteArrayToFile(restoredPayload, payloadSegment.getPayloadBytes());
    restoredPayload.validateChecksum(payloadSegment.getPayloadChecksum());
    restoredPayload.restorationNote = "Payload can be restored correctly.";
    restoredPayload.wasPayload = true;
    restoredPayload.originalFilePath = payloadSegment.getPayloadPath();
    copiedCarrier.originalFilePath = payloadSegment.getCarrierPath();
    restoredFiles.add(restoredPayload);
    FileUtils.forceDelete(tmpPayload);
    restoredFiles.add(copiedCarrier);// carrier can not be restored
    for (RestoredFile file : restoredFiles) {
        file.algorithm = this;
        for (RestoredFile relatedFile : restoredFiles) {
            if (file != relatedFile) {
                file.relatedFiles.add(relatedFile);
            }
        }
    }
    return restoredFiles;
}

From source file:com.docd.purefm.test.MediaStoreUtilsTest.java

private void doTearDown() throws Exception {
    if (TEST_ROOT.exists()) {
        FileUtils.forceDelete(TEST_ROOT);
    }/* w  w w. j  a v a 2  s  .c o m*/
    MediaStoreUtils.deleteAllFromDirectory(getContext().getContentResolver(), new JavaFile(TEST_ROOT));
}

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

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

    File temp;//from   w w  w.  j a  v a2 s . c om
    try {
        temp = new File(url.toURI());
    } catch (URISyntaxException e) {
        temp = new File(url.getPath());
    }

    temp = new File(temp, "net/nicholaswilliams/java/licensing/licensor/testGetLicenseFile04.prop");

    FileUtils.writeStringToFile(temp, "temp");

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

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

    FileUtils.forceDelete(temp);
}