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:com.hortonworks.registries.util.HdfsFileStorageTest.java

@Test
public void testUploadJarWithDir() throws Exception {
    Map<String, String> config = new HashMap<>();
    config.put(HdfsFileStorage.CONFIG_FSURL, "file:///");
    config.put(HdfsFileStorage.CONFIG_DIRECTORY, HDFS_DIR);
    fileStorage.init(config);//ww  w.ja v a2  s. c  om

    File file = File.createTempFile("test", ".tmp");
    file.deleteOnExit();

    List<String> lines = Arrays.asList("test-line-1", "test-line-2");
    Files.write(file.toPath(), lines, Charset.forName("UTF-8"));
    String jarFileName = "test.jar";

    fileStorage.deleteFile(jarFileName);

    fileStorage.uploadFile(new FileInputStream(file), jarFileName);

    InputStream inputStream = fileStorage.downloadFile(jarFileName);
    List<String> actual = IOUtils.readLines(inputStream);
    Assert.assertEquals(lines, actual);
}

From source file:org.trustedanalytics.utils.hdfs.HdfsConfigFactory.java

private String createTmpDir() {
    File tmpFolder = Files.createTempDir();
    tmpFolder.deleteOnExit();
    return tmpFolder.getAbsolutePath();
}

From source file:edu.ur.ir.file.DefaultTemporaryFileCreator.java

/**
 * Creates a temporary file and set the file to be deleted on exit.
 * //from  www . j  a  va 2 s .co m
 * @see edu.ur.ir.file.TemporaryFileCreator#createTemporaryFile(java.lang.String)
 */
public File createTemporaryFile(String extension) throws IOException {
    File tempDir = new File(temporaryDirectory);

    if (!tempDir.exists()) {
        FileUtils.forceMkdir(tempDir);
    }

    if (!tempDir.isDirectory()) {
        throw new RuntimeException("Temp directory is not a directory " + tempDir.getAbsolutePath());
    }

    if (!tempDir.canWrite()) {
        throw new RuntimeException("Could not write to directory " + tempDir.getAbsolutePath());
    }

    if (!tempDir.canRead()) {
        throw new RuntimeException("Could not read temp directory " + tempDir.getAbsolutePath());
    }
    File f = File.createTempFile("ur-temp", extension, tempDir);
    f.deleteOnExit();
    return f;
}

From source file:org.canova.cli.driver.TestCommandLineInterfaceDriver.java

@Test
public void testMainCLIDriverEntryPoint() throws Exception {

    String[] args = { "vectorize", "-conf", "src/test/resources/csv/confs/unit_test_conf.txt" };

    CommandLineInterfaceDriver.main(args);

    String outputFile = "csv/data/uci_iris_sample.txt";

    ArrayList<String> vectors = new ArrayList<>();

    Map<String, Integer> labels = new HashMap<>();
    List<String> lines = FileUtils.readLines(new ClassPathResource(outputFile).getFile());
    for (String line : lines) {
        // process the line.
        if (!line.trim().isEmpty()) {
            vectors.add(line);//w w  w . j  av a2s. c o m

            String parts[] = line.split(" ");
            String key = parts[0];
            if (labels.containsKey(key)) {
                Integer count = labels.get(key);
                count++;
                labels.put(key, count);
            } else {
                labels.put(key, 1);
            }

        }
    }

    assertEquals(12, vectors.size());
    assertEquals(12, labels.size());
    File f = new File("/tmp/iris_unit_test_sample.txt");
    f.deleteOnExit();
    assertTrue(f.exists());

}

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();
    this.copyResourceToFile(tempFile, "hello.zip");
    final Supplier<File> supplier = EasyMockUtils.createMockSupplier();
    org.easymock.EasyMock.expect(supplier.get()).andReturn(new File("/moo"));
    EasyMock.replay(supplier);// w ww .  j  a  v  a2 s . co m
    new ZipFileCollection(tempFile, supplier);
}

From source file:eu.europa.ejusticeportal.dss.applet.model.action.SavePdfActionTest.java

/**
 * Test the doExec method for SavePdfAction
 *//*from w  w  w  .  j a v a2  s .c om*/
@Test
public void testDoExec() {
    FileInputStream fis = null;
    FileInputStream result = null;
    SavePdfAction instance;
    try {
        fis = new FileInputStream("src/test/resources/hello-world.pdf");
        byte[] pdf = (IOUtils.toByteArray(fis));
        instance = new SavePdfAction(pdf, null);
        instance.exec();

        File f = File.createTempFile("test", ".pdf");
        f.deleteOnExit();
        instance = new SavePdfAction(pdf, f);
        instance.exec();
        assertNotNull(f);
        assertTrue(f.exists());
        assertTrue(f.canRead());
        assertTrue(f.canWrite());

        result = new FileInputStream(f);
        byte[] resultPdf = (IOUtils.toByteArray(result));
        assertTrue(resultPdf.length > 0);

    } catch (FileNotFoundException ex) {
        fail("Hello-world.pdf is not available.");
    } catch (IOException ex) {
        fail("IO Issue");
    } finally {
        try {
            fis.close();
            result.close();
        } catch (IOException ex) {
            fail("Unable to close File stream");
        }
    }
}

