Example usage for org.apache.commons.io FileUtils forceDeleteOnExit

List of usage examples for org.apache.commons.io FileUtils forceDeleteOnExit

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils forceDeleteOnExit.

Prototype

public static void forceDeleteOnExit(File file) throws IOException 

Source Link

Document

Schedules a file to be deleted when JVM exits.

Usage

From source file:com.opengamma.transport.TaxonomyGatheringFudgeMessageSenderTest.java

@Test(timeOut = 20000)
public void validFileLoadingOnStartup() throws IOException, InterruptedException {
    File tmpFile = File.createTempFile("TaxonomyGatheringFudgeMessageSenderTest_validFileLoadingOnStartup",
            ".properties");
    FileUtils.forceDelete(tmpFile);/*from w  ww .  j a v  a2s  . c  om*/
    FileUtils.forceDeleteOnExit(tmpFile);

    FudgeContext context = new FudgeContext();
    CollectingFudgeMessageReceiver collectingReceiver = new CollectingFudgeMessageReceiver();
    ByteArrayFudgeMessageReceiver fudgeReceiver = new ByteArrayFudgeMessageReceiver(collectingReceiver);
    DirectInvocationByteArrayMessageSender byteArraySender = new DirectInvocationByteArrayMessageSender(
            fudgeReceiver);
    ByteArrayFudgeMessageSender fudgeSender = new ByteArrayFudgeMessageSender(byteArraySender, context);
    TaxonomyGatheringFudgeMessageSender gatheringSender = new TaxonomyGatheringFudgeMessageSender(fudgeSender,
            tmpFile.getAbsolutePath(), context, 1000L);

    MutableFudgeMsg msg1 = context.newMessage();
    msg1.add("name1", 1);
    msg1.add("name2", 1);
    msg1.add("name3", 1);
    msg1.add("name1", 1);
    MutableFudgeMsg msg2 = context.newMessage();
    msg1.add("name4", msg2);
    msg2.add(14, 1);
    msg2.add("name5", "foo");

    gatheringSender.send(msg1);
    gatheringSender.waitForNextWrite();
    gatheringSender.getTimer().cancel();

    // Now reload the file.
    gatheringSender = new TaxonomyGatheringFudgeMessageSender(fudgeSender, tmpFile.getAbsolutePath(), context,
            5000L);
    assertTrue(gatheringSender.getCurrentTaxonomy().containsKey("name1"));
    assertTrue(gatheringSender.getCurrentTaxonomy().containsKey("name2"));
    assertTrue(gatheringSender.getCurrentTaxonomy().containsKey("name3"));
    assertTrue(gatheringSender.getCurrentTaxonomy().containsKey("name4"));
    assertTrue(gatheringSender.getCurrentTaxonomy().containsKey("name5"));
    assertEquals(5, gatheringSender.getCurrentTaxonomy().size());
}

From source file:com.epam.catgenome.controller.AbstractRESTController.java

/**
 * Joins back the file, transferred by chunks.
 *
 * @param multipart {@code Multipart} used to handle file chunk upload
 * @param id {@code Integer} identifies a specific file
 * @param fileName {@code String} original file name
 * @param chunk {@code int} current chunk number
 * @param chunks {@code int} overall number of chunks
 * @return {@code File} represents a reference on a temporary file that has been created
 * @throws IOException/*w w  w.  ja  v  a2 s .  c om*/
 */
