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.greenpepper.server.license.LicenceGenerator.java

private static void buildCommercial(int users, Date supportDate) throws Exception {
    File file = File.createTempFile("commercial", ".lic");
    License license = License.commercial("My Paying Company", _2006, supportDate, users);
    LicenseManager lm = new LicenseManager(getLicenseParam());
    lm.store(license, file);//  ww w . ja v a 2  s  .  c o m
    if (deleteFiles)
        file.deleteOnExit();
    System.out.println(
            "# Commercial " + users + " USERS - Expery: " + new FormatedDate(supportDate).getFormatedDate());
    System.out.println(new String(Base64.encodeBase64(FileUtils.readFileToByteArray(file))));
    System.out.println("");
}

From source file:com.qmetry.qaf.automation.util.FileUtil.java

public static File createTempFile(File dir, String... name) throws IOException {
    String fname = null, ext = null;
    if ((name != null)) {
        if ((name.length == 1) && StringUtil.isNotEmpty(name[0])) {
            // check contains extension?
            int dotSign = name[0].lastIndexOf(".");
            if ((dotSign >= 0) && (dotSign < name[0].length())) {
                fname = name[0].substring(0, dotSign);
                ext = name[0].substring(dotSign);
            } else {
                fname = name[0];/*from  w w w  . java  2s  .  co m*/
            }
        } else if (name.length > 1) {
            fname = name[0];
            ext = name[1].startsWith(".") ? name[1] : "." + name[1];
        }
    }
    if (StringUtil.isBlank(fname)) {
        fname = StringUtil.createRandomString("Auto");
    }
    File tmpfile = File.createTempFile(fname, ext, dir);
    tmpfile.deleteOnExit();
    return tmpfile;
}

From source file:ibeam.maven.plugins.Tools.java

/**
 * Deletes a file (or a directory), never throwing an exception.
 * If deleteOnExistMode option is activated, the deletion will be attempted only for normal termination of the virtual machine.
 * A directory to be deleted does not have to be empty. No exceptions are thrown when a file or directory cannot be deleted.
 * /*from  w  w  w  .java 2 s  . c  om*/
 * @param file
 * @param deleteOnExistMode
 * @param log
 */
public static void deleteQuietly(final File file, final boolean deleteOnExistMode, final Log log) {

    try {
        if (deleteOnExistMode) {
            file.deleteOnExit();
        } else {
            FileUtils.deleteQuietly(file);
        }
    } catch (SecurityException e) {
        log.error(Enumeres.EXCEPTION.FILE_DELETION_EXCEPTION + file, e);
    }

}

From source file:ProxyAuthTest.java

private static void generateData() throws Exception {
    String fileData[] = { "1|aaa", "2|bbb", "3|ccc", "4|ddd", "5|eee", };

    File tmpFile = File.createTempFile(tabName, ".data");
    tmpFile.deleteOnExit();
    tabDataFileName = tmpFile.getPath();
    FileWriter fstream = new FileWriter(tabDataFileName);
    BufferedWriter out = new BufferedWriter(fstream);
    for (String line : fileData) {
        out.write(line);/*from w ww  .  j  a v  a  2s  . c om*/
        out.newLine();
    }
    out.close();
    tmpFile.setWritable(true, true);
}

From source file:edu.stolaf.cs.wmrserver.streaming.StreamJob.java

public static String createJobJar(JobConf conf, List extraFiles, File tmpDir) throws IOException {
    ArrayList unjarFiles = new ArrayList();
    ArrayList packageFiles = new ArrayList(extraFiles);

    // Runtime code: ship same version of code as self (job submitter code)
    // usually found in: build/contrib or build/hadoop-<version>-dev-streaming.jar

    // First try an explicit spec: it's too hard to find our own location in this case:
    // $HADOOP_HOME/bin/hadoop jar /not/first/on/classpath/custom-hadoop-streaming.jar
    // where findInClasspath() would find the version of hadoop-streaming.jar in $HADOOP_HOME
    String runtimeClasses = conf.get("stream.shipped.hadoopstreaming"); // jar or class dir

    if (runtimeClasses == null) {
        runtimeClasses = StreamUtil.findInClasspath(StreamJob.class);
    }//w  ww  .ja  va 2  s.c  om
    if (runtimeClasses == null) {
        throw new IOException("runtime classes not found: " + StreamJob.class.getPackage());
    }
    if (StreamUtil.isLocalJobTracker(conf)) {
        // don't package class files (they might get unpackaged in "." and then
        //  hide the intended CLASSPATH entry)
        // we still package everything else (so that scripts and executable are found in
        //  Task workdir like distributed Hadoop)
    } else {
        if (new File(runtimeClasses).isDirectory()) {
            packageFiles.add(runtimeClasses);
        } else {
            unjarFiles.add(runtimeClasses);
        }
    }
    if (packageFiles.size() + unjarFiles.size() == 0) {
        return null;
    }
    if (tmpDir == null) {
        String tmp = conf.get("stream.tmpdir", ""); //, "/tmp/${user.name}/"
        tmpDir = new File(tmp);
    }
    // tmpDir=null means OS default tmp dir
    File jobJar = File.createTempFile("streamjob", ".jar", tmpDir);
    System.out
            .println("packageJobJar: " + packageFiles + " " + unjarFiles + " " + jobJar + " tmpDir=" + tmpDir);
    jobJar.deleteOnExit();
    JarBuilder builder = new JarBuilder();
    String jobJarName = jobJar.getAbsolutePath();
    builder.merge(packageFiles, unjarFiles, jobJarName);
    return jobJarName;
}

