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:com.xpn.xwiki.tool.doc.DocumentUpdateMojoTest.java

/**
 * Test that a document loaded in memory from XML by the mojo then written back to XML does not lose any
 * information/is not affected by the process
 *//*w  w  w .  ja  v a2 s  .  c o  m*/
@Test
public void testXMLDocumentLoading() throws Exception {
    AttachMojo mojo = new AttachMojo();

    File resourceFile = new File(this.getClass().getResource("/Test/SampleWikiXMLDocument.input").toURI());

    String inputContent = IOUtils.toString(new FileReader(resourceFile));
    assertTrue(inputContent.contains("<class>"));

    XWikiDocument doc = mojo.loadFromXML(resourceFile);
    assertEquals(doc.getName(), "Install");

    File outputFile = File.createTempFile("output", "xml");
    mojo.writeToXML(doc, outputFile);

    String outputContent = IOUtils.toString(new FileReader(outputFile));

    // Check that we did not lose the class definition during the loading from XML/writing to XML process.
    assertTrue(outputContent.contains("<class>"));
}

From source file:com.playonlinux.webservice.HTTPDownloaderTest.java

@Test
public void testGet_DownloadFile_FileIsDownloaded() throws Exception {
    mockServer.when(request().withMethod("GET").withPath("/test.txt")).respond(response().withStatusCode(200)
            .withHeaders(new Header("Content-Type", "application/json")).withBody("Content file to download"));

    File temporaryFile = File.createTempFile("test", "txt");
    new HTTPDownloader(mockServerURL).get(temporaryFile);

    String fileContent = IOUtils.toString(new FileReader(temporaryFile));

    assertEquals("Content file to download", fileContent);
}

From source file:com.github.jankrause.javadoctools.exporters.DefinitionsAsHtmlExporter.java

public void export() throws IOException {
    Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
    File tmpFile = File.createTempFile("tmp_", ".tpl");

    FileOutputStream copyFileOutputStream = null;
    InputStream templateInputStream = null;

    cfg.setDirectoryForTemplateLoading(new File(tmpFile.getParent()));
    cfg.setDefaultEncoding("UTF-8");
    cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

    try {// ww w  . j a va  2  s. c  o m
        templateInputStream = DefinitionsAsHtmlExporter.class.getResourceAsStream("glossary.tpl");
        copyFileOutputStream = new FileOutputStream(tmpFile);
        IOUtils.copy(templateInputStream, copyFileOutputStream);
    } finally {
        IOUtils.closeQuietly(templateInputStream);
        IOUtils.closeQuietly(copyFileOutputStream);
    }

    Writer out = null;

    try {
        Map<Character, List<Definition>> sortedByFirstCharacter = DefinitionUtils
                .sortByFirstCharacter(definitions);
        Template temp = cfg.getTemplate(tmpFile.getName());

        out = new FileWriter(this.outputFile);

        temp.process(sortedByFirstCharacter, out);
    } catch (TemplateException templateEx) {
        throw new IOException(templateEx);
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:com.netscape.certsrv.client.PKIRESTProvider.java

@Override
public StreamingOutput readFrom(Class<StreamingOutput> type, Type genericType, Annotation[] annotations,
        MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
        throws IOException, WebApplicationException {

    final File file = File.createTempFile("PKIRESTProvider-", ".tmp");
    file.deleteOnExit();/*  ww w. java 2 s. com*/

    FileOutputStream out = new FileOutputStream(file);
    IOUtils.copy(entityStream, out);

    return new StreamingOutput() {

        @Override
        public void write(OutputStream out) throws IOException, WebApplicationException {
            FileInputStream in = new FileInputStream(file);
            IOUtils.copy(in, out);
        }

        public void finalize() {
            file.delete();
        }
    };
}

From source file:edu.um.umflix.stubs.UploadServletStub.java

protected List<FileItem> getFileItems(HttpServletRequest request) throws FileUploadException {
    if (error.equals("fileUpload"))
        new FileUploadException();

    File file = null;//from ww w  . j  av a 2  s.  c  om
    FileItem item1 = null;
    List<FileItem> list = new ArrayList<FileItem>();
    for (int i = 0; i < fields.length; i++) {
        FileItem item = Mockito.mock(FileItem.class);
        Mockito.when(item.isFormField()).thenReturn(true);
        Mockito.when(item.getFieldName()).thenReturn(fields[i]);
        if (fields[i].equals("premiere") || fields[i].equals("endDate") || fields[i].equals("startDate")) {
            Mockito.when(item.getString()).thenReturn("2013-06-01");
        } else {
            Mockito.when(item.getString()).thenReturn("11");
        }
        if (fields[i].equals("premiere") && error.equals("date"))
            Mockito.when(item.getString()).thenReturn("11");
        if (fields[i].equals("clipduration0")) {
            Mockito.when(item.getString()).thenReturn("01:22:01");
        }
        list.add(item);
    }
    try {
        file = File.createTempFile("aaaa", "aaaatest");
        item1 = Mockito.mock(FileItem.class);
        Mockito.when(item1.getInputStream()).thenReturn(new FileInputStream(file));

    } catch (IOException e) {
        e.printStackTrace();
    }

    list.add(item1);
    FileItem token = Mockito.mock(FileItem.class);
    Mockito.when(token.isFormField()).thenReturn(true);
    Mockito.when(token.getFieldName()).thenReturn("token");
    if (error.equals("token")) {
        Mockito.when(token.getString()).thenReturn("invalidToken");
    } else
        Mockito.when(token.getString()).thenReturn("validToken");

    list.add(token);

    return list;
}

From source file:eu.planets_project.services.datatypes.Content.java

/**
 * Create (streamed) content by reference, from an input stream.
 * @param inputStream The InputStream containing the value for the content.
 * @return A content instance with the specified value
 *///from   www . j a v a 2  s.c  o m
public static DigitalObjectContent byReference(final InputStream inputStream) {
    try {
        File tempFile = File.createTempFile("tempContent", "tmp");
        tempFile.deleteOnExit(); // TODO do we really want this here? 
        FileOutputStream out = new FileOutputStream(tempFile);
        IOUtils.copyLarge(inputStream, out);
        out.close();
        return new ImmutableContent(tempFile);
    } catch (IOException e) {
        e.printStackTrace();
    }
    throw new IllegalStateException("Could not create content for input stream: " + inputStream);
}

From source file:org.eclipse.epp.internal.logging.aeri.ui.log.ProblemsDatabaseUpdateJob.java

@Override
protected IStatus run(IProgressMonitor monitor) {
    SubMonitor progress = SubMonitor.convert(monitor, 3);
    progress.beginTask("Checking...", 1000);
    if (!server.isProblemsDatabaseOutdated()) {
        return Status.OK_STATUS;
    }/*from w  ww .ja  va2s. co m*/
    try {
        progress.subTask("Checking remote database");
        File tempRemoteIndexZip = File.createTempFile("problems-index", ".zip");
        int downloadStatus = server.downloadDatabase(tempRemoteIndexZip, progress);
        if (downloadStatus == HttpStatus.SC_NOT_MODIFIED) {
            return Status.OK_STATUS;
        } else if (downloadStatus != HttpStatus.SC_OK) {
            // Could not access problems.zip for whatever reason; switch off error reporting until restart.
            settings.setAction(SendAction.IGNORE);
            settings.setRememberSendAction(RememberSendAction.RESTART);
            log(INFO_SERVER_NOT_AVAILABLE);
            return Status.OK_STATUS;
        }

        progress.worked(1);
        File tempDir = Files.createTempDir();
        progress.subTask("Replacing local database");
        Zips.unzip(tempRemoteIndexZip, tempDir);
        service.replaceContent(tempDir);
        progress.worked(1);

        // cleanup files
        tempRemoteIndexZip.delete();
        FileUtils.deleteDirectory(tempDir);
        progress.worked(1);

        return Status.OK_STATUS;
    } catch (CancellationException e) {
        return Status.CANCEL_STATUS;
    } catch (Exception e) {
        log(WARN_INDEX_UPDATE_FAILED, e);
        return Status.OK_STATUS;
    } finally {
        monitor.done();
    }
}

From source file:edu.umn.msi.tropix.common.test.ZipFileCollectionTest.java

@Test(groups = "linux", expectedExceptions = IORuntimeException.class)
public void testException() throws IOException {
    final File tempFile = File.createTempFile("temp", "");
    tempFile.deleteOnExit();//from  w  ww. j av a 2s  .c  o  m
    this.copyResourceToFile(tempFile, "hello.zip");
    final Supplier<File> supplier = EasyMockUtils.createMockSupplier();
    org.easymock.EasyMock.expect(supplier.get()).andReturn(new File("/moo"));
    EasyMock.replay(supplier);
    new ZipFileCollection(tempFile, supplier);
}

From source file:com.tess4j.rest.Tess4jV1.java

@RequestMapping(value = "ocr/v0.9/upload", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public Status doOcrFile(@RequestBody final Image image) throws Exception {
    File tmpFile = File.createTempFile("ocr_image", image.getExtension());
    try {/* w w  w.  j av a2 s  .  c om*/
        FileUtils.writeByteArrayToFile(tmpFile, Base64.decodeBase64(image.getImage()));
        Tesseract tesseract = Tesseract.getInstance(); // JNA Interface Mapping
        String imageText = tesseract.doOCR(tmpFile);
        LOGGER.info("OCR Image Text = " + imageText);
    } catch (Exception e) {
        LOGGER.error("Exception while converting/uploading image: ", e);
        throw new TesseractException();
    } finally {
        tmpFile.delete();
    }
    return new Status("success");
}

From source file:com.playonlinux.core.python.PythonInstallerTest.java

@Test
public void testPythonInstaller_DefineLogContextWithMethod_ContextIsSet()
        throws IOException, PlayOnLinuxException {
    File temporaryScript = File.createTempFile("testDefineLogContext", "py");
    temporaryScript.deleteOnExit();/*from  w ww  .  ja va 2  s  .c om*/

    try (FileOutputStream fileOutputStream = new FileOutputStream(temporaryScript)) {

        fileOutputStream.write(
                ("#!/usr/bin/env/python\n" + "from com.playonlinux.framework.templates import Installer\n"
                        + "\n" + "class PlayOnLinuxBashInterpreter(Installer):\n" + "    def main(self):\n"
                        + "        pass\n" +

                        "    def title(self):\n" + "        return \"Mock Log Context\"\n").getBytes());
    }

    PythonInterpreter interpreter = defaultJythonInterpreterFactory.createInstance();
    interpreter.execfile(temporaryScript.getAbsolutePath());
    PythonInstaller<ScriptTemplate> pythonInstaller = new PythonInstaller<>(interpreter, ScriptTemplate.class);

    assertEquals("Mock Log Context", pythonInstaller.extractLogContext());
}