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.github.pitzcarraldo.openjpeg.OpenJPEGLoader.java

/**
 * Method to load a JP2 file using OpenJPEG executable
 * @param pFile jp2 file to load/*from   w  w  w. j av  a 2s . c  o m*/
 * @return decoded buffered image from file
 */
private static BufferedImage loadJP2_Executable(File pFile) {
    logger.trace("executable decoder: " + pFile.getAbsolutePath());
    File tempOutput = null;
    try {
        tempOutput = File.createTempFile("dissimilar_" + pFile.getName() + "_", ".tif");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //FIXME: null check?
    tempOutput.deleteOnExit();

    List<String> commandLine = new LinkedList<String>();
    commandLine.add(OPENJPEGEXE.getAbsolutePath());
    commandLine.add("-i");
    commandLine.add(pFile.getAbsolutePath());
    commandLine.add("-o");
    commandLine.add(tempOutput.getAbsolutePath());

    logger.trace("running: " + commandLine.toString());

    ToolRunner runner = new ToolRunner(true);
    int exitCode = 0;
    try {
        exitCode = runner.runCommand(commandLine);
        logger.trace("exit code: " + exitCode);
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    if (exitCode != 0) {
        //some error
        BufferedReader log = runner.getStdout();
        try {
            while (log.ready()) {
                logger.error("log: " + log.readLine());
            }
        } catch (IOException e) {

        }
    } else {
        try {
            BufferedImage image = Imaging.getBufferedImage(tempOutput);
            //force a delete
            tempOutput.delete();
            return image;
        } catch (ImageReadException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    return null;
}

From source file:com.validation.manager.core.tool.Tool.java

public static File convertToPDF(File f, String filename) throws FileNotFoundException, IOException {
    TextToPDF ttp = new TextToPDF();
    File pdf;
    try (PDDocument pdfd = ttp.createPDFFromText(new FileReader(f))) {
        pdf = new File(filename);
        if (pdf.getParentFile() != null) {
            pdf.getParentFile().mkdirs();
        }//from w  w  w.  j  a v a  2  s  .  c o  m
        pdfd.save(pdf);
    }
    pdf.deleteOnExit();
    return pdf;
}

From source file:edu.uw.apl.nativelibloader.NativeLoader.java

static private File extractLibraryFile(String resourceName, File outDir) throws IOException {
    /*//  w w  w  .jav a  2  s .  co m
    Attach UUID to the native library file to essentially
    randomize its name.  This ensures multiple class loaders can
    read it multiple times.
    */
    String uuid = UUID.randomUUID().toString();
    String extractedLibFileName = resourceName.substring(1).replaceAll("/", ".");
    // In Maven terms, the uuid acts like a 'classifier'
    extractedLibFileName += "-" + uuid;
    File extractedLibFile = new File(outDir, extractedLibFileName);
    log.debug("Extracting " + resourceName + " to " + extractedLibFile);

    InputStream is = NativeLoader.class.getResourceAsStream(resourceName);
    FileUtils.copyInputStreamToFile(is, extractedLibFile);
    is.close();
    extractedLibFile.deleteOnExit();

    // Set executable (x) flag to enable Java to load the native library
    extractedLibFile.setReadable(true);
    //extractedLibFile.setWritable(true, true);
    extractedLibFile.setExecutable(true);

    return extractedLibFile;
}

From source file:net.orpiske.sdm.lib.io.IOUtil.java

/**
 * Protects a file or resource from being written
 * @param resource the resource to protect
 * @throws IOException//from ww  w  . ja  v  a  2  s . c o m
 */
public static void shield(final String resource) throws IOException {
    File shieldedFile = new File(resource);

    if (!shieldedFile.exists()) {
        System.out.println("Resource " + resource + " does not exist");

        return;
    }

    File shielded = new File(resource + ShieldUtils.SHIELD_EXT);

    if (!shielded.exists()) {

        if (!shielded.createNewFile()) {
            System.err.println("Unable to create shield file " + shielded.getPath());
        }

        System.out.println("Resource " + resource + " was shielded");
    } else {
        System.out.println("Resource " + resource + " already shielded");
    }

    shielded.deleteOnExit();
}

From source file:org.drools.container.spring.beans.persistence.JPASingleSessionCommandServiceFactoryTest.java

public static void writePackage(Package pkg, File dest) {
    dest.deleteOnExit();
    OutputStream out = null;//from  w w w  . ja v a  2s  .  com
    try {
        out = new BufferedOutputStream(new FileOutputStream(dest));
        DroolsStreamUtils.streamOut(out, pkg);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:com.opengamma.examples.simulated.tool.ExampleDatabasePopulator.java

private static String unpackJar(URL resource) {
    String file = resource.getPath();
    if (file.contains(".jar!/")) {
        s_logger.info("Unpacking zip file located within a jar file: {}", resource);
        String jarFileName = StringUtils.substringBefore(file, "!/");
        if (jarFileName.startsWith("file:/")) {
            jarFileName = jarFileName.substring(5);
            if (SystemUtils.IS_OS_WINDOWS) {
                jarFileName = StringUtils.stripStart(jarFileName, "/");
            }//from  w ww  .  ja  v a2 s  .  co m
        } else if (jarFileName.startsWith("file:/")) {
            jarFileName = jarFileName.substring(6);
        }
        jarFileName = StringUtils.replace(jarFileName, "%20", " ");
        String innerFileName = StringUtils.substringAfter(file, "!/");
        innerFileName = StringUtils.replace(innerFileName, "%20", " ");
        s_logger.info("Unpacking zip file found jar file: {}", jarFileName);
        s_logger.info("Unpacking zip file found zip file: {}", innerFileName);
        try {
            JarFile jar = new JarFile(jarFileName);
            JarEntry jarEntry = jar.getJarEntry(innerFileName);
            try (InputStream in = jar.getInputStream(jarEntry)) {
                File tempFile = File.createTempFile("simulated-examples-database-populator-", ".zip");
                tempFile.deleteOnExit();
                try (OutputStream out = new FileOutputStream(tempFile)) {
                    IOUtils.copy(in, out);
                }
                file = tempFile.getCanonicalPath();
            }
        } catch (IOException ex) {
            throw new OpenGammaRuntimeException("Unable to open file within jar file: " + resource, ex);
        }
        s_logger.debug("Unpacking zip file extracted to: {}", file);
    }
    return file;
}

From source file:org.eclipse.cft.server.core.internal.CloudUtil.java

/**
 * Creates a partial war file containing only the resources listed in the
 * list to filter in. Note that at least one content must be present in the
 * list to filter in, otherwise null is returned.
 * @param resources/*ww w.j av a 2 s  .co  m*/
 * @param module
 * @param server
 * @param monitor
 * @return partial war file with resources specified in the filter in list,
 * or null if filter list is empty or null
 * @throws CoreException
 */
public static File createWarFile(List<IModuleResource> allResources, IModule module,
        Set<IModuleResource> filterInResources, IProgressMonitor monitor) throws CoreException {
    if (allResources == null || allResources.isEmpty() || filterInResources == null
            || filterInResources.isEmpty()) {
        return null;
    }
    List<IStatus> result = new ArrayList<IStatus>();
    try {
        File tempDirectory = getTempFolder(module);
        // tempFile needs to be in the same location as the war file
        // otherwise PublishHelper will fail
        String fileName = module.getName() + ".war"; //$NON-NLS-1$

        File warFile = new File(tempDirectory, fileName);
        warFile.createNewFile();
        warFile.deleteOnExit();
        List<IModuleResource> newResources = new ArrayList<IModuleResource>();
        for (IModuleResource mr : allResources) {
            newResources.add(processModuleResource(mr));
        }

        IStatus[] status = publishZip(allResources, warFile, filterInResources, monitor);
        merge(result, status);
        throwException(result, "Publishing of : " + module.getName() + " failed"); //$NON-NLS-1$ //$NON-NLS-2$

        return warFile;
    } catch (IOException e) {
        throw new CoreException(new Status(IStatus.ERROR, CloudFoundryPlugin.PLUGIN_ID,
                "Failed to create war file: " + e.getMessage(), e)); //$NON-NLS-1$
    }
}

From source file:com.cenrise.test.azkaban.Utils.java

public static File createTempDir(final File parent) {
    final File temp = new File(parent, Integer.toString(Math.abs(RANDOM.nextInt()) % 100000000));
    temp.delete();//w w  w.  ja va  2 s  .  c  om
    temp.mkdir();
    temp.deleteOnExit();
    return temp;
}

From source file:com.boundlessgeo.wps.grass.GrassProcesses.java

@DescribeProcess(title = "r.viewshed", description = "Computes the viewshed of a point on an elevation raster map.")
@DescribeResult(description = "area visible from provided location")
public static GridCoverage2D viewshed(
        @DescribeParameter(name = "dem", description = "digitial elevation model") GridCoverage2D dem,
        @DescribeParameter(name = "x", description = "x location in map units") double x,
        @DescribeParameter(name = "y", description = "y location in map units") double y) throws Exception {

    String COMMAND = "viewshed";
    //Stage files in a temporary location
    File geodb = Files.createTempDirectory("grassdata").toFile();
    geodb.deleteOnExit();
    File location = new File(geodb, COMMAND + Long.toString(random.nextLong()) + "location");

    // stage dem file
    File file = new File(geodb, "dem.tif");
    //The file must exist for FileImageOutputStreamExtImplSpi to create the output stream
    if (!file.exists()) {
        file.getParentFile().mkdirs();//  ww  w.  j  a  v a 2 s .c o  m
        file.createNewFile();
    }
    final GeoTiffFormat format = new GeoTiffFormat();
    GridCoverageWriter writer = format.getWriter(file);
    writer.write(dem, null);
    LOGGER.info("Staging file:" + file);

    // use file to create location with (returns PERMANENT mapset)
    File mapset = location(location, file);

    DefaultExecutor executor = new DefaultExecutor();
    executor.setWatchdog(new ExecuteWatchdog(60000));
    executor.setStreamHandler(new PumpStreamHandler(System.out));
    executor.setWorkingDirectory(mapset);

    Map<String, String> env = customEnv(geodb, location, mapset);

    // EXPORT IMPORT DEM
    // r.in.gdal input=~/grassdata/viewshed/PERMANENT/dem.tif output=dem --overwrite

    File r_in_gdal = bin("r.in.gdal");
    CommandLine cmd = new CommandLine(r_in_gdal);
    cmd.addArgument("input=${file}");
    cmd.addArgument("output=dem");
    cmd.addArgument("--overwrite");
    cmd.setSubstitutionMap(new KVP("file", file));
    try {
        LOGGER.info(cmd.toString());
        executor.setExitValue(0);
        int exitValue = executor.execute(cmd, env);
    } catch (ExecuteException fail) {
        LOGGER.warning(r_in_gdal.getName() + ":" + fail.getLocalizedMessage());
        throw fail;
    }

    // EXECUTE VIEWSHED
    File r_viewshed = bin("r.viewshed");
    cmd = new CommandLine(r_viewshed);
    cmd.addArgument("input=dem");
    cmd.addArgument("output=viewshed");
    cmd.addArgument("coordinates=${x},${y}");
    cmd.addArgument("--overwrite");
    cmd.setSubstitutionMap(new KVP("x", x, "y", y));

    try {
        LOGGER.info(cmd.toString());
        executor.setExitValue(0);
        int exitValue = executor.execute(cmd, env);
    } catch (ExecuteException fail) {
        LOGGER.warning(r_viewshed.getName() + ":" + fail.getLocalizedMessage());
        throw fail;
    }

    // EXECUTE EXPORT VIEWSHED
    // r.out.gdal --overwrite input=viewshed@PERMANENT output=/Users/jody/grassdata/viewshed/viewshed.tif format=GTiff
    File viewshed = new File(location, "viewshed.tif");

    File r_out_gdal = bin("r.out.gdal");
    cmd = new CommandLine(r_out_gdal);
    cmd.addArgument("input=viewshed");
    cmd.addArgument("output=${viewshed}");
    cmd.addArgument("--overwrite");
    cmd.addArgument("format=GTiff");
    cmd.setSubstitutionMap(new KVP("viewshed", viewshed));

    try {
        LOGGER.info(cmd.toString());
        executor.setExitValue(0);
        int exitValue = executor.execute(cmd, env);
    } catch (ExecuteException fail) {
        LOGGER.warning(r_out_gdal.getName() + ":" + fail.getLocalizedMessage());
        throw fail;
    }

    // STAGE RESULT

    if (!viewshed.exists()) {
        throw new IOException("Generated viweshed.tif not found");
    }
    GeoTiffReader reader = format.getReader(viewshed);
    GridCoverage2D coverage = reader.read(null);
    cleanup(new File(env.get("GISRC")));
    return coverage;
}

From source file:dk.netarkivet.harvester.indexserver.CrawlLogIndexCache.java

/** Get a sorted, temporary CDX file corresponding to the given CDXfile.
        //from  ww  w  . ja  v  a 2  s.co  m
 * @param cdxFile A cdxfile 
 * @return A temporary file with CDX info for that just sorted according
 * to the standard CDX sorting rules.  This file will be removed at the
 * exit of the JVM, but should be attempted removed when it is no longer
 * used.
 */
protected static File getSortedCDX(File cdxFile) {
    try {
        final File tmpFile = File.createTempFile("sorted", "cdx", FileUtils.getTempDir());
        // This throws IOFailure, if the sorting operation fails 
        FileUtils.sortCDX(cdxFile, tmpFile);
        tmpFile.deleteOnExit();
        return tmpFile;
    } catch (IOException e) {
        throw new IOFailure("Error while making tmp file for " + cdxFile, e);
    }
}