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:io.druid.data.input.impl.SqlFirehoseTest.java

@Before
public void setup() throws IOException {
    TEST_DIR = File.createTempFile(SqlFirehose.class.getSimpleName(), "testDir");
    FileUtils.forceDelete(TEST_DIR);/*from  w  w w  .  j av  a2  s.c  o m*/
    FileUtils.forceMkdir(TEST_DIR);

    final List<Map<String, Object>> inputTexts = ImmutableList.of(
            ImmutableMap.of("x", "foostring1", "timestamp", 2000),
            ImmutableMap.of("x", "foostring2", "timestamp", 2000));
    List<FileInputStream> testFile = new ArrayList<>();
    this.objectMapper = new ObjectMapper(new SmileFactory());
    int i = 0;
    for (Map m : inputTexts) {
        File file = new File(TEST_DIR, "test_" + i++);
        try (FileOutputStream fos = new FileOutputStream(file)) {
            final JsonGenerator jg = objectMapper.getFactory().createGenerator(fos);
            jg.writeStartArray();
            jg.writeObject(m);
            jg.writeEndArray();
            jg.close();
            testFile.add(new FileInputStream(file));
        }
    }

    this.fileList = testFile;
    parser = new MapInputRowParser(new TimeAndDimsParseSpec(new TimestampSpec("timestamp", "auto", null),
            new DimensionsSpec(DimensionsSpec.getDefaultSchemas(ImmutableList.of("x")), null, null)));

    this.inputs = inputTexts;
}

From source file:io.github.seanboyy.lotReset.json.ReadJSON.java

/**Read JSON file by using configuration file's JSON value,
 * which points to the file/*from  ww  w.  j a va 2 s.  c o  m*/
 * @param configLocation String which specifies the location of the config.properties file
 * @return <code>ArrayList&ltArrayList&ltLot&gt&gt lots</code> if no errors are encountered
 * @since 1.0 - Implemented config.properties in 2.0
 */
public static ArrayList<ArrayList<Lot>> read(String configLocation) {
    JSONParser parser = new JSONParser();
    URL url;
    File f;
    //lots is multidimensional in this format: {{fromLot,toLot},{fromLot,toLot},{fromLot,toLot},etc...}
    ArrayList<ArrayList<Lot>> lots = new ArrayList<ArrayList<Lot>>();
    Config config = ReadConfig.read(configLocation);
    final String[] alphabet = config.getAlpha();
    final String[] types = config.getType();
    final String[] worlds = config.getWorld();
    try {
        url = new URL(config.getJSON());
        InputStream in = url.openStream();
        f = File.createTempFile("temp", "json");
        FileWriter file = new FileWriter(f);
        Scanner input = new Scanner(in);
        while (input.hasNextLine()) {
            file.write(input.nextLine());
        }
        input.close();
        file.close();
        Object obj = parser.parse(new FileReader(f));
        JSONObject jsonObj = (JSONObject) obj;
        JSONObject regions = (JSONObject) jsonObj.get("Regions");
        for (String a : worlds) {
            for (String b : types) {
                for (String c : alphabet) {
                    for (int d = 1; d <= alphabet.length; ++d) {
                        String lotId = a + "-" + b + "-" + c + d;
                        String lotIdA = a + "_" + b + "-" + c + d;
                        String lotIdB = a + "-" + b + "_" + c + d;
                        String lotIdC = a + "_" + b + "_" + c + d;
                        JSONObject lot = (JSONObject) regions.get(lotId);
                        JSONObject lotA = (JSONObject) regions.get(lotIdA);
                        JSONObject lotB = (JSONObject) regions.get(lotIdB);
                        JSONObject lotC = (JSONObject) regions.get(lotIdC);
                        ArrayList<Lot> lotInfo = new ArrayList<Lot>();
                        if (lot != null) {
                            lotInfo.add(new Lot((long) lot.get("source_minX"), (long) lot.get("source_maxX"),
                                    (long) lot.get("source_minY"), (long) lot.get("source_maxY"),
                                    (long) lot.get("source_minZ"), (long) lot.get("source_maxZ"),
                                    (String) lot.get("source_file"), lotId));
                            lotInfo.add(new Lot((long) lot.get("dest_minX"), (long) lot.get("dest_maxX"),
                                    (long) lot.get("dest_minY"), (long) lot.get("dest_maxY"),
                                    (long) lot.get("dest_minZ"), (long) lot.get("dest_maxZ"),
                                    (String) lot.get("dest_file"), lotId));
                            lots.add(lotInfo);
                        }
                        if (lotA != null) {
                            lotInfo.add(new Lot((long) lotA.get("source_minX"), (long) lotA.get("source_maxX"),
                                    (long) lotA.get("source_minY"), (long) lotA.get("source_maxY"),
                                    (long) lotA.get("source_minZ"), (long) lotA.get("source_maxZ"),
                                    (String) lotA.get("source_file"), lotIdA));
                            lotInfo.add(new Lot((long) lotA.get("dest_minX"), (long) lotA.get("dest_maxX"),
                                    (long) lotA.get("dest_minY"), (long) lotA.get("dest_maxY"),
                                    (long) lotA.get("dest_minZ"), (long) lotA.get("dest_maxZ"),
                                    (String) lotA.get("dest_file"), lotIdA));
                            lots.add(lotInfo);
                        }
                        if (lotB != null) {
                            lotInfo.add(new Lot((long) lotB.get("source_minX"), (long) lotB.get("source_maxX"),
                                    (long) lotB.get("source_minY"), (long) lotB.get("source_maxY"),
                                    (long) lotB.get("source_minZ"), (long) lotB.get("source_maxZ"),
                                    (String) lotB.get("source_file"), lotIdB));
                            lotInfo.add(new Lot((long) lotB.get("dest_minX"), (long) lotB.get("dest_maxX"),
                                    (long) lotB.get("dest_minY"), (long) lotB.get("dest_maxY"),
                                    (long) lotB.get("dest_minZ"), (long) lotB.get("dest_maxZ"),
                                    (String) lotB.get("dest_file"), lotIdB));
                            lots.add(lotInfo);
                        }
                        if (lotC != null) {
                            lotInfo.add(new Lot((long) lotC.get("source_minX"), (long) lotC.get("source_maxX"),
                                    (long) lotC.get("source_minY"), (long) lotC.get("source_maxY"),
                                    (long) lotC.get("source_minZ"), (long) lotC.get("source_maxZ"),
                                    (String) lotC.get("source_file"), lotIdC));
                            lotInfo.add(new Lot((long) lotC.get("dest_minX"), (long) lotC.get("dest_maxX"),
                                    (long) lotC.get("dest_minY"), (long) lotC.get("dest_maxY"),
                                    (long) lotC.get("dest_minZ"), (long) lotC.get("dest_maxZ"),
                                    (String) lotC.get("dest_file"), lotIdC));
                            lots.add(lotInfo);
                        }
                    }
                }
            }
        }
    } catch (IOException e) {
        System.out.println("FILE ERROR FROM READING JSON");
        e.printStackTrace();
        return null;
    } catch (ParseException e) {
        System.out.println("PARSER ERROR FROM READING JSON");
        e.printStackTrace();
        return null;
    }
    return lots;
}