protected File saveChunkedFile(MultipartFile multipart, Integer id, String fileName, int chunk, int chunks)
        throws IOException {
    File dst = new File(fileManager.getTempDir(), id + fileName);

    if (Objects.equals(chunk, chunks - 1)) {
        FileUtils.forceDeleteOnExit(dst);
    }

    try (InputStream inputStream = multipart.getInputStream();
            OutputStream out = dst.exists()
                    ? new BufferedOutputStream(new FileOutputStream(dst, true), BUF_SIZE)
                    : new BufferedOutputStream(new FileOutputStream(dst), BUF_SIZE);) {
        byte[] buffer = new byte[BUF_SIZE];
        int len = 0;
        while ((len = inputStream.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }
    }

    return dst;
}

From source file:com.splunk.shuttl.testutil.TUtilsFile.java

private static void createDirectory(File dir) {
    if (!dir.mkdir())
        TUtilsTestNG.failForException("Could not create directory: " + dir.getAbsolutePath(),
                new RuntimeException());
    try {/*w ww. j  a  v a  2s.  com*/
        FileUtils.forceDeleteOnExit(dir);
    } catch (IOException e) {
        TUtilsTestNG.failForException("Could not force delete on exit: " + dir.getAbsolutePath(),
                new RuntimeException(e));
    }
}

From source file:it.geosolutions.geonetwork.GeonetworkUpdateWithInfoTest.java

@Test
public void testUpdateMetadata() throws Exception {
    if (!runIntegrationTest())
        return;//from w  ww.j  a v  a2 s . com

    GNInsertConfiguration cfg = createDefaultInsertConfiguration();

    GNPrivConfiguration pcfg = new GNPrivConfiguration();

    pcfg.addPrivileges(GNPrivConfiguration.GROUP_GUEST, EnumSet.of(GNPriv.FEATURED));
    pcfg.addPrivileges(GNPrivConfiguration.GROUP_INTRANET, EnumSet.of(GNPriv.DYNAMIC, GNPriv.FEATURED));
    pcfg.addPrivileges(GNPrivConfiguration.GROUP_ALL, EnumSet.of(GNPriv.VIEW, GNPriv.DYNAMIC, GNPriv.FEATURED));
    pcfg.addPrivileges(2, EnumSet.allOf(GNPriv.class));

    File file = loadFile("metadata.xml");
    assertNotNull(file);

    GNClient client = createClientAndLogin();
    long id = client.insertMetadata(cfg, file);

    client.setPrivileges(id, pcfg);

    //=== using the custom service
    MetadataInfo info = null;

    // first try: the service is installed?
    try {
        info = GNMetadataGetInfo.get(client.getConnection(), gnServiceURL, id, false);
        LOGGER.info("Basic metadataInfo by id is " + info);
        assertNotNull(info);
        assertNull(info.getVersion());
        assertEquals(id, info.getId());
    } catch (GNServerException ex) {
        if (ex.getHttpCode() == 404) {
            LOGGER.error("metadata.info.get is not installed on GeoNetwork. Skipping test.");
            assumeTrue(false);
        } else
            throw ex;
    }

    info = GNMetadataGetInfo.get(client.getConnection(), gnServiceURL, info.getUuid(), false);
    LOGGER.info("Basic metadataInfo by UUID is " + info);
    assertNotNull(info);
    assertNull(info.getVersion());
    assertEquals(id, info.getId());

    info = GNMetadataGetInfo.get(client.getConnection(), gnServiceURL, id, true);
    LOGGER.info("MetadataInfo is " + info);

    assertNotNull(info);
    assertEquals(Integer.valueOf(2), info.getVersion()); // the md has just been created
    assertEquals(id, info.getId());

    Element md = client.get(id);
    //        XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
    //        outputter.output(md, System.out);

    final String UPDATED_TEXT = "Updated title";
    {
        Element chstr = getTitleElement(md);
        assertEquals("TEST GeoBatch Action: GeoNetwork", chstr.getText());
        chstr.setText(UPDATED_TEXT);
    }

    File tempFile = File.createTempFile("gnm_info_update", ".xml");
    FileUtils.forceDeleteOnExit(tempFile);
    XMLOutputter fileOutputter = new XMLOutputter(Format.getCompactFormat());
    FileUtils.writeStringToFile(tempFile, fileOutputter.outputString(md));

    GNMetadataUpdate.update(client.getConnection(), gnServiceURL, id, Integer.toString(info.getVersion()),
            tempFile);

    {
        Element md2 = client.get(id);
        Element chstr = getTitleElement(md2);
        assertEquals(UPDATED_TEXT, chstr.getText());
    }

    info = GNMetadataGetInfo.get(client.getConnection(), gnServiceURL, id, true);
    //        String version3 = GNMetadataGetVersion.get(client.getConnection(), gnServiceURL, id);
    LOGGER.info("New MetadataInfo is " + info);

    assertNotNull(info.getVersion());
    assertEquals(Integer.valueOf(4), info.getVersion()); // the md has been updated once

    // try bad version number
    try {
        GNMetadataUpdate.update(client.getConnection(), gnServiceURL, id, "9999", tempFile);
        fail("Bad version exception not trapped");
    } catch (GNServerException e) {
        LOGGER.info("Bad version number error trapped properly (" + e.getMessage() + ")");
    }

    //        client.deleteMetadata(id);
}

From source file:com.joyent.manta.client.MantaClientIT.java

@Test
public final void canCopyStreamToFileAndCloseWithoutErrors() throws IOException {
    final String name = UUID.randomUUID().toString();
    final String path = testPathPrefix + name;

    try (InputStream in = new RandomInputStream(8000)) {
        mantaClient.put(path, in);//w w  w.j  a va  2 s .  c  o m
    }

    File temp = File.createTempFile("object-" + name, ".data");
    FileUtils.forceDeleteOnExit(temp);

    InputStream in = mantaClient.getAsInputStream(path);
    FileOutputStream out = new FileOutputStream(temp);

    try {
        IOUtils.copyLarge(in, out);
    } finally {
        in.close();
        out.close();
    }
}

From source file:net.pms.formats.v2.SubtitleUtils.java

/**
 * Shift timing of subtitles in SSA/ASS or SRT format and converts charset to UTF8 if necessary
 *
 *
 * @param inputSubtitles Subtitles file in SSA/ASS or SRT format
 * @param timeShift  Time stamp value/*w w w .  j  a v a 2  s. c  o  m*/
 * @return Converted subtitles file
 * @throws IOException
 */
public static DLNAMediaSubtitle shiftSubtitlesTimingWithUtfConversion(final DLNAMediaSubtitle inputSubtitles,
        double timeShift) throws IOException {
    if (inputSubtitles == null) {
        throw new NullPointerException("inputSubtitles should not be null.");
    }
    if (!inputSubtitles.isExternal()) {
        throw new IllegalArgumentException("inputSubtitles should be external.");
    }
    if (isBlank(inputSubtitles.getExternalFile().getName())) {
        throw new IllegalArgumentException("inputSubtitles' external file should not have blank name.");
    }
    if (inputSubtitles.getType() == null) {
        throw new NullPointerException("inputSubtitles.getType() should not be null.");
    }
    if (!isSupportsTimeShifting(inputSubtitles.getType())) {
        throw new IllegalArgumentException(
                "inputSubtitles.getType() " + inputSubtitles.getType() + " is not supported.");
    }

    final File convertedSubtitlesFile = new File(configuration.getTempFolder(),
            getBaseName(inputSubtitles.getExternalFile().getName()) + System.currentTimeMillis() + ".tmp");
    FileUtils.forceDeleteOnExit(convertedSubtitlesFile);
    BufferedReader input;

    final boolean isSubtitlesCodepageForcedInConfigurationAndSupportedByJVM = isNotBlank(
            configuration.getSubtitlesCodepage()) && Charset.isSupported(configuration.getSubtitlesCodepage());
    final boolean isSubtitlesCodepageAutoDetectedAndSupportedByJVM = isNotBlank(
            inputSubtitles.getExternalFileCharacterSet())
            && Charset.isSupported(inputSubtitles.getExternalFileCharacterSet());
    if (isSubtitlesCodepageForcedInConfigurationAndSupportedByJVM) {
        input = new BufferedReader(new InputStreamReader(new FileInputStream(inputSubtitles.getExternalFile()),
                Charset.forName(configuration.getSubtitlesCodepage())));
    } else if (isSubtitlesCodepageAutoDetectedAndSupportedByJVM) {
        input = new BufferedReader(new InputStreamReader(new FileInputStream(inputSubtitles.getExternalFile()),
                Charset.forName(inputSubtitles.getExternalFileCharacterSet())));
    } else {
        input = new BufferedReader(
                new InputStreamReader(new FileInputStream(inputSubtitles.getExternalFile())));
    }
    final BufferedWriter output = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream(convertedSubtitlesFile), Charset.forName("UTF-8")));
    String line;
    double startTime;
    double endTime;

    try {
        if (SubtitleType.ASS.equals(inputSubtitles.getType())) {
            while ((line = input.readLine()) != null) {
                if (startsWith(line, "Dialogue:")) {
                    String[] timings = splitPreserveAllTokens(line, ",");
                    if (timings.length >= 3 && isNotBlank(timings[1]) && isNotBlank(timings[1])) {
                        startTime = convertSubtitleTimingStringToTime(timings[1]);
                        endTime = convertSubtitleTimingStringToTime(timings[2]);
                        if (startTime >= timeShift) {
                            timings[1] = convertTimeToSubtitleTimingString(startTime - timeShift,
                                    TimingFormat.ASS_TIMING);
                            timings[2] = convertTimeToSubtitleTimingString(endTime - timeShift,
                                    TimingFormat.ASS_TIMING);
                            output.write(join(timings, ",") + "\n");
                        } else {
                            continue;
                        }
                    } else {
                        output.write(line + "\n");
                    }
                } else {
                    output.write(line + "\n");
                }
            }
        } else if (SubtitleType.SUBRIP.equals(inputSubtitles.getType())) {
            int n = 1;
            while ((line = input.readLine()) != null) {
                if (contains(line, ("-->"))) {
                    startTime = convertSubtitleTimingStringToTime(line.substring(0, line.indexOf("-->") - 1));
                    endTime = convertSubtitleTimingStringToTime(line.substring(line.indexOf("-->") + 4));
                    if (startTime >= timeShift) {
                        output.write("" + (n++) + "\n");
                        output.write(convertTimeToSubtitleTimingString(startTime - timeShift,
                                TimingFormat.SRT_TIMING));
                        output.write(" --> ");
                        output.write(
                                convertTimeToSubtitleTimingString(endTime - timeShift, TimingFormat.SRT_TIMING)
                                        + "\n");

                        while (isNotBlank(line = input.readLine())) { // Read all following subs lines
                            output.write(line + "\n");
                        }
                        output.write("" + "\n");
                    }
                }
            }
        }
    } finally {
        if (output != null) {
            output.flush();
            output.close();
        }
        if (input != null) {
            input.close();
        }
    }

    final DLNAMediaSubtitle convertedSubtitles = new DLNAMediaSubtitle();
    convertedSubtitles.setExternalFile(convertedSubtitlesFile);
    convertedSubtitles.setType(inputSubtitles.getType());
    convertedSubtitles.setLang(inputSubtitles.getLang());
    convertedSubtitles.setFlavor(inputSubtitles.getFlavor());
    convertedSubtitles.setId(inputSubtitles.getId());
    return convertedSubtitles;
}

From source file:gov.nih.nci.firebird.commons.test.TestFileUtils.java

/**
 * Creates a temporary file which will be deleted upon JVM exit.
 *
 * @return temporary file/*from w  w  w  .j  a v  a 2  s  .  c om*/
 * @throws IOException if there is a problem creating a temporary file
 */
public static File createTemporaryFile() throws IOException {
    File file = File.createTempFile("temp_", ".tmp");
    file.createNewFile();
    FileWriter fileWriter = new FileWriter(file);
    fileWriter.append(SimpleDateFormat.getDateTimeInstance().format(new Date()));
    fileWriter.flush();
    fileWriter.close();
    FileUtils.forceDeleteOnExit(file);
    return file;
}

From source file:com.epam.catgenome.common.AbstractJUnitTest.java

protected File getResourceFileCopy(String resourcePath) throws IOException {
    Resource resource = context.getResource(resourcePath);
    final File tmp = new File(fileManager.getTempDir(), resource.getFilename());
    FileUtils.copyFile(resource.getFile(), tmp);
    FileUtils.forceDeleteOnExit(tmp);
    return tmp;/* ww  w . ja  v  a 2  s. c  om*/
}

From source file:com.splunk.shuttl.archiver.filesystem.hadoop.HadoopArchiveFileSystemTest.java

public void putFile_givenRelativeSrcFile_putsFile() throws IOException {
    File file = new File("relative-file");
    assertTrue(file.createNewFile());// www .  j a v a2s  .co m
    FileUtils.forceDeleteOnExit(file);

    assertNotEquals(file.getAbsolutePath(), file.getPath());
    File temp = createFilePath();
    hadoopArchiveFileSystem.getFileTransferer().put(file.getPath(), temp.getAbsolutePath(),
            createFilePath().getAbsolutePath());
    assertTrue(temp.exists());
}

From source file:com.joyent.manta.client.MantaClientIT.java

@Test
public final void canCreateStreamInOneThreadAndCloseInAnother() throws Exception {
    final String name = UUID.randomUUID().toString();
    final String path = testPathPrefix + name;

    try (InputStream in = new RandomInputStream(8000)) {
        mantaClient.put(path, in);//from  www . jav  a 2  s .  c  o  m
    }

    File temp = File.createTempFile("object-" + name, ".data");
    FileUtils.forceDeleteOnExit(temp);

    FileOutputStream out = new FileOutputStream(temp);

    Callable<InputStream> callable = () -> mantaClient.getAsInputStream(path);

    ExecutorService service = Executors.newFixedThreadPool(1);
    InputStream in = service.submit(callable).get();

    try {
        IOUtils.copyLarge(in, out);
    } finally {
        in.close();
        out.close();
    }
}