Example usage for java.io File deleteOnExit

List of usage examples for java.io File deleteOnExit

Introduction

In this page you can find the example usage for java.io File deleteOnExit.

Prototype

public void deleteOnExit() 

Source Link

Document

Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates.

Usage

From source file:gobblin.data.management.copy.recovery.RecoveryHelperTest.java

@Test
public void testPersistFile() throws Exception {

    String content = "contents";

    File stagingDir = Files.createTempDir();
    stagingDir.deleteOnExit();

    File file = new File(stagingDir, "file");
    OutputStream os = new FileOutputStream(file);
    IOUtils.write(content, os);/*w ww .  j  a v a2  s.  c  o  m*/
    os.close();

    Assert.assertEquals(stagingDir.listFiles().length, 1);

    State state = new State();
    state.setProp(RecoveryHelper.PERSIST_DIR_KEY, this.tmpDir.getAbsolutePath());
    state.setProp(ConfigurationKeys.DATA_PUBLISHER_FINAL_DIR, "/publisher");

    File recoveryDir = new File(RecoveryHelper.getPersistDir(state).get().toUri().getPath());

    FileSystem fs = FileSystem.getLocal(new Configuration());

    CopyableFile copyableFile = CopyableFile.builder(fs, new FileStatus(0, false, 0, 0, 0, new Path("/file")),
            new Path("/dataset"), CopyConfiguration.builder(fs, state.getProperties())
                    .preserve(PreserveAttributes.fromMnemonicString("")).build())
            .build();

    CopySource.setWorkUnitGuid(state, Guid.fromHasGuid(copyableFile));

    RecoveryHelper recoveryHelper = new RecoveryHelper(FileSystem.getLocal(new Configuration()), state);

    recoveryHelper.persistFile(state, copyableFile, new Path(file.getAbsolutePath()));

    Assert.assertEquals(stagingDir.listFiles().length, 0);
    Assert.assertEquals(recoveryDir.listFiles().length, 1);

    File fileInRecovery = recoveryDir.listFiles()[0];
    Assert.assertEquals(IOUtils.readLines(new FileInputStream(fileInRecovery)).get(0), content);

    Optional<FileStatus> fileToRecover = recoveryHelper.findPersistedFile(state, copyableFile,
            Predicates.<FileStatus>alwaysTrue());
    Assert.assertTrue(fileToRecover.isPresent());
    Assert.assertEquals(fileToRecover.get().getPath().toUri().getPath(), fileInRecovery.getAbsolutePath());

    fileToRecover = recoveryHelper.findPersistedFile(state, copyableFile, Predicates.<FileStatus>alwaysFalse());
    Assert.assertFalse(fileToRecover.isPresent());

}

From source file:com.aurel.track.util.PluginUtils.java

public static void extractArchiveFromClasspath(String dirInClasspath, String filter, File toDir) {
    URL urlDest;//  w  w w .j  ava 2 s .c  o  m
    File directory = null;
    //first try to get the template dir through class.getResource(path)
    urlDest = PluginUtils.class.getResource(dirInClasspath); // example: "/plugins"
    urlDest = PluginUtils.createValidFileURL(urlDest);
    if (urlDest != null) {
        LOGGER.info("Retrieving archive from " + urlDest.toString());
        directory = new File(urlDest.getPath());
        Long uuid = new Date().getTime();
        File tmpDir = new File(
                System.getProperty("java.io.tmpdir") + File.separator + "TrackTmp" + uuid.toString());
        if (!tmpDir.isDirectory()) {
            tmpDir.mkdir();
        }
        tmpDir.deleteOnExit();

        File[] files = null;

        if (filter != null && !"".equals(filter)) {
            files = directory.listFiles(new PluginUtils.Filter(filter));
        } else {
            files = directory.listFiles();
        }

        if (files == null || files.length == 0) {
            LOGGER.info("Problem extracting archive: No files.");
            return;
        }
        for (int index = 0; index < files.length; index++) {
            File zipFile = null;
            try {
                zipFile = files[index];
                LOGGER.info("Extracting archive from " + files[index].getName());
                unzipFileIntoDirectory(zipFile, toDir);
            } catch (Exception e) {
                LOGGER.error("Problem unzipping archive " + files[index].getName());
                LOGGER.debug(ExceptionUtils.getStackTrace(e));
            }
        }
    }
}