From source file:it.unitn.elisco.servlet.ImageUploadServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from  ww  w  .ja  va 2  s  .c om
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession session = request.getSession(false);
    Person user;

    if (request.getRequestURI().equals("/admin/image_upload")) {
        user = (Person) session.getAttribute("admin");
    } else {
        user = (Person) session.getAttribute("student");
    }
    // Get the image uploaded by the user as a stream
    Part imagePart = request.getPart("image");
    String imageExtension = "." + imagePart.getSubmittedFileName().split("\\.")[1];

    // Write to a temp file
    File tempFile = File.createTempFile("tmp", imageExtension);
    tempFile.deleteOnExit();
    FileOutputStream out = new FileOutputStream(tempFile);
    IOUtils.copy(imagePart.getInputStream(), out);

    // Upload the image to Cloudinary
    ImageUploader uploader = ImageUploader.getInstance();
    String imageId = uploader.uploadImageToCloud(user, tempFile);

    // Get the url for the uploaded image
    String imageUrl = uploader.getURLWithDimensions(imageId, 200, 200);

    // Send JSON response back to ajax
    String json = new Gson().toJson(imageUrl);
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

From source file:com.cloudera.oryx.kmeans.computation.local.KMeansLocalGenerationRunner.java

@Override
protected void runSteps() throws IOException, InterruptedException, JobException {
    String instanceDir = getInstanceDir();
    int generationID = getGenerationID();
    String generationPrefix = Namespaces.getInstanceGenerationPrefix(instanceDir, generationID);

    File currentInboundDir = Files.createTempDir();
    currentInboundDir.deleteOnExit();
    File tempOutDir = Files.createTempDir();
    tempOutDir.deleteOnExit();/* w  w  w .  j  ava 2s.  c  o m*/

    try {
        Store store = Store.get();
        store.downloadDirectory(generationPrefix + "inbound/", currentInboundDir);
        Summary summary = new Summarize(currentInboundDir).call();
        if (summary == null) {
            // No summary created, bail out.
            return;
        }
        List<List<RealVector>> foldVecs = new Standarize(currentInboundDir, summary).call();
        List<List<WeightedRealVector>> weighted = new WeightedPointsByFold(foldVecs).call();
        List<KMeansEvaluationData> evalData = new ClusteringEvaluation(weighted).call();
        ClusteringModelBuilder b = new ClusteringModelBuilder(summary);
        DataDictionary dictionary = b.getDictionary();
        List<Model> models = Lists.newArrayList();
        List<String> stats = Lists.newArrayList();
        for (KMeansEvaluationData data : evalData) {
            stats.add(data.getClusterValidityStatistics().toString());
            ClusteringModel cm = b.build(data.getName(generationPrefix), data.getBest());
            models.add(cm);
        }
        Files.write(Joiner.on("\n").join(stats) + '\n', new File(tempOutDir, "cluster_stats.csv"),
                Charsets.UTF_8);
        KMeansPMML.write(new File(tempOutDir, "model.pmml.gz"), dictionary, models);
        store.uploadDirectory(generationPrefix, tempOutDir, false);
    } catch (ExecutionException ee) {
        throw new JobException(ee.getCause());
    } finally {
        IOUtils.deleteRecursively(tempOutDir);
    }
}

From source file:com.amazonaws.services.kinesis.clientlibrary.config.AWSCredentialsProviderPropertyValueDecoderTest.java

@Test
public void testProfileProviderWithTwoArgs() throws IOException {
    File temp = File.createTempFile("test-profiles-file", ".tmp");
    temp.deleteOnExit();
    AWSCredentialsProvider provider = decoder.decodeValue(
            ProfileCredentialsProvider.class.getName() + "|" + temp.getAbsolutePath() + "|profileName");
    assertEquals(provider.getClass(), AWSCredentialsProviderChain.class);
}

From source file:gov.lanl.adore.djatoka.plugin.ExtractPDF.java

/**
 * Get PDF information with pdfinfo:/*from  w  w w  .jav  a 2 s  .  co m*/
 * - "Pages: X": number of pages;
 * - "Page X size: www.ww hhh.hh": size of each page, in pts.
 * @returns a map:
 * - [Pages][n]
 * - [Page 1][111.11 222.22]
 * - [Page i][www.ww hhh.hh]
 * - [Page n][999.99 1000.00]
 */
