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:io.joynr.util.JoynrUtil.java

public static void copyDirectoryFromJar(String jarName, String srcDir, File tmpDir) throws IOException {

    JarFile jf = null;/*from w  w w.j  a  v  a 2s. c  o  m*/
    JarInputStream jarInputStream = null;

    try {
        jf = new JarFile(jarName);
        JarEntry je = jf.getJarEntry(srcDir);
        if (je.isDirectory()) {
            FileInputStream fis = new FileInputStream(jarName);
            BufferedInputStream bis = new BufferedInputStream(fis);
            jarInputStream = new JarInputStream(bis);
            JarEntry ze = null;
            while ((ze = jarInputStream.getNextJarEntry()) != null) {
                if (ze.isDirectory()) {
                    continue;
                }
                if (ze.getName().contains(je.getName())) {
                    InputStream is = jf.getInputStream(ze);
                    String name = ze.getName().substring(ze.getName().lastIndexOf("/") + 1);
                    File tmpFile = new File(tmpDir + "/" + name); //File.createTempFile(file.getName(), "tmp");
                    tmpFile.deleteOnExit();
                    OutputStream outputStreamRuntime = new FileOutputStream(tmpFile);
                    copyStream(is, outputStreamRuntime);
                }
            }
        }
    } finally {
        if (jf != null) {
            jf.close();
        }
        if (jarInputStream != null) {
            jarInputStream.close();
        }
    }
}

From source file:com.asual.summer.onejar.OneJarServer.java

private static String getCurrentWarFile() throws IOException {
    JarFile jarFile = new JarFile(System.getProperty("java.class.path"));
    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        String name = entries.nextElement().getName();
        if (name.endsWith(".war")) {
            File war = new File(new File(System.getProperty("java.io.tmpdir")),
                    "summer-onejar-" + System.currentTimeMillis() + ".war");
            InputStream input = jarFile.getInputStream(new ZipEntry(name));
            FileOutputStream output = new FileOutputStream(war);
            IOUtils.copy(input, output);
            IOUtils.closeQuietly(input);
            IOUtils.closeQuietly(output);
            war.deleteOnExit();
            return war.getAbsolutePath();
        }//w w  w .j ava  2s  .c  o m
    }
    return null;
}

From source file:com.canoo.webtest.util.FileUtil.java

/**
 * Creates a temporary file using a prefix and suffix and marks it for deletion on exit.
 *
 * @param prefix/*  ww w  .  j a v a2s.  c  o m*/
 * @param suffix
 * @param step
 * @throws StepExecutionException if an error occurs while creating the file
 * @return the newly created temp file
 */
public static File tryCreateTempFile(final String prefix, final String suffix, final Step step) {
    final File tmpFile;
    try {
        tmpFile = File.createTempFile(prefix, suffix);
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        throw new StepExecutionException("Error creating temporary file " + e.getMessage(), step);
    }
    tmpFile.deleteOnExit();
    return tmpFile;
}

From source file:Main.java

/** Carga una librer&iacute;a nativa del sistema.
 * @param path Ruta a la libreria de sistema.
 * @throws IOException Si ocurre alg&uacute;n problema durante la carga */
public static void loadNativeLibrary(final String path) throws IOException {
    if (path == null) {
        LOGGER.warning("No se puede cargar una biblioteca nula"); //$NON-NLS-1$
        return;//from w  ww .j a  va  2 s.  c o  m
    }
    final int pos = path.lastIndexOf('.');
    final File file = new File(path);
    final File tempLibrary = File.createTempFile(
            pos < 1 ? file.getName() : file.getName().substring(0, file.getName().indexOf('.')),
            pos < 1 || pos == path.length() - 1 ? null : path.substring(pos));

    // Copiamos el fichero
    copyFile(file, tempLibrary);

    // Pedimos borrar los temporales cuando se cierre la JVM
    if (tempLibrary != null) {
        tempLibrary.deleteOnExit();
    }

    LOGGER.info("Cargamos " + (tempLibrary == null ? path : tempLibrary.getAbsolutePath())); //$NON-NLS-1$
    System.load(tempLibrary != null ? tempLibrary.getAbsolutePath() : path);

}

From source file:$.FileUtils.java

/**
     * Get temporary file//from  w  w w  .  ja  v  a  2  s  . co m
     * @param name File name
     * @param suffix Suffix
     * @return Temp file folder
     */
    public static File getTmpFile(final String name, final String suffix) {
        String suffixToUse = suffix == null ? ".tmp" : suffix;
        if (!suffixToUse.startsWith(".")) {
            suffixToUse = "." + suffix;
        }
        String nameToUse = name == null ? "tmp" : name;
        File input = null;
        try {
            File folder = new File(JAVA_TMP, FileUtils.TMP_DIR);
            if (!folder.exists()) {
                boolean mkdirs = folder.mkdirs();
                checkCreation(folder, mkdirs);
            }
            input = File.createTempFile(nameToUse, suffixToUse, folder);
            input.deleteOnExit();
        } catch (IOException e) {
            logger.error("An error occurred while creating the temporary file: \"" + name + suffix + "\"");
        }
        return input;
    }

From source file:com.sap.prd.mobile.ios.mios.StraightForwardLibAndAppTest.java

@BeforeClass
public static void __setup() throws Exception {

    dynamicVersion = "1.0." + String.valueOf(System.currentTimeMillis());
    myLibArtifactFilePrefix = TestConstants.GROUP_ID_WITH_SLASH + "/MyLibrary/" + dynamicVersion + "/MyLibrary-"
            + dynamicVersion;/*  ww w.  j  a  v  a 2  s.c o m*/
    testName = StraightForwardLibAndAppTest.class.getName() + File.separator
            + Thread.currentThread().getStackTrace()[1].getMethodName();

    remoteRepositoryDirectory = getRemoteRepositoryDirectory(StraightForwardLibAndAppTest.class.getName());

    prepareRemoteRepository(remoteRepositoryDirectory);

    Properties pomReplacements = new Properties();
    pomReplacements.setProperty(PROP_NAME_DEPLOY_REPO_DIR, remoteRepositoryDirectory.getAbsolutePath());
    pomReplacements.setProperty(PROP_NAME_DYNAMIC_VERSION, dynamicVersion);

    Map<String, String> additionalSystemProperties = new HashMap<String, String>();
    additionalSystemProperties.put("mios.ota-service.url",
            "http://apple-ota.wdf.sap.corp:8080/ota-service/HTML");
    additionalSystemProperties.put("xcode.app.defaultConfigurations", "Release");
    additionalSystemProperties.put("xcode.app.defaultSdks", "iphoneos");
    additionalSystemProperties.put("archive.dir", "archive");
    additionalSystemProperties.put("xcode.useSymbolicLinks", Boolean.TRUE.toString());

    test(testName, new File(getTestRootDirectory(), "straight-forward/MyLibrary"), "deploy", THE_EMPTY_LIST,
            THE_EMPTY_MAP, pomReplacements, new NullProjectModifier());

    appVerifier = test(testName, new File(getTestRootDirectory(), "straight-forward/MyApp"), "deploy",
            THE_EMPTY_LIST, additionalSystemProperties, pomReplacements, new NullProjectModifier());

    myAppVersionRepoDir = TestConstants.GROUP_ID_WITH_SLASH + "/MyApp/" + dynamicVersion;
    myAppArtifactFilePrefix = myAppVersionRepoDir + "/MyApp-" + dynamicVersion;

    final File tmpFolder = new File(getTargetDirectory(), "tests/tmp");
    tmpFolder.deleteOnExit();

    extractedIpaFolder = new File(tmpFolder, "ipa");
    extractFileWithShellScript(
            new File(remoteRepositoryDirectory, myAppArtifactFilePrefix + "-Release-iphoneos.ipa"),
            extractedIpaFolder);

    File appstoreUploadFile = new File(remoteRepositoryDirectory,
            myAppArtifactFilePrefix + "-Release-iphoneos-app.zip");
    assertTrue(appstoreUploadFile.exists());

    appstoreFolder = new File(tmpFolder, "appstoreFolder");
    appstoreFolder.deleteOnExit();
    extractFileWithShellScript(appstoreUploadFile, appstoreFolder);

    appTestBaseDir = new File(appVerifier.getBasedir());

    archiveArtifactsDir = new File(appTestBaseDir,
            "archive/artifacts/com.sap.ondevice.production.ios.tests/MyApp");
}

From source file:com.splunk.shuttl.testutil.TUtilsFile.java

/**
 * @return a new file having same contents (but different path) as the
 *         specified file.// w  ww.j a v  a  2s  . c  o m
 */
public static File createFileWithContentsOfFile(File file) {
    File newFile = createFile();
    try {
        FileUtils.copyFile(file, newFile);
    } catch (IOException e) {
        TUtilsTestNG.failForException("Couldn't create file with contents of " + file.toString(), e);
    }
    newFile.deleteOnExit();
    return newFile;
}

From source file:it.cnr.icar.eric.client.xml.registry.util.CertificateUtil.java

@SuppressWarnings("static-access")
private static Certificate[] getCertificateSignedByRegistry(LifeCycleManager lcm, X509Certificate inCert)
        throws JAXRException {
    Certificate[] certChain = new Certificate[2];

    try {/*from  w w w.  j  a v a 2  s  .  c  o m*/
        // Save cert in a temporary keystore file which is sent as
        // repository item to server so it can be signed
        KeyStore tmpKeystore = KeyStore.getInstance("JKS");
        tmpKeystore.load(null, bu.FREEBXML_REGISTRY_KS_PASS_REQ.toCharArray());

        tmpKeystore.setCertificateEntry(bu.FREEBXML_REGISTRY_USERCERT_ALIAS_REQ, inCert);
        File repositoryItemFile = File.createTempFile(".eric-ca-req", ".jks");
        repositoryItemFile.deleteOnExit();
        FileOutputStream fos = new java.io.FileOutputStream(repositoryItemFile);
        tmpKeystore.store(fos, bu.FREEBXML_REGISTRY_KS_PASS_REQ.toCharArray());
        fos.flush();
        fos.close();

        // Now have server sign the cert using extensionRequest
        javax.activation.DataHandler repositoryItem = new DataHandler(new FileDataSource(repositoryItemFile));
        String id = it.cnr.icar.eric.common.Utility.getInstance().createId();
        HashMap<String, Object> idToRepositoryItemsMap = new HashMap<String, Object>();
        idToRepositoryItemsMap.put(id, repositoryItem);

        HashMap<String, String> slotsMap = new HashMap<String, String>();
        slotsMap.put(BindingUtility.FREEBXML_REGISTRY_PROTOCOL_SIGNCERT, "true");

        RegistryRequestType req = bu.rsFac.createRegistryRequestType();
        bu.addSlotsToRequest(req, slotsMap);

        RegistryResponseHolder respHolder = ((LifeCycleManagerImpl) lcm).extensionRequest(req,
                idToRepositoryItemsMap);
        DataHandler responseRepositoryItem = (DataHandler) respHolder.getAttachmentsMap().get(id);

        InputStream is = responseRepositoryItem.getInputStream();
        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(is, bu.FREEBXML_REGISTRY_KS_PASS_RESP.toCharArray());
        is.close();

        certChain[0] = keyStore.getCertificate(bu.FREEBXML_REGISTRY_USERCERT_ALIAS_RESP);
        if (certChain[0] == null) {
            throw new JAXRException(JAXRResourceBundle.getInstance().getString("message.CannotFindUserCert"));
        }
        certChain[1] = keyStore.getCertificate(bu.FREEBXML_REGISTRY_CACERT_ALIAS);
        if (certChain[1] == null) {
            throw new JAXRException(JAXRResourceBundle.getInstance().getString("message.CannotFindCARootCert"));
        }
    } catch (Exception e) {
        throw new JAXRException(JAXRResourceBundle.getInstance().getString("message.CertSignFailed"), e);
    }

    return certChain;
}

From source file:org.paxml.selenium.rc.FileServer.java

/**
 * Host a string as file content, preferrably in a system temp file. If
 * system temp file does not work, host in memory. In either case, a file is
 * readable for only once./*w w  w  .j a  v  a2  s .  c  o  m*/
 * 
 * @param content
 *            the file content
 * @return the hosted path
 */
public static String hostFileContent(String content) {
    String path;
    File file;
    try {
        File dir = new File(TMP_DIR);
        dir.mkdirs();
        file = File.createTempFile(FileServer.class.getSimpleName() + "_", ".tmp", dir);
        file.deleteOnExit();

        FileOutputStream fout = new FileOutputStream(file, false);
        try {
            fout.write(content.getBytes("UTF-8"));
            fout.flush();
        } finally {
            IOUtils.closeQuietly(fout);
        }
        path = TMP_FILE_IDENT + file.getName();

    } catch (IOException e) {
        path = IN_MEM_IDENT + UUID.randomUUID().toString() + ".txt";
        if (null != memFiles.putIfAbsent(path, content)) {
            throw new RuntimeException("Duplicated in memory fike key: " + path);
        }

    }
    if (log.isDebugEnabled()) {
        log.debug("File content held in: " + path);
    }
    return path;

}

From source file:com.splunk.shuttl.testutil.TUtilsFile.java

public static File createFileInParent(File parent, String fileName) {
    File child = new File(parent, fileName);
    try {/*from   www  .ja v  a2  s  .co  m*/
        child.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
        TUtilsTestNG.failForException("Could not create file: " + child, e);
    }
    child.deleteOnExit();
    return child;
}