From source file:com.premiumminds.persistence.utils.HibernateEnversDDLTest.java

@Test
public void testCreateCommandWithFile() throws Exception {

    File file = File.createTempFile("updatedb", ".sql");
    file.deleteOnExit();

    String[] args = new String[] { "--create", "application-data-unit-export-test", file.getAbsolutePath() };

    HibernateEnversDDL.main(args);/*from  w ww  .  j a  va  2  s  .  c  o m*/

    assertTrue(outContent.toString().isEmpty());
    assertEquals("\n" + "    create table FooBar (\n" + "        id integer not null,\n"
            + "        bar integer not null,\n" + "        foo varchar(255),\n" + "        primary key (id)\n"
            + "    );\n" + "\n" + "    create table FooBar_AUD (\n" + "        id integer not null,\n"
            + "        REV integer not null,\n" + "        REVTYPE tinyint,\n" + "        bar integer,\n"
            + "        foo varchar(255),\n" + "        primary key (id, REV)\n" + "    );\n" + "\n"
            + "    create table REVINFO (\n" + "        REV integer generated by default as identity,\n"
            + "        REVTSTMP bigint,\n" + "        primary key (REV)\n" + "    );\n" + "\n"
            + "    alter table FooBar_AUD \n" + "        add constraint FK_hq6lvb9twe0idlwiwq4locy79 \n"
            + "        foreign key (REV) \n" + "        references REVINFO;\n" + "",
            IOUtils.toString(new FileReader(file)));
}

From source file:com.sap.prd.mobile.ios.mios.xcodeprojreader.jaxb.JAXBPlistParserTest.java

@Test
public void convertOpenStepToXML() throws Exception {
    JAXBPlistParser parser = new JAXBPlistParser();
    try {/*from  w ww.j a  v  a  2  s  .  c om*/
        parser.load(fileNameOpenStep);
        Assert.fail();
    } catch (javax.xml.bind.UnmarshalException e) {
        if (!(e.getCause().getClass() == SAXParseException.class)) {
            Assert.fail();
        }
    }

    File xmlProj = File.createTempFile("project", ".pbxproj");
    xmlProj.deleteOnExit();

    try {
        parser.convert(fileNameOpenStep, xmlProj.getAbsolutePath());
        Plist plist = parser.load(xmlProj.getAbsolutePath());
        assertEquals("1.0", plist.getVersion());
    } catch (UnsupportedOperationException ex) {
        // If we are running on a non Mac OS X system an UnsupportedOperationException is expected
        assertFalse("The convert function should only fail on non Mac OS X systems", SystemUtils.IS_OS_MAC_OSX);
        assertTrue("Wrong UnsupportedOperationException message", ex.getMessage().contains("Mac OS X"));
    }

}

From source file:com.amazonaws.codedeploy.AWSClients.java

private File createTestFile() throws IOException {
    File file = File.createTempFile("codedeploy-jenkins-plugin", ".txt");
    file.deleteOnExit();

    Writer writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
    writer.write("");
    writer.close();/*w  w w . j ava 2 s. com*/

    return file;
}

From source file:com.atlassian.jira.webtests.ztests.admin.TestImportExport.java

