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:at.treedb.jslib.JsLib.java

/**
 * Loads an external JavaScript library.
 * //from   www  .  j  a  va 2 s . c om
 * @param dao
 *            {@code DAOiface} (data access object)
 * @param name
 *            library name
 * @param version
 *            optional library version. If this parameter is null the
 *            library with the highest version number will be loaded
 * @return {@code JsLib} object
 * @throws Exception
 */
@SuppressWarnings("resource")
public static synchronized JsLib load(DAOiface dao, String name, String version) throws Exception {
    initJsLib(dao);
    if (jsLibs == null) {
        return null;
    }
    JsLib lib = null;
    synchronized (lockObj) {
        HashMap<Version, JsLib> v = jsLibs.get(name);
        if (v == null) {
            return null;
        }

        if (version != null) {
            lib = v.get(new Version(version));
        } else {
            Version[] array = v.keySet().toArray(new Version[v.size()]);
            Arrays.sort(array);
            // return the library with the highest version number
            lib = v.get(array[array.length - 1]);
        }
    }
    if (lib != null) {
        if (!lib.isExtracted) {
            // load binary archive data
            lib.callbackAfterLoad(dao);
            // detect zip of 7z archive
            MimeType mtype = ContentInfo.getContentInfo(lib.data);
            int totalSize = 0;
            HashMap<String, byte[]> dataMap = null;
            String libName = "jsLib" + lib.getHistId();
            String classPath = lib.getName() + "/java/classes/";
            if (mtype != null) {
                // ZIP archive
                if (mtype.equals(MimeType.ZIP)) {
                    dataMap = new HashMap<String, byte[]>();
                    lib.zipInput = new ZipArchiveInputStream(new ByteArrayInputStream(lib.data));
                    do {
                        ZipArchiveEntry entry = lib.zipInput.getNextZipEntry();
                        if (entry == null) {
                            break;
                        }
                        if (entry.isDirectory()) {
                            continue;
                        }
                        int size = (int) entry.getSize();
                        totalSize += size;
                        byte[] data = new byte[size];
                        lib.zipInput.read(data, 0, size);
                        dataMap.put(entry.getName(), data);
                        if (entry.getName().contains(classPath)) {
                            lib.javaFiles.add(entry.getName());
                        }
                    } while (true);
                    lib.zipInput.close();
                    lib.isExtracted = true;
                    // 7-zip archive
                } else if (mtype.equals(MimeType._7Z)) {
                    dataMap = new HashMap<String, byte[]>();
                    File tempFile = FileStorage.getInstance().createTempFile(libName, ".7z");
                    tempFile.deleteOnExit();
                    Stream.writeByteStream(tempFile, lib.data);
                    lib.sevenZFile = new SevenZFile(tempFile);
                    do {
                        SevenZArchiveEntry entry = lib.sevenZFile.getNextEntry();
                        if (entry == null) {
                            break;
                        }
                        if (entry.isDirectory()) {
                            continue;
                        }
                        int size = (int) entry.getSize();
                        totalSize += size;
                        byte[] data = new byte[size];
                        lib.sevenZFile.read(data, 0, size);
                        dataMap.put(entry.getName(), data);
                        if (entry.getName().contains(classPath)) {
                            lib.javaFiles.add(entry.getName());
                        }

                    } while (true);
                    lib.sevenZFile.close();
                    lib.isExtracted = true;
                }
            }
            if (!lib.isExtracted) {
                throw new Exception("JsLib.load(): No JavaScript archive extracted!");
            }
            // create a buffer for the archive
            byte[] buf = new byte[totalSize];
            int offset = 0;
            // enumerate the archive entries
            for (String n : dataMap.keySet()) {
                byte[] d = dataMap.get(n);
                System.arraycopy(d, 0, buf, offset, d.length);
                lib.archiveMap.put(n, new ArchiveEntry(offset, d.length));
                offset += d.length;
            }
            // create a temporary file containing the extracted archive
            File tempFile = FileStorage.getInstance().createTempFile(libName, ".dump");
            lib.dumpFile = tempFile;
            tempFile.deleteOnExit();
            Stream.writeByteStream(tempFile, buf);
            FileInputStream inFile = new FileInputStream(tempFile);
            // closed by the GC
            lib.inChannel = inFile.getChannel();
            // discard the archive data - free the memory
            lib.data = null;
            dataMap = null;
        }
    }
    return lib;
}

From source file:com.github.seqware.queryengine.system.Utility.java

/**
 * <p>dumpVCFFromFeatureSetID.</p>
 *
 * @param fSet a {@link com.github.seqware.queryengine.model.FeatureSet} object.
 * @param file a {@link java.lang.String} object.
 *//*from w  w w .  ja va  2  s  .  c  om*/
public static boolean dumpFromMapReducePlugin(String header, Reference ref, FeatureSet fSet,
        Class<? extends PluginInterface> arbitraryPlugin, String file, Object... params) {
    BufferedWriter outputStream = null;
    try {
        if (file != null) {
            outputStream = new BufferedWriter(new FileWriter(file));
        } else {
            outputStream = new BufferedWriter(new OutputStreamWriter(System.out));
        }
        if (header != null) {
            outputStream.append(header);
        }
    } catch (IOException e) {
        Logger.getLogger(Utility.class.getName()).fatal("Exception thrown starting export to file:", e);
        System.exit(-1);
    }
    if (SWQEFactory.getQueryInterface() instanceof MRHBasePersistentBackEnd) {
        if (SWQEFactory.getModelManager() instanceof MRHBaseModelManager) {
            try {
                QueryFuture<File> future = SWQEFactory.getQueryInterface().getFeaturesByPlugin(0,
                        arbitraryPlugin, ref, params);
                File get = future.get();
                Collection<File> listFiles = FileUtils.listFiles(get, new WildcardFileFilter("part*"),
                        DirectoryFileFilter.DIRECTORY);
                for (File f : listFiles) {
                    BufferedReader in = new BufferedReader(new FileReader(f));
                    IOUtils.copy(in, outputStream);
                    in.close();
                }
                get.deleteOnExit();
                assert (outputStream != null);
                outputStream.flush();
                outputStream.close();
                return true;
            } catch (IOException e) {
                Logger.getLogger(VCFDumper.class.getName()).fatal("Exception thrown exporting to file:", e);
                System.exit(-1);
            } catch (Exception e) {
                Logger.getLogger(VCFDumper.class.getName())
                        .fatal("MapReduce exporting failed, falling-through to normal exporting to file", e);
            }
        }
    }
    return false;
}

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

/** Get a sorted, temporary crawl.log file from an unsorted one.
 *
 * @param file The file containing an unsorted crawl.log file.
 * @return A temporary file containing the entries sorted according to
 * URL.  The file will be removed upon exit of the JVM, but should be
 * attempted removed when it is no longer used.
 *//*from w w w . j  av  a  2  s.  c o m*/
protected static File getSortedCrawlLog(File file) {
    try {
        File tmpCrawlLog = File.createTempFile("sorted", "crawllog", FileUtils.getTempDir());
        // This throws IOFailure, if the sorting operation fails
        FileUtils.sortCrawlLog(file, tmpCrawlLog);
        tmpCrawlLog.deleteOnExit();
        return tmpCrawlLog;
    } catch (IOException e) {
        throw new IOFailure("Error creating sorted crawl log file for '" + file + "'", e);
    }
}

From source file:gov.nasa.ensemble.common.io.FileUtilities.java

/**
 * Create a temporary file that will auto-delete when this VM terminates
 * /*from   w w w.ja  v a  2  s.c  o  m*/
 * @param prefix
 * @param suffix
 * @return File
 * @throws IOException
 */
public static File createTempFile(String prefix, String suffix) throws IOException {
    File tempFile = File.createTempFile(prefix, suffix);
    tempFile.deleteOnExit();
    return tempFile;
}

From source file:eu.planets_project.services.utils.DigitalObjectUtils.java

/**
 * @param object The digital object to copy to a temporary file
 * @return The temporary file the digital object's byte stream was written to
 *//*from w  ww.j av  a  2  s.c  o  m*/
public static File toFile(final DigitalObject object) {
    try {
        /* TODO: use format registry to set the extension? The framework should not presume user needs or perform preservation actions silently. */
        /* TODO: use data registry to store the content? Maybe, but TMP files are needed too: toTmpFile.*/
        File file = File.createTempFile("planets", null);
        file.deleteOnExit();
        toFile(object, file);
        return file;
    } catch (IOException e) {
        e.printStackTrace();
    }
    throw new IllegalStateException("Could not copy digital object: " + object);
}

From source file:com.ryan.ryanreader.common.General.java

/**
 * /*from w w  w .j  a  va2  s.c  o  m*/
 * 
 * @param src
 * @param dst
 * @throws IOException
 */
public static void moveFile(final File src, final File dst) throws IOException {

    if (!src.renameTo(dst)) {

        // renameToCOPY
        copyFile(src, dst);

        if (!src.delete()) {
            src.deleteOnExit();
        }
    }
}

From source file:docs.AbstractGemFireIntegrationTests.java

protected static File createDirectory(String pathname) {
    File directory = new File(WORKING_DIRECTORY, pathname);

    assertThat(directory.isDirectory() || directory.mkdirs())
            .as(String.format("Failed to create directory (%1$s)", directory)).isTrue();

    directory.deleteOnExit();

    return directory;
}

From source file:gov.nasa.ensemble.common.io.FileUtilities.java

/**
 * Create a temporary file that will auto-delete when this VM terminates
 * //from w w  w.  j  a  v a2  s. c  o  m
 * @param prefix
 * @param suffix
 * @param directory
 * @return File
 * @throws IOException
 */
public static File createTempFile(String prefix, String suffix, File directory) throws IOException {
    File tempFile = File.createTempFile(prefix, suffix, directory);
    tempFile.deleteOnExit();
    return tempFile;
}

From source file:be.ibridge.kettle.core.LogWriter.java

public static final Log4jFileAppender createFileAppender(String filename, boolean exact)
        throws KettleException {
    try {/*from   w w  w  .  j a v  a2s .c  o  m*/
        File file;
        if (!exact) {
            file = File.createTempFile(filename + ".", ".log");
            file.deleteOnExit();
        } else {
            file = new File(filename);
        }
        File realFile = file.getAbsoluteFile();

        Log4jFileAppender appender = new Log4jFileAppender(realFile);
        appender.setLayout(new Log4jKettleLayout(true));
        appender.setName(LogWriter.createFileAppenderName(filename, exact));

        return appender;
    } catch (IOException e) {
        throw new KettleFileException("Unable to add Kettle file appender to Log4J", e);
    }
}

From source file:com.sldeditor.test.SLDTestRunner.java

/**
 * Writes an InputStream to a temporary file.
 *
 * @param in the in//w  w w  . j  ava  2s  . co  m
 * @return the file
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static File stream2file(InputStream in) throws IOException {
    final File tempFile = File.createTempFile(PREFIX, SUFFIX);
    tempFile.deleteOnExit();
    try (FileOutputStream out = new FileOutputStream(tempFile)) {
        IOUtils.copy(in, out);
    }

    // Update the font for the operating system
    String newFont = getFontForOS();
    if (newFont.compareToIgnoreCase(DEFAULT_FONT) != 0) {
        BufferedReader br = new BufferedReader(new FileReader(tempFile));
        try {
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();

            while (line != null) {
                sb.append(line.replace(DEFAULT_FONT, newFont));
                sb.append("\n");
                line = br.readLine();
            }
            try {
                FileWriter fileWriter = new FileWriter(tempFile);
                fileWriter.write(sb.toString());
                fileWriter.flush();
                fileWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        } finally {
            br.close();
        }
    }
    return tempFile;
}