Example usage for java.io File createTempFile

List of usage examples for java.io File createTempFile

Introduction

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

Prototype

public static File createTempFile(String prefix, String suffix) throws IOException 

Source Link

Document

Creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name.

Usage

From source file:fr.gael.ccsds.sip.archive.TarArchiveManager.java

/**
 * Produces TAR archive//from  w  w w  .  j a  v a 2 s.  c om
 */
@Override
public File copy(final File src, final File tar_file, final String dst) throws Exception {
    final ArchiveStreamFactory asf = new ArchiveStreamFactory();

    // Case of tar already exist: all the entries must be copied..
    if (tar_file.exists()) {
        final FileInputStream fis = new FileInputStream(tar_file);
        final ArchiveInputStream ais = asf.createArchiveInputStream(ArchiveStreamFactory.TAR, fis);

        final File tempFile = File.createTempFile("updateTar", "tar");
        final FileOutputStream fos = new FileOutputStream(tempFile);
        final ArchiveOutputStream aos = asf.createArchiveOutputStream(ArchiveStreamFactory.TAR, fos);

        // copy the existing entries
        ArchiveEntry nextEntry;
        while ((nextEntry = ais.getNextEntry()) != null) {
            aos.putArchiveEntry(nextEntry);
            IOUtils.copy(ais, aos);
            aos.closeArchiveEntry();
        }

        // create the new entry
        final TarArchiveEntry entry = new TarArchiveEntry(src, dst);
        entry.setSize(src.length());
        aos.putArchiveEntry(entry);
        final FileInputStream sfis = new FileInputStream(src);
        IOUtils.copy(sfis, aos);
        sfis.close();
        aos.closeArchiveEntry();

        aos.finish();
        ais.close();
        aos.close();
        fis.close();

        // copies the new file over the old
        tar_file.delete();
        tempFile.renameTo(tar_file);
        return tar_file;
    } else {
        final FileOutputStream fos = new FileOutputStream(tar_file);
        final ArchiveOutputStream aos = asf.createArchiveOutputStream(ArchiveStreamFactory.TAR, fos);

        // create the new entry
        final TarArchiveEntry entry = new TarArchiveEntry(src, dst);
        entry.setSize(src.length());
        aos.putArchiveEntry(entry);
        final FileInputStream sfis = new FileInputStream(src);
        IOUtils.copy(sfis, aos);
        sfis.close();
        aos.closeArchiveEntry();

        aos.finish();
        aos.close();
        fos.close();
    }
    return tar_file;
}

From source file:com.spring.tutorial.entitites.FileUploader.java

public String upload() throws IOException, ServletException, FacebookException {
    OutputStream output = null;/*from  w  ww.  j  a va 2s  .co m*/
    InputStream fileContent = null;
    final Part filePart;

    final File file;
    try {
        filePart = request.getPart("file");

        fileContent = filePart.getInputStream();

        MongoClient mongoClient = new MongoClient();
        mongoClient = new MongoClient();
        DB db = mongoClient.getDB("fou");

        char[] pass = "mongo".toCharArray();
        boolean auth = db.authenticate("admin", pass);

        file = File.createTempFile("fileToStore", "tmp");

        file.deleteOnExit();
        FileOutputStream fout = new FileOutputStream(file);

        int read = 0;
        byte[] bytes = new byte[1024];

        while ((read = fileContent.read(bytes)) != -1) {
            fout.write(bytes, 0, read);
        }

        GridFS gridFS = new GridFS(db, request.getSession().getAttribute("id") + "_files");
        GridFSInputFile gfsInputFile = gridFS.createFile(file);
        gfsInputFile.setFilename(filePart.getSubmittedFileName());
        gfsInputFile.save();

        DBCollection collection = db.getCollection(request.getSession().getAttribute("id") + "_files_meta");
        BasicDBObject metaDocument = new BasicDBObject();
        metaDocument.append("name", filePart.getSubmittedFileName());
        metaDocument.append("size", filePart.getSize());
        metaDocument.append("content-type", filePart.getContentType());
        metaDocument.append("file-id", gfsInputFile.getId());
        metaDocument.append("tags", request.getParameter("tags"));
        metaDocument.append("description", request.getParameter("description"));

        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

        metaDocument.append("last_modified", dateFormat.format(new Date()));

        collection.insert(metaDocument);

    } catch (Exception e) {
        return "message:" + e.getMessage();
    } finally {
        if (output != null) {
            output.close();
        }
        if (fileContent != null) {
            fileContent.close();
        }
    }

    return "success";
}

From source file:ar.com.fdvs.dj.output.FileReportWriter.java

public void writeTo(final HttpServletResponse _response) throws IOException, JRException {
    LOGGER.info("entering FileReportWriter.writeTo()");
    final File file = File.createTempFile("djreport", ".tmp");
    try {/*from   w ww  .  j a va 2s. c om*/
        exporter.setParameter(JRExporterParameter.OUTPUT_FILE, file);
        exporter.exportReport();
        _response.setContentLength((int) file.length());
        copyStreams(new FileInputStream(file), _response.getOutputStream());
    } finally {
        LOGGER.info("deleting " + file.getAbsolutePath());
        file.delete();
    }
}

From source file:eu.planets_project.services.utils.DigitalObjectUtilsTests.java

@Test
public void toFileDigitalObjectFile() throws IOException {
    DigitalObject object = new DigitalObject.Builder(Content.byReference(testZip)).build();
    File file = File.createTempFile("planets", null);
    DigitalObjectUtils.toFile(object, file);
    Assert.assertTrue(/*  ww  w. j  ava  2  s.  co  m*/
            IOUtils.contentEquals(object.getContent().getInputStream(), file.toURI().toURL().openStream()));
}

From source file:net.oletalk.hellospringboot.controller.HelloController.java

@PostMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes attributes) {
    // multipart file upload is slightly different

    String originalName = file.getOriginalFilename();
    // TODO any way of getting files uploaded without transferring to a temp file?
    //  It seems to want to know the complete path but MultipartFile doesn't give us that.
    String returnMsg;/*from   w  ww  . ja  va2  s . c om*/
    try {
        LOG.info("Creating temp file for upload");
        File tmpFile = File.createTempFile("s3upload", null);
        tmpFile.deleteOnExit();
        file.transferTo(tmpFile);
        returnMsg = s3service.uploadDocument("test/" + originalName, tmpFile);
        attributes.addFlashAttribute("message", returnMsg);
    } catch (IOException ioe) {
        LOG.error("Error creating temp file for upload:" + ioe.toString());
        attributes.addFlashAttribute("message", "Problem preparing upload to S3");
    }
    return "redirect:/hello/doc/";
}

From source file:com.cloudera.flume.handlers.avro.TestAvroDataFile.java

@Test
public void testAvroDataFileWriteRead() throws IOException, FlumeSpecException, InterruptedException {

    MemorySinkSource mem = MemorySinkSource.cannedData("test ", 5);

    // setup sink.
    File f = File.createTempFile("avrodata", ".avro");
    f.deleteOnExit();//www  . j  ava  2 s.  co m
    LOG.info("filename before escaping: " + f.getAbsolutePath());
    String custom = "text(\"" + StringEscapeUtils.escapeJava(f.getAbsolutePath()) + "\", \"avrodata\")";
    LOG.info("sink to parse: " + custom);
    EventSink snk = FlumeBuilder.buildSink(new Context(), custom);
    snk.open();
    mem.open();
    EventUtil.dumpAll(mem, snk);
    snk.close();

    mem.open();
    DatumReader<EventImpl> dtm = new ReflectDatumReader<EventImpl>(EventImpl.class);
    DataFileReader<EventImpl> dr = new DataFileReader<EventImpl>(f, dtm);

    EventImpl eout = null;
    for (Object o : dr) {
        eout = (EventImpl) o; // TODO (jon) fix AVRO -- this is gross
        Event expected = mem.next();
        Assert.assertTrue(Arrays.equals(eout.getBody(), expected.getBody()));
    }

}

From source file:com.milaboratory.core.io.sequence.fasta.FastaReaderTest.java

private static TestItem createTestData(long seed, int readsCount, boolean withWildcards) throws IOException {
    Well1024a rnd = new Well1024a(seed);

    File tempFile = File.createTempFile("temp" + seed, ".fasta");
    tempFile.deleteOnExit();//ww  w.  ja v a2s.c om
    FileOutputStream output = new FileOutputStream(tempFile);

    SingleRead[] reads = new SingleRead[readsCount];

    WildcardSymbol[] wildcards = NucleotideSequence.ALPHABET.getAllWildcards().toArray(new WildcardSymbol[0]);
    long id = 0;
    for (int i = 0; i < readsCount; ++i) {
        char[] seq = new char[50 + rnd.nextInt(100)];
        char[] seqExp = new char[seq.length];

        int qPointer = 0;
        byte[] qualityData = new byte[seq.length];
        Arrays.fill(qualityData, SequenceQuality.GOOD_QUALITY_VALUE);
        for (int j = 0; j < seq.length; ++j) {
            seq[j] = seqExp[j] = NucleotideSequence.ALPHABET.symbolFromCode((byte) rnd.nextInt(4));
            if (j != 0 && j != seq.length - 1 && ((4 * j) % seq.length == 0) && rnd.nextBoolean()) {
                //next line for sequence
                seq[j] = seqExp[j] = '\n';
                --qPointer;
            } else if (withWildcards && j % 5 == 0) {//wildcard
                WildcardSymbol wildcard = wildcards[rnd.nextInt(wildcards.length)];
                if (NucleotideSequence.ALPHABET.codeFromSymbol(wildcard.getSymbol()) == -1) {
                    seq[j] = wildcard.getSymbol();
                    seqExp[j] = NucleotideSequence.ALPHABET
                            .symbolFromCode(wildcard.getUniformlyDistributedSymbol(id ^ (j + qPointer)));//as used in FastaReader#getSequenceWithQuality(..)
                    qualityData[j + qPointer] = SequenceQuality.BAD_QUALITY_VALUE;
                }
            }
        }
        String description = ">seq" + i;
        String sequenceString = new String(seq);
        output.write(description.getBytes());
        output.write('\n');
        output.write(sequenceString.getBytes());
        output.write('\n');

        reads[i] = new SingleReadImpl(id,
                new NSequenceWithQuality(new NucleotideSequence(new String(seqExp).replace("\n", "")),
                        new SequenceQuality(Arrays.copyOfRange(qualityData, 0, seq.length + qPointer))),
                description.substring(1));
        ++id;
    }
    output.close();

    return new TestItem(tempFile, reads);
}

From source file:com.webpagebytes.cms.controllers.ExportImportController.java

public void importContent(HttpServletRequest request, HttpServletResponse response, String requestUri)
        throws WPBException {
    File tempFile = null;/*  w w w.  j  a va  2s  . co m*/
    try {
        ServletFileUpload upload = new ServletFileUpload();

        FileItemIterator iterator = upload.getItemIterator(request);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            if (!item.isFormField() && item.getFieldName().equals("file")) {
                InputStream is = item.openStream();
                tempFile = File.createTempFile("wpbImport", null);
                FileOutputStream fos = new FileOutputStream(tempFile);
                IOUtils.copy(is, fos);
                fos.close();

                adminStorage.stopNotifications();
                deleteAll();

                // because the zip file entries cannot be predicted we needto import in two step1
                // step 1 when we create the resource records
                // step 2 when we import the files, pages, modules and articles content
                InputStream is1 = new FileInputStream(tempFile);
                storageExporter.importFromZipStep1(is1);
                is1.close();

                InputStream is2 = new FileInputStream(tempFile);
                storageExporter.importFromZipStep2(is2);
                is2.close();

                org.json.JSONObject returnJson = new org.json.JSONObject();
                returnJson.put(DATA, "");
                httpServletToolbox.writeBodyResponseAsJson(response, returnJson, null);
            }
        }
    } catch (Exception e) {
        Map<String, String> errors = new HashMap<String, String>();
        errors.put("", WPBErrors.WB_CANNOT_IMPORT_PROJECT);
        httpServletToolbox.writeBodyResponseAsJson(response, jsonObjectConverter.JSONObjectFromMap(null),
                errors);
    } finally {
        if (tempFile != null) {
            if (!tempFile.delete()) {
                tempFile.deleteOnExit();
            }
        }

        adminStorage.startNotifications();
    }
}

From source file:net.sf.taverna.raven.launcher.TestPreLauncher.java

@Test
public void launchHelloWorld() throws Exception {
    System.setProperty("raven.launcher.app.name", "helloworld");
    System.setProperty("raven.launcher.app.main", "net.sf.taverna.raven.helloworld.HelloWorld");
    List<URL> urls = makeClassPath("TestPreLauncher-helloworld/");
    URLClassLoader classLoader = new URLClassLoader(urls.toArray(new URL[0]), getClass().getClassLoader());
    Thread.currentThread().setContextClassLoader(classLoader);
    classLoader.loadClass("org.apache.log4j.Logger");

    File outFile = File.createTempFile(getClass().getCanonicalName(), "test");
    outFile.deleteOnExit();/*from w w  w  .ja  v  a 2  s  . com*/

    PreLauncher.main(new String[] { outFile.getAbsolutePath() });
    String out = FileUtils.readFileToString(outFile, "utf8");
    assertEquals("Did not match expected output", "This is the test data.\n", out);
}

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

@Test(timeOut = 10000)
public void taxonomyGathering() throws IOException, InterruptedException {
    File tmpFile = File.createTempFile("TaxonomyGatheringFudgeMessageSenderTest_taxonomyGathering",
            ".properties");
    FileUtils.forceDelete(tmpFile);/*from ww w .j  a v a2 s  . com*/
    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);

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

    Properties props = new Properties();
    gatheringSender.waitForNextWrite();
    InputStream is = new FileInputStream(tmpFile);
    props.load(new BufferedInputStream(is));
    is.close();

    for (Map.Entry<Object, Object> propEntry : props.entrySet()) {
        Integer ordinal = gatheringSender.getCurrentTaxonomy().get(propEntry.getValue());
        assertEquals(ordinal.intValue(), Integer.parseInt((String) propEntry.getKey()));
    }
    assertEquals(5, props.size());
}