public void testXmlImportWithInvalidIndexDirectory() throws Exception {
    //By creating a file for the index path, we'll force the failure of the index path directory creation
    File indexPath = File.createTempFile("testXmlImportWithInvalidIndexDirectory", null);
    indexPath.createNewFile();/*from w  ww .j av  a 2 s .  com*/
    indexPath.deleteOnExit();

    final String absolutePath = indexPath.getAbsolutePath();
    safeModeImport("TestSetupInvalidIndexPath.xml", ImmutableMap.of("@@INDEX_PATH@@", absolutePath));
    tester.assertTextPresent(
            "Cannot write to index directory. Check that the application server and JIRA have permissions to write to: "
                    + absolutePath);
}

From source file:com.gooddata.gdc.DatastoreServiceAT.java

@Test(groups = "datastore", dependsOnMethods = "datastoreUpload")
public void datastoreDownload() throws Exception {
    DataStoreService dataStoreService = gd.getDataStoreService();

    final File file = File.createTempFile("file", ".txt");
    try (InputStream stream = dataStoreService.download(this.file)) {
        file.deleteOnExit();
        IOUtils.copy(stream, new FileOutputStream(file));
    } finally {//from w w  w .  j ava2  s .  c o m
        file.delete();
    }
}

From source file:eu.planets_project.tb.impl.serialization.ExperimentFileCache.java

/**
 * //from  w  w  w  .  j  a  v a2  s .  c  o  m
 */