From source file:com.sldeditor.test.unit.tool.ysld.YSLDToolTest.java

/**
 * Writes an InputStream to a temporary file.
 *
 * @param in the in//from  ww  w  . ja  v  a2 s .co  m
 * @param suffix the suffix
 * @return the file
 * @throws IOException Signals that an I/O exception has occurred.
 */
private static File stream2file(InputStream in, String suffix) throws IOException {
    final File tempFile = File.createTempFile(PREFIX, suffix);
    tempFile.deleteOnExit();
    try (FileOutputStream out = new FileOutputStream(tempFile)) {
        IOUtils.copy(in, out);
    }
    return tempFile;
}

From source file:net.sourceforge.lept4j.util.LoadLibs.java

/**
 * Copies resources from the jar file of the current thread and extract it
 * to the destination directory./*  w  w w.  j  a v a2  s .  c  o  m*/
 *
 * @param jarConnection
 * @param destDir
 */
static void copyJarResourceToDirectory(JarURLConnection jarConnection, File destDir) {
    try {
        JarFile jarFile = jarConnection.getJarFile();
        String jarConnectionEntryName = jarConnection.getEntryName() + "/";

        /**
         * Iterate all entries in the jar file.
         */
        for (Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements();) {
            JarEntry jarEntry = e.nextElement();
            String jarEntryName = jarEntry.getName();

            /**
             * Extract files only if they match the path.
             */
            if (jarEntryName.startsWith(jarConnectionEntryName)) {
                String filename = jarEntryName.substring(jarConnectionEntryName.length());
                File currentFile = new File(destDir, filename);

                if (jarEntry.isDirectory()) {
                    currentFile.mkdirs();
                } else {
                    currentFile.deleteOnExit();
                    InputStream is = jarFile.getInputStream(jarEntry);
                    OutputStream out = FileUtils.openOutputStream(currentFile);
                    IOUtils.copy(is, out);
                    is.close();
                    out.close();
                }
            }
        }
    } catch (IOException e) {
        logger.log(Level.WARNING, e.getMessage(), e);
    }
}

From source file:com.offbynull.coroutines.instrumenter.testhelpers.TestUtils.java

/**
 * Creates a JAR as a temporary file. Simple manifest file will automatically be inserted.
 *
 * @param entries files to put inside of the jar
 * @return resulting jar file//from   www.  j  a v a2 s.c om
 * @throws IOException if any IO errors occur
 * @throws NullPointerException if any argument is {@code null} or contains {@code null} elements
 */
public static File createJar(JarEntry... entries) throws IOException {
    Validate.notNull(entries);
    Validate.noNullElements(entries);

    File tempFile = File.createTempFile(TestUtils.class.getSimpleName(), ".jar");
    tempFile.deleteOnExit();

    try (FileOutputStream fos = new FileOutputStream(tempFile);
            JarArchiveOutputStream jaos = new JarArchiveOutputStream(fos)) {
        writeJarEntry(jaos, MANIFEST_PATH, MANIFEST_TEXT.getBytes(Charsets.UTF_8));
        for (JarEntry entry : entries) {
            writeJarEntry(jaos, entry.name, entry.data);
        }
    }

    return tempFile;
}

From source file:com.cloudera.director.aws.ec2.EphemeralDeviceMappings.java

/**
 * Gets a test instance of this class that uses only the given mapping.
 *
 * @param counts                      map of instance types to counts
 * @param launcherLocalizationContext the parent launcher localization context
 * @return new mapping object//  w  w  w  .  ja  v a  2 s.c  o m
 */
public static EphemeralDeviceMappings getTestInstance(Map<String, Integer> counts,
        LocalizationContext launcherLocalizationContext) {
    Map<String, String> propertyMap = Maps.transformValues(counts, Functions.toStringFunction());
    PropertyResolver ephemeralDeviceMappingsResolver = PropertyResolvers.newMapPropertyResolver(propertyMap);
    File tempDir = Files.createTempDir();
    tempDir.deleteOnExit();
    EphemeralDeviceMappingsConfigProperties ephemeralDeviceMappingsConfigProperties = new EphemeralDeviceMappingsConfigProperties(
            new SimpleConfiguration(), tempDir, launcherLocalizationContext);
    return new EphemeralDeviceMappings(ephemeralDeviceMappingsConfigProperties,
            ephemeralDeviceMappingsResolver);
}

From source file:com.github.pitzcarraldo.openjpeg.OpenJPEGLoader.java

private static File loadExeFromResource(String resource) throws IOException {
    logger.trace("Attempting to extract executable from jar: " + resource);
    String temp = System.getProperty("java.io.tmpdir");
    String ext = resource.substring(resource.lastIndexOf("."));
    String name = new File(resource).getName();
    name = name.substring(0, name.lastIndexOf("."));
    File libDir = File.createTempFile("dissimilar_" + name + "_", ext + ".dir", new File(temp));
    libDir.mkdirs();/*w ww .j  a v a 2s .co  m*/
    libDir.deleteOnExit();
    File lib = new File(libDir.getAbsolutePath() + "/" + new File(resource).getName());
    //TODO: fail if we are not running on linux-x86_64
    InputStream libInputStream = OpenJPEGLoader.class.getClassLoader().getResourceAsStream(resource);
    copyStreamToFile(libInputStream, lib);
    logger.trace("Extracted executable from jar: " + resource + " -> " + lib.getAbsolutePath());
    return lib;
}