From source file:org.ocpsoft.redoculous.tests.asciidoc.AsciidocIncludeTest.java

License:asdf

@Before
public void before() throws IOException, GitAPIException {
    repository = File.createTempFile("redoc", "ulous-test");
    repository.delete();/*  w w  w.j  ava 2  s  . co m*/
    repository.mkdirs();
    File document = new File(repository, "document.asciidoc");
    document.createNewFile();
    File master = new File(repository, "master.asciidoc");
    master.createNewFile();

    Files.write(document, getClass().getClassLoader().getResourceAsStream("asciidoc/toc.asciidoc"));
    Files.write(master, "Somethingn, then...\n" + "include::document.asciidoc[]\n" + ASDF123);

    Git repo = Git.init().setDirectory(repository).call();
    repo.add().addFilepattern("document.asciidoc").call();
    repo.add().addFilepattern("master.asciidoc").call();
    repo.commit().setMessage("Initial commit.").call();
}

From source file:com.plugin.excel.xsd.node.store.impl.XsdNodeParserManagerImpl.java

public XsdNodeParserManagerImpl(String directoryLocation, boolean readFromResource, String ignoreDirectories) {

    try {// w w w. j av a  2s . c o m
        File parentDirectory = null;
        if (readFromResource) {

            /**
             * XSOMParser Parser parses relatives XSD only if it is provided in form of {@link File} and InputStream
             * throws NPE due to relative import XSDs.
             * 
             * We can't get File object pointer for any File in Jar. but we can traverse Jar file by file. So, we
             * will traverse jar, read as input stream, create a temp directory and copies all the file there and
             * get the File Object pointer.
             */
            parentDirectory = File.createTempFile(directoryLocation, "temp");
            parentDirectory.delete();
            parentDirectory.deleteOnExit();
            List<String> files = getXsdPaths(directoryLocation);
            parentDirectory = FileHelper.copyFolder(this.getClass(), files, parentDirectory, directoryLocation);

        } else {
            parentDirectory = new File(directoryLocation);
        }

        initializeParsers(parentDirectory, ignoreDirectories);
    } catch (Exception e) {
        // TODO: log
        String msg = "Couldn't parse XSDs from the location: " + directoryLocation + ", " + e.getMessage();
        throw new IllegalArgumentException(msg, e);
    }
}

From source file:com.microsoft.azure.hdinsight.common.StreamUtil.java