public ExperimentFileCache() {
    if (cachedir != null)
        return;
    // Generate a temporary file and turn it into a directory:
    try {
        UUID dirname = UUID.randomUUID();
        File tmp = File.createTempFile(dirname.toString(), cacheExt);
        tmp.delete();
        tmp.mkdir();
        tmp.deleteOnExit();
        cachedir = tmp;
        log.info("Set up export cache: " + cachedir.getPath());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:annis.visualizers.component.AbstractDotVisualizer.java

public void writeOutput(VisualizerInput input, OutputStream outstream) {

    StringBuilder dot = new StringBuilder();

    try {/*ww  w.j  a v  a 2 s.  c om*/
        File tmpInput = File.createTempFile("annis-dot-input", ".dot");
        tmpInput.deleteOnExit();

        // write out input file
        StringBuilder dotContent = new StringBuilder();
        createDotContent(input, dotContent);
        FileUtils.writeStringToFile(tmpInput, dotContent.toString());

        // execute dot
        String dotPath = input.getMappings().getProperty("dotpath", "dot");
        ProcessBuilder pBuilder = new ProcessBuilder(dotPath, "-Tpng", tmpInput.getCanonicalPath());

        pBuilder.redirectErrorStream(false);
        Process process = pBuilder.start();

        InputStream inputFromProcess = process.getInputStream();
        for (int chr = inputFromProcess.read(); chr != -1; chr = inputFromProcess.read()) {
            outstream.write(chr);
        }

        inputFromProcess.close();

        int resultCode = process.waitFor();

        if (resultCode != 0) {
            InputStream stderr = process.getErrorStream();
            StringBuilder errorMessage = new StringBuilder();

            for (int chr = stderr.read(); chr != -1; chr = stderr.read()) {
                errorMessage.append((char) chr);
            }
            if (!"".equals(errorMessage.toString())) {
                log.error(
                        "Could not execute dot graph-layouter.\ncommand line:\n{}\n\nstderr:\n{}\n\nstdin:\n{}",
                        new Object[] { StringUtils.join(pBuilder.command(), " "), errorMessage.toString(),
                                dot.toString() });
            }
        }

        // cleanup
        if (!tmpInput.delete()) {
            log.warn("Cannot delete " + tmpInput.getAbsolutePath());
        }

    } catch (Exception ex) {
        log.error(null, ex);
    }
}

From source file:com.flexive.faces.beans.NewsletterProcessor.java

public static boolean sendMessage(FxPK messagePK) throws FxApplicationException {
    final ContentEngine ce = EJBLookup.getContentEngine();
    final FxContent message = ce.load(messagePK);
    final FxContent newsletter = ce.load(((FxReference) message.getValue("/NEWSLETTER")).getBestTranslation());
    final List<NewsletterSubscriber> subscribers = getSubscribers(newsletter.getPk());
    if (subscribers.size() == 0) {
        LOG.info("No subscribers for Message " + message.getCaption() + " (pk:" + messagePK + "), Newsletter: "
                + newsletter.getCaption() + " (pk:" + newsletter.getPk() + ")");
        return false;
    }//www  . ja va  2 s .c o m
    //build the message to send
    String[] attachments = new String[message.getValues("/ATTACHMENT").size()];
    int ai = 0;
    for (FxValue att : message.getValues("/ATTACHMENT")) {
        if (!(att instanceof FxBinary)) {
            LOG.warn("Attachment " + att + " is no FxBinary as expected!");
            continue;
        }
        FxBinary ba = (FxBinary) att;
        File ftmp = null;
        FileOutputStream fout;
        final BinaryDescriptor bdesc = ba.getBestTranslation();
        try {
            ftmp = File.createTempFile("NLAttachment", "bin");
            fout = new FileOutputStream(ftmp);
            bdesc.download(fout);
            fout.close();
            attachments[ai++] = FxMailUtils.encodeAttachment(bdesc.getMimeType(), bdesc.getName(), ftmp);
        } catch (IOException e) {
            LOG.error("Failed to download and encode attachment " + bdesc.getName());
            return false;
        } finally {
            if (ftmp != null)
                if (!ftmp.delete())
                    ftmp.deleteOnExit();
        }
    }

    final String plainContent = String.valueOf(message.getValue("/CONTENT_PLAIN").getBestTranslation());
    final String htmlContent = String.valueOf(message.getValue("/CONTENT_HTML").getBestTranslation());
    final String subject = String.valueOf(message.getValue("/TITLE").getBestTranslation());
    final String from = String.valueOf(message.getValue("/FROM").getBestTranslation());
    final String replyTo;
    if (message.containsValue("/REPLY_TO") && !message.getValue("/REPLY_TO").isEmpty())
        replyTo = String.valueOf(message.getValue("/REPLY_TO").getBestTranslation());
    else
        replyTo = "";
    FxContent protocol = ce.initialize("NEWSLETTER_PROTOCOL");
    protocol.setValue("/SENT", new FxDateTime(false, new Date(System.currentTimeMillis())));
    protocol.setValue("/NEWSLETTER", new FxReference(false, newsletter.getPk()));
    protocol.setValue("/MESSAGE", new FxReference(false, messagePK));
    final String cancellationURL = ((FxString) newsletter.getValue("/CANCELURL")).getDefaultTranslation();
    final String smtpServer = ((FxString) newsletter.getValue("/SMTPSERVER")).getDefaultTranslation();
    for (NewsletterSubscriber subs : subscribers) {
        boolean sendPlain = !subs.getPlainText().isEmpty() && subs.getPlainText().getBestTranslation();
        boolean sendHTML = !subs.getHtmlText().isEmpty() && subs.getHtmlText().getBestTranslation();
        final String email = subs.getEmail().getBestTranslation();
        if (!sendPlain && !sendHTML) {
            sendPlain = true;
            LOG.warn("Subscriber " + email + " wants neither plain nor html messages! Forcing plain!");
        }
        String plain = sendPlain ? parseContent(newsletter.getPk(), subs, plainContent, cancellationURL) : "";
        String html = sendHTML ? parseContent(newsletter.getPk(), subs, htmlContent, cancellationURL) : "";

        try {
            FxMailUtils.sendMail(smtpServer, subject, plain, html, email, "", "", from, replyTo, attachments);
            protocol.setValue("/SUCCESS", new FxReference(false, subs.getPk()));
            LOG.info("Sent message to " + email);
        } catch (FxApplicationException e) {
            LOG.warn("Failed to send message to " + email);
            protocol.setValue("/FAILURE", new FxReference(false, subs.getPk()));
        }
    }
    ce.save(protocol);
    return true;
}