private static Map<String, String> getPDFProperties(ImageRecord input) throws DjatokaException {
    logger.debug("Getting PDF info");

    try {
        setPDFCommandsPath();
    } catch (IllegalStateException e) {
        logger.error("Failed to set PDF commands path: ", e);
        throw e;
    }

    HashMap<String, String> pdfProperties = new HashMap<String, String>();

    String sourcePath = null;

    if (input.getImageFile() != null) {
        logger.debug("PDFInfo image file: " + input.getImageFile());
        sourcePath = input.getImageFile();
    } else if (input.getObject() != null && (input.getObject() instanceof InputStream)) {
        FileInputStream fis = null;
        fis = (FileInputStream) input.getObject();
        File in;

        // Copy to tmp file
        try {
            String cacheDir = OpenURLJP2KService.getCacheDir();
            if (cacheDir != null) {
                in = File.createTempFile("tmp", ".pdf", new File(cacheDir));
            } else {
                in = File.createTempFile("tmp", ".pdf");
            }
            in.deleteOnExit();

            FileOutputStream fos = new FileOutputStream(in);
            IOUtils.copyStream(fis, fos);
        } catch (IOException e) {
            logger.error(e, e);
            throw new DjatokaException(e);
        }
        sourcePath = in.getAbsolutePath();
    } else {
        throw new DjatokaException("File not defined and Input Object Type " + input //.getObject().getClass().getName()
                + " is not supported");
    }

    String pdfinfoCmd[] = PDFINFO_COMMAND.clone();
    pdfinfoCmd[PDFINFO_COMMAND_POSITION_BIN] = pdfinfoPath;
    pdfinfoCmd[PDFINFO_COMMAND_POSITION_FIRSTPAGE] = "1";
    pdfinfoCmd[PDFINFO_COMMAND_POSITION_LASTPAGE] = "-1"; // Last page even we not knowing its number.
    pdfinfoCmd[PDFINFO_COMMAND_POSITION_FILE] = sourcePath;
    Process pdfProc = null;
    try {
        ArrayList<MatchResult> pageSizes = new ArrayList<MatchResult>();
        MatchResult pages = null;

        pdfProc = Runtime.getRuntime().exec(pdfinfoCmd);
        BufferedReader lr = new BufferedReader(new InputStreamReader(pdfProc.getInputStream()));
        String line;
        for (line = lr.readLine(); line != null; line = lr.readLine()) {
            Matcher mm1 = PAGES_PATT.matcher(line);
            if (mm1.matches())
                pages = mm1.toMatchResult();
            Matcher mm2 = MEDIABOX_PATT.matcher(line);
            if (mm2.matches())
                pageSizes.add(mm2.toMatchResult());
        }

        int istatus = pdfProc.waitFor();
        if (istatus != 0)
            logger.error("pdfinfo proc failed, exit status=" + istatus + ", file=" + sourcePath);

        if (pages == null) {
            logger.error("Did not find 'Pages' line in output of pdfinfo command: "
                    + Arrays.deepToString(pdfinfoCmd));
            pdfProperties.put("Pages", "0");
        } else {
            //int n = Integer.parseInteger(pages.group(1));
            pdfProperties.put("Pages", pages.group(1));
        }

        if (pageSizes.isEmpty()) {
            logger.error("Did not find \"Page X size\" lines in output of pdfinfo command: "
                    + Arrays.deepToString(pdfinfoCmd));
            throw new IllegalArgumentException("Failed to get pages size of PDF with pdfinfo.");
        } else {
            for (MatchResult mr : pageSizes) {
                String page = mr.group(1);

                float x0 = Float.parseFloat(mr.group(2));
                float y0 = Float.parseFloat(mr.group(3));
                float x1 = Float.parseFloat(mr.group(4));
                float y1 = Float.parseFloat(mr.group(5));
                float w = Math.abs(x1 - x0);
                float h = Math.abs(y1 - y0);
                // Have to scale page sizes by max dpi (MAX_DPI / DEFAULT_DENSITY). Otherwise, BookReader.js will request the wrong zoom level (svc.level).
                float ws = w * MAX_DPI / DEFAULT_DENSITY;
                float hs = h * MAX_DPI / DEFAULT_DENSITY;
                String width = "" + ws; //mr.group(2);
                String height = "" + hs; //mr.group(3);
                pdfProperties.put("Page " + page, width + " " + height);
            }
        }

    } catch (Exception e) {
        logger.error("Failed getting PDF information: ", e);
        throw new DjatokaException("Failed getting PDF information: ", e);
    } finally {
        // Our exec() should just consume one of the streams, but we want to stay safe.
        // http://mark.koli.ch/2011/01/leaky-pipes-remember-to-close-your-streams-when-using-javas-runtimegetruntimeexec.html
        org.apache.commons.io.IOUtils.closeQuietly(pdfProc.getOutputStream());
        org.apache.commons.io.IOUtils.closeQuietly(pdfProc.getInputStream());
        org.apache.commons.io.IOUtils.closeQuietly(pdfProc.getErrorStream());
    }

    return pdfProperties;
}