public static File getResourceFile(String resource) throws IOException {
    File file = null;
    URL res = streamUtil.getClass().getResource(resource);

    if (res.toString().startsWith("jar:")) {
        InputStream input = null;
        OutputStream out = null;/*from   w  w w  .j a va 2  s  . c  om*/

        try {
            input = streamUtil.getClass().getResourceAsStream(resource);
            file = File.createTempFile(String.valueOf(new Date().getTime()), ".tmp");
            out = new FileOutputStream(file);

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

            while ((read = input.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
        } finally {
            if (input != null) {
                input.close();
            }

            if (out != null) {
                out.flush();
                out.close();
            }

            if (file != null) {
                file.deleteOnExit();
            }
        }

    } else {
        file = new File(res.getFile());
    }

    return file;
}

From source file:com.ibm.watson.developer_cloud.retrieve_and_rank.v1.util.ZipUtils.java

/**
 * Creates the empty ZIP file.//from w ww.j  a  va 2  s  .  c  om
 * 
 * @param prefix file name prefix
 * @return the file
 */
public static File createEmptyZipFile(String prefix) {
    try {
        return File.createTempFile(prefix, ".zip");
    } catch (final IOException e) {
        throw new RuntimeException(MSGS.format(ERROR_CREATING_ZIP_1, prefix + ".zip"), e);
    }
}

From source file:com.googlecode.fannj.FannTrainerTest.java

@Test
public void testTrainingQuickprop() throws IOException {

    File temp = File.createTempFile("fannj_", ".tmp");
    temp.deleteOnExit();/*  w  w w.  ja  v a 2s.  c  om*/
    IOUtils.copy(this.getClass().getResourceAsStream("xor.data"), new FileOutputStream(temp));

    List<Layer> layers = new ArrayList<Layer>();
    layers.add(Layer.create(2));
    layers.add(Layer.create(3, ActivationFunction.FANN_SIGMOID_SYMMETRIC));
    layers.add(Layer.create(1, ActivationFunction.FANN_SIGMOID_SYMMETRIC));

    Fann fann = new Fann(layers);
    Trainer trainer = new Trainer(fann);

    trainer.setTrainingAlgorithm(TrainingAlgorithm.FANN_TRAIN_QUICKPROP);

    float desiredError = .001f;
    float mse = trainer.train(temp.getPath(), 500000, 1000, desiredError);
    assertTrue("" + mse, mse <= desiredError);
}

From source file:com.elasticgrid.storage.amazon.s3.S3Storable.java

public File asFile() throws IOException {
    File f = File.createTempFile("elastic-grid-storable", getName());
    InputStream input = null;//  w  w w.j a  va2s.  co m
    OutputStream output = null;
    try {
        input = asInputStream();
        output = new BufferedOutputStream(new FileOutputStream(f));
        IOUtils.copy(input, output);
    } finally {
        IOUtils.closeQuietly(input);
        IOUtils.closeQuietly(output);
    }
    return f;
}

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  www  .j  a va  2s .  co m
    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.sangupta.jerry.util.ZipUtils.java

/**
 * Read a given file from the ZIP file and store it in a temporary file. The
 * temporary file is set to be deleted on exit of application.
 * //  w w w. j av a2s.  c om
 * @param zipFile
 *            the zip file from which the file needs to be read
 * 
 * @param fileName
 *            the name of the file that needs to be extracted
 * 
 * @return the {@link File} handle for the extracted file in the temp
 *         directory
 * 
 * @throws IllegalArgumentException
 *             if the zipFile is <code>null</code> or the fileName is
 *             <code>null</code> or empty.
 */
public static File readFileFromZip(File zipFile, String fileName) throws FileNotFoundException, IOException {
    if (zipFile == null) {
        throw new IllegalArgumentException("zip file to extract from cannot be null");
    }

    if (AssertUtils.isEmpty(fileName)) {
        throw new IllegalArgumentException("the filename to extract cannot be null/empty");
    }

    LOGGER.debug("Reading {} from {}", fileName, zipFile.getAbsolutePath());

    ZipInputStream stream = null;
    BufferedOutputStream outStream = null;
    File tempFile = null;

    try {
        byte[] buf = new byte[1024];
        stream = new ZipInputStream(new FileInputStream(zipFile));
        ZipEntry entry;
        while ((entry = stream.getNextEntry()) != null) {
            String entryName = entry.getName();
            if (entryName.equals(fileName)) {
                tempFile = File.createTempFile(FilenameUtils.getName(entryName),
                        FilenameUtils.getExtension(entryName));
                tempFile.deleteOnExit();

                outStream = new BufferedOutputStream(new FileOutputStream(tempFile));
                int readBytes;
                while ((readBytes = stream.read(buf, 0, 1024)) > -1) {
                    outStream.write(buf, 0, readBytes);
                }

                stream.close();
                outStream.close();

                return tempFile;
            }
        }
    } finally {
        IOUtils.closeQuietly(stream);
        IOUtils.closeQuietly(outStream);
    }

    return tempFile;
}