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.mobiaware.util.UploadHelpers.java

public static File createUploadFile(final HttpServletRequest request) {
    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
    fileItemFactory.setSizeThreshold(THRESHOLD_SIZE);
    fileItemFactory.setRepository(FileUtils.getTempDirectory());

    ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
    servletFileUpload.setFileSizeMax(MAX_FILE_SIZE);
    servletFileUpload.setSizeMax(REQUEST_SIZE);

    File file = null;/*w ww  . jav a2s  .  c  om*/

    try {
        FileItemIterator fileItemIterator = servletFileUpload.getItemIterator(request);
        while (fileItemIterator.hasNext()) {
            FileItemStream fileItem = fileItemIterator.next();

            if (fileItem.isFormField()) {
                // ignore
            } else {
                file = File.createTempFile("liim_", null);

                InputStream is = new BufferedInputStream(fileItem.openStream());
                FileUtils.copyInputStreamToFile(is, file);
            }
        }
    } catch (IOException e) {
        LOG.error(Throwables.getStackTraceAsString(e));
    } catch (FileUploadException e) {
        LOG.error(Throwables.getStackTraceAsString(e));
    }

    return file;
}

From source file:co.com.realtech.mariner.util.jsf.file.FileDownloader.java

/**
 * Crea el informe seleccionado en formato excel.
 *
 * @param colHeaders//from   ww  w  . j  a v a2 s.c o m
 * @param datos
 * @param nombreHoja
 * @param nombreArchivo
 * @param contexto
 * @param descargar
 * @return 
 * @throws java.lang.Exception
 */
public File construirExcel(List<String> colHeaders, List<Object> datos, String nombreHoja, String nombreArchivo,
        FacesContext contexto, boolean descargar) throws Exception {
    File tempFile = null;
    try {
        ResultSetToExcel rste = new ResultSetToExcel(nombreHoja);
        tempFile = File.createTempFile("reporteGeneral", ".xlsx");
        OutputStream os = new FileOutputStream(tempFile);
        rste.generate(os, datos, colHeaders);
        if (descargar) {
            InputStream is = new FileInputStream(tempFile);
            byte[] bytes;
            bytes = IOUtils.toByteArray(is);
            descargarArchivo(contexto, bytes, nombreArchivo, "xlsx");
        }
    } catch (Exception e) {
        throw e;
    }
    return tempFile;
}

From source file:gov.nih.nci.cabig.caaers.rules.business.service.CaaersRulesEngineServiceIntegrationTest.java

public void testImportRules() throws Exception {

    InputStream in = RuleUtil.getResouceAsStream("sae_reporting_rules_sponsor_org_ctep.xml");
    String xml = RuleUtil.getFileContext(in);
    System.out.println(xml);/*from  w  w  w  .j  ava 2  s .c  o  m*/
    File f = File.createTempFile("r_" + System.currentTimeMillis(), "sae.xml");
    System.out.println(f.getAbsolutePath());
    FileWriter fw = new FileWriter(f);
    IOUtils.write(xml, fw);
    IOUtils.closeQuietly(fw);
    assertTrue(f.exists());

    assertTrue(findRuleSets().isEmpty());

    service.importRules(f.getAbsolutePath());
    f.delete();
    List<RuleSet> ruleSets = findRuleSets();
    assertFalse(ruleSets.isEmpty());

    RuleSet rs = ruleSets.get(0);

    assertTrue(rs.isEnabled());

    String xml2 = service.exportRules(rs.getRuleBindURI());

    assertNotNull(xml2);

    f = File.createTempFile("r_" + System.currentTimeMillis(), "sae.xml");
    fw = new FileWriter(f);
    IOUtils.write(xml, fw);
    IOUtils.closeQuietly(fw);
    assertTrue(f.exists());

    List<String> outList = service.importRules(f.getAbsolutePath());
    f.delete();
    assertEquals(rs.getRuleBindURI(), outList.get(0));

    String xml3 = service.exportRules(rs.getRuleBindURI());
    assertNotNull(xml3);

}

From source file:com.snaker.ocr.TesseractOCR.java

@Override
public String recognize(byte[] image) throws OCRException {
    if (tessExecutable == null) {
        tessExecutable = getDefaultTessExecutable();
    }/*from   ww  w.j ava2 s. c o  m*/

    File source = null;
    File dest = null;
    try {
        String prefix = System.nanoTime() + "";
        source = File.createTempFile(prefix, ".jpg");
        DataOutputStream dos = new DataOutputStream(new FileOutputStream(source));
        dos.write(image);
        dos.flush();
        dos.close();
        String sourceFileName = source.getAbsolutePath();
        Process p = Runtime.getRuntime().exec(String.format("%s %s %s -l eng nobatch digits", tessExecutable,
                sourceFileName, sourceFileName));
        String destFileName = sourceFileName + ".txt";
        dest = new File(destFileName);
        int result = p.waitFor();
        if (result == 0) {
            BufferedReader in = new BufferedReader(new FileReader(dest));
            StringBuilder sb = new StringBuilder();
            String str;
            while ((str = in.readLine()) != null) {
                sb.append(str).append("\n");
            }
            in.close();
            return sb.toString().trim();
        } else {
            String msg;
            switch (result) {
            case 1:
                msg = "Errors accessing files. There may be spaces in your image's filename.";
                break;
            case 29:
                msg = "Cannot recognize the image or its selected region.";
                break;
            case 31:
                msg = "Unsupported image format.";
                break;
            default:
                msg = "Errors occurred.";
            }
            throw new OCRException(msg);
        }
    } catch (IOException e) {
        throw new OCRException("recognize failed", e);
    } catch (InterruptedException e) {
        logger.error("interrupted", e);
    } finally {
        if (source != null) {
            source.delete();
        }
        if (dest != null) {
            dest.delete();
        }
    }
    return null;
}

From source file:com.ikon.util.FileUtils.java

/**
 * Creates a temporal and unique directory
 * /*  ww  w .j a v a2 s  .c  o m*/
 * @throws IOException If something fails.
 */
public static File createTempDir() throws IOException {
    File tmpFile = File.createTempFile("okm", null);

    if (!tmpFile.delete())
        throw new IOException();
    if (!tmpFile.mkdir())
        throw new IOException();
    return tmpFile;
}

From source file:com.netflix.niws.client.http.SecureRestClientKeystoreTest.java

@Test
public void testGetKeystoreWithClientAuth() throws Exception {

    // jks format
    byte[] dummyTruststore = Base64.decode(SecureGetTest.TEST_TS1);
    byte[] dummyKeystore = Base64.decode(SecureGetTest.TEST_KS1);

    File tempKeystore = File.createTempFile(this.getClass().getName(), ".keystore");
    File tempTruststore = File.createTempFile(this.getClass().getName(), ".truststore");

    FileOutputStream keystoreFileOut = new FileOutputStream(tempKeystore);
    try {//from   w w w. ja  va  2 s  .c  o  m
        keystoreFileOut.write(dummyKeystore);
    } finally {
        keystoreFileOut.close();
    }

    FileOutputStream truststoreFileOut = new FileOutputStream(tempTruststore);
    try {
        truststoreFileOut.write(dummyTruststore);
    } finally {
        truststoreFileOut.close();
    }

    AbstractConfiguration cm = ConfigurationManager.getConfigInstance();

    String name = this.getClass().getName() + ".test1";

    String configPrefix = name + "." + "ribbon";

    cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsSecure, "true");
    cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsClientAuthRequired, "true");
    cm.setProperty(configPrefix + "." + CommonClientConfigKey.KeyStore, tempKeystore.getAbsolutePath());
    cm.setProperty(configPrefix + "." + CommonClientConfigKey.KeyStorePassword, "changeit");
    cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStore, tempTruststore.getAbsolutePath());
    cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStorePassword, "changeit");

    RestClient client = (RestClient) ClientFactory.getNamedClient(name);

    KeyStore keyStore = client.getKeyStore();

    Certificate cert = keyStore.getCertificate("ribbon_key");

    assertNotNull(cert);

}

From source file:edu.unc.lib.dl.util.ZipFileUtil.java

/**
 * Create a temporary directory, unzip the contents of the given zip file to
 * it, and return the directory.//from w  w  w.  j  av  a  2 s .co  m
 * 
 * If anything goes wrong during this process, clean up the temporary
 * directory and throw an exception.
 */
public static File unzipToTemp(InputStream zipStream) throws IOException {
    // get a temporary directory to work with
    File tempDir = File.createTempFile("ingest", null);
    tempDir.delete();
    tempDir.mkdir();
    tempDir.deleteOnExit();
    log.debug("Unzipping to temporary directory: " + tempDir.getPath());
    try {
        unzip(zipStream, tempDir);
        return tempDir;
    } catch (IOException e) {
        // attempt cleanup, then re-throw
        org.apache.commons.io.FileUtils.deleteDirectory(tempDir);
        throw e;
    }
}

From source file:net.sf.taverna.raven.helloworld.TestHelloWorld.java

@Test
public void mainWithFilename() throws IOException {
    File tmpFile = File.createTempFile(getClass().getCanonicalName(), "test");
    tmpFile.deleteOnExit();//  ww  w.ja  v a 2 s  . c o m
    assertTrue(tmpFile.isFile());
    String fileContent = FileUtils.readFileToString(tmpFile, "utf8");
    assertEquals("File was not empty", "", fileContent);

    HelloWorld.main(new String[] { tmpFile.getAbsolutePath() });
    fileContent = FileUtils.readFileToString(tmpFile, "utf8");
    assertEquals("File did not contain expected output", HelloWorld.TEST_DATA, fileContent);
}

From source file:li.poi.services.docx.resource.MailMerge.java

@Path("/test")
@GET/*  w  ww.j  ava 2  s .com*/
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public MailMergeResponse test() throws Docx4JException {
    MailMergeResponse mail = new MailMergeResponse();
    File tmp = null;
    try {
        WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
        wordMLPackage.getMainDocumentPart().addParagraphOfText("Hello Word!");

        tmp = File.createTempFile("document", "docx");
        wordMLPackage.save(tmp);
        mail.setDocument(Base64.encodeBase64String(IOUtils.toByteArray(new FileInputStream(tmp))));
        mail.setError("success");
        mail.setDocumentName(tmp.getName());
    } catch (IOException e) {
        e.printStackTrace();
        mail.setError("error... " + e.getMessage());
    } finally {
        if (tmp != null) {
            boolean deleted = tmp.delete();
            if (!deleted) {
                log.warn("file not deleted " + tmp.getAbsolutePath());
            }
        }
    }

    return mail;
}

From source file:atg.tools.dynunit.test.util.FileUtil.java

public static File newTempFile() throws IOException {
    logger.entry();//from w w  w.ja  va2  s. com
    final File tempFile = File.createTempFile("dynunit-", null);
    tempFile.deleteOnExit();
    return logger.exit(tempFile);
}