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:gobblin.runtime.job_catalog.FSJobCatalogHelperTest.java

@BeforeClass
public void setUp() throws IOException {
    this.jobConfigDir = java.nio.file.Files
            .createTempDirectory(String.format("gobblin-test_%s_job-conf", this.getClass().getSimpleName()))
            .toFile();//from   w ww .j  av a 2  s.c  o  m
    FileUtils.forceDeleteOnExit(this.jobConfigDir);
    this.subDir1 = new File(this.jobConfigDir, "test1");
    this.subDir11 = new File(this.subDir1, "test11");
    this.subDir2 = new File(this.jobConfigDir, "test2");

    this.subDir1.mkdirs();
    this.subDir11.mkdirs();
    this.subDir2.mkdirs();

    this.sysConfig = ConfigFactory.parseMap(ImmutableMap.<String, Object>builder()
            .put(ConfigurationKeys.JOB_CONFIG_FILE_GENERAL_PATH_KEY, this.jobConfigDir.getAbsolutePath())
            .build());
    ImmutableFSJobCatalog.ConfigAccessor cfgAccess = new ImmutableFSJobCatalog.ConfigAccessor(this.sysConfig);
    this.loader = new PullFileLoader(new Path(jobConfigDir.toURI()), FileSystem.get(new Configuration()),
            cfgAccess.getJobConfigurationFileExtensions(), PullFileLoader.DEFAULT_HOCON_PULL_FILE_EXTENSIONS);
    this.converter = new ImmutableFSJobCatalog.JobSpecConverter(new Path(this.jobConfigDir.toURI()),
            Optional.of(FSJobCatalog.CONF_EXTENSION));

    Properties rootProps = new Properties();
    rootProps.setProperty("k1", "a1");
    rootProps.setProperty("k2", "a2");
    // test-job-conf-dir/root.properties
    rootProps.store(new FileWriter(new File(this.jobConfigDir, "root.properties")), "");

    Properties jobProps1 = new Properties();
    jobProps1.setProperty("k1", "c1");
    jobProps1.setProperty("k3", "b3");
    jobProps1.setProperty("k6", "a6");
    // test-job-conf-dir/test1/test11.pull
    jobProps1.store(new FileWriter(new File(this.subDir1, "test11.pull")), "");

    Properties jobProps2 = new Properties();
    jobProps2.setProperty("k7", "a7");
    // test-job-conf-dir/test1/test12.PULL
    jobProps2.store(new FileWriter(new File(this.subDir1, "test12.PULL")), "");

    Properties jobProps3 = new Properties();
    jobProps3.setProperty("k1", "d1");
    jobProps3.setProperty("k8", "a8");
    jobProps3.setProperty("k9", "${k8}");
    // test-job-conf-dir/test1/test11/test111.pull
    jobProps3.store(new FileWriter(new File(this.subDir11, "test111.pull")), "");

    Properties props2 = new Properties();
    props2.setProperty("k2", "b2");
    props2.setProperty("k5", "a5");
    // test-job-conf-dir/test2/test.properties
    props2.store(new FileWriter(new File(this.subDir2, "test.PROPERTIES")), "");

    Properties jobProps4 = new Properties();
    jobProps4.setProperty("k5", "b5");
    // test-job-conf-dir/test2/test21.PULL
    jobProps4.store(new FileWriter(new File(this.subDir2, "test21.PULL")), "");
}

From source file:com.qulice.checkstyle.LicenseRule.java

/**
 * Make a file.//www.j a  v a2s  .  c om
 * @return The location of LICENSE.txt
 * @throws IOException If something wrong happens inside
 */
public File file() throws IOException {
    final File license = File.createTempFile("LICENSE", ".txt");
    FileUtils.forceDeleteOnExit(license);
    FileUtils.writeStringToFile(license, new Joined(this.eol, this.lines).asString(), StandardCharsets.UTF_8);
    if (this.directory != null) {
        this.makePackageInfo(this.directory);
    }
    return license;
}

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

/**
 * Transfers content of the given {@code Multipart} entity to a temporary file.
 *
 * @param multipart {@code Multipart} used to handle file uploads
 * @return {@code File} represents a reference on a file that has been created
 * from the given {@code Multipart}/*ww w . java2  s .c om*/
 * @throws IOException
 */
protected File transferToTempFile(final MultipartFile multipart) throws IOException {
    Assert.notNull(multipart);
    final File tmp = File.createTempFile(UUID.randomUUID().toString(), multipart.getOriginalFilename(),
            fileManager.getTempDir());
    multipart.transferTo(tmp);
    FileUtils.forceDeleteOnExit(tmp);
    return tmp;
}

From source file:com.michaelfitzmaurice.clocktwerk.TweetResponderTest.java

@Before
public void setup() throws Exception {

    persistenceDir = new File(System.getProperty("java.io.tmpdir"), "test-prevayler");
    FileUtils.forceMkdir(persistenceDir);
    FileUtils.forceDeleteOnExit(persistenceDir);
    lastSeenMentionId = new Long(new Random().nextInt(Integer.MAX_VALUE));
    HashMap<String, Long> prevayledMap = new HashMap<String, Long>();
    prevayledMap.put(LAST_MENTION_HANDLED_ID_KEY, lastSeenMentionId);
    prevayler = PrevaylerFactory.createPrevayler(prevayledMap, persistenceDir.getAbsolutePath());
    paging = new Paging(lastSeenMentionId);

    mockTweetDb = createNiceMock(TweetDatabase.class);
    mockTweetDb.getNextTweet();/*from  w  w w  .  j  ava2  s .  c  o  m*/
    expectLastCall().andReturn(replyText).anyTimes();
    replay(mockTweetDb);

    String twitterUserHandle = "Receiver";
    twitterUser = userFrom("Mr. " + twitterUserHandle, twitterUserHandle);

    String mentionerHandle = "MentionU";
    mentioningUser = userFrom("Miss " + mentionerHandle, mentionerHandle);

    mockTwitterClient = createStrictMock(Twitter.class);
    mockTwitterClient.getScreenName();
    expectLastCall().andReturn(twitterUserHandle);
    replay(mockTwitterClient);
}

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

@Test
public void testUpdateMetadata() throws Exception {
    if (!runIntegrationTest())
        return;/*from   w  w w . j  a  va  2  s.  c om*/

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

    String version = GNMetadataGetVersion.get(client.getConnection(), gnServiceURL, id);
    LOGGER.info("Version is " + version);

    assertNotNull(version);
    assertEquals("2", version); // the md has just been created

    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_update", ".xml");
    FileUtils.forceDeleteOnExit(tempFile);
    XMLOutputter fileOutputter = new XMLOutputter(Format.getCompactFormat());
    FileUtils.writeStringToFile(tempFile, fileOutputter.outputString(md));

    GNMetadataUpdate.update(client.getConnection(), gnServiceURL, id, version, tempFile);

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

    String version3 = GNMetadataGetVersion.get(client.getConnection(), gnServiceURL, id);
    LOGGER.info("Version is " + version3);

    assertNotNull(version3);
    assertEquals("4", version3); // 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:edu.cornell.med.icb.goby.modes.TestCompactToFastaMode.java

/**
 * Remove any test files.//from   w  w w . j ava2 s  .  co m
 * @throws IOException if any of the test files cannot be deleted
 */
@After
public void cleanup() throws IOException {
    final Iterator<File> files = testFiles.iterator();
    while (files.hasNext()) {
        final File file = files.next();
        if (file.exists()) {
            FileUtils.forceDeleteOnExit(file);
        }
        files.remove();
    }
}

From source file:dremel.common.AvroTest.java

@Test
public void shallowCopyTest() throws IOException {

    Schema inSchema = getSchema("OrecSchema.avpr.json");
    File inFile = getFile("OrecDremelPaperData.avro.json");
    Array<GenericRecord> inData = getData(inSchema, inFile, FileEncoding.JSON);
    File outFile = getTempFile("AvroTestCopyShallow.avro.json");
    FileUtils.deleteQuietly(outFile);/*from   www  . j  a va2 s. co  m*/

    Encoder encoder = new JsonEncoder(inSchema, new FileOutputStream(outFile));

    DatumWriter<Array<GenericRecord>> writer = new GenericDatumWriter<Array<GenericRecord>>(inSchema);

    writer.write(inData, encoder);

    encoder.flush();

    assertTrue("Copied files differs", FileUtils.contentEquals(inFile, outFile));

    // FileUtils.forceDelete(outFile);
    FileUtils.forceDeleteOnExit(outFile); // TODO fucking file hasn't being
    // deleted for some reason
}

From source file:it.geosolutions.geobatch.actions.geonetwork.GeonetworkActionDeleteTest.java

public void testRemoveMetadata() throws GNException, IOException {
    if (!runIntegrationTest)
        return;/*from   ww w. ja v  a  2 s  .co  m*/
    removeAllMetadata();

    GNClient client = createClientAndLogin();
    insertSome();

    // check that entries have been inserted properly
    {
        GNSearchRequest searchRequest = new GNSearchRequest(); // empty filter, get all entries
        GNSearchResponse searchResponse = client.search(searchRequest);
        assertEquals(12, searchResponse.getCount());
    }

    // create a request file
    Element request = new Element("request").addContent(new Element("any").setText("ACK99"));
    File requestFile = File.createTempFile("gbtest_request", ".xml");
    FileUtils.forceDeleteOnExit(requestFile);
    XMLOutputter outputter = new XMLOutputter(Format.getCompactFormat());
    FileUtils.writeStringToFile(requestFile, outputter.outputString(request));

    // check that the search works properly
    {
        GNSearchResponse searchResponse = client.search(requestFile);
        assertEquals(7, searchResponse.getCount());
    }

    GeonetworkDeleteConfiguration cfg = new GeonetworkDeleteConfiguration("test", "test", "test");
    cfg.setGeonetworkServiceURL(gnServiceUrl);
    cfg.setLoginUsername(gnUsername);
    cfg.setLoginPassword(gnPassword);

    // OK: run the operation now
    GNDelete gnd = new GNDelete(cfg);
    boolean ret = gnd.run(client, requestFile);
    if (ret)
        LOGGER.info("Clear procedure successful");
    else
        LOGGER.warn("Problems in clear procedure");

    // check that entries have been inserted properly
    {
        GNSearchRequest searchRequest = new GNSearchRequest(); // empty filter, get all entries
        GNSearchResponse searchResponse = client.search(searchRequest);
        assertEquals(12 - 7, searchResponse.getCount());
    }
    // check that the search works properly
    {
        GNSearchResponse searchResponse = client.search(requestFile);
        assertEquals(0, searchResponse.getCount());
    }

}

From source file:com.navercorp.pinpoint.bootstrap.AgentDirGenerator.java

public void remove() throws IOException {
    File file = new File(agentDirPath);
    try {/*from ww w.j a  v  a  2s .c o m*/
        FileUtils.deleteDirectory(file);
    } catch (IOException e) {
        logger.warn("unable to deleteDirectory. path:{}", file.getPath(), e);
        // Boot directory is not deleted.
        // Perhaps JarFile is not closed.
        FileUtils.forceDeleteOnExit(file);
    }
}

From source file:com.joyent.manta.client.crypto.SecretKeyUtilsTest.java

public void writeKeyToPath() throws IOException {
    File file = File.createTempFile("ciphertext-", ".data");
    FileUtils.forceDeleteOnExit(file);
    Path path = file.toPath();//from w w w . j a v  a 2 s . com

    SupportedCipherDetails cipherDetails = AesGcmCipherDetails.INSTANCE_128_BIT;
    byte[] keyBytes = SecretKeyUtils.generate(cipherDetails).getEncoded();
    SecretKey key = SecretKeyUtils.loadKey(keyBytes, cipherDetails);
    SecretKeyUtils.writeKeyToPath(key, path);

    SecretKey actual = SecretKeyUtils.loadKeyFromPath(path, cipherDetails);
    Assert.assertEquals(actual.getAlgorithm(), key.getAlgorithm());
    Assert.assertTrue(Arrays.equals(key.getEncoded(), actual.getEncoded()));
}