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:gobblin.source.extractor.extract.google.GoogleCommon.java

/**
 * As Google API only accepts java.io.File for private key, and this method copies private key into local file system.
 * Once Google credential is instantiated, it deletes copied private key file.
 *
 * @param privateKeyPath//from   ww  w  .j ava  2s  .  c o m
 * @param fsUri
 * @param id
 * @param transport
 * @param serviceAccountScopes
 * @return Credential
 * @throws IOException
 * @throws GeneralSecurityException
 */
private static Credential buildCredentialFromP12(String privateKeyPath, Optional<String> fsUri,
        Optional<String> id, HttpTransport transport, Collection<String> serviceAccountScopes)
        throws IOException, GeneralSecurityException {
    Preconditions.checkArgument(id.isPresent(), "user id is required.");

    FileSystem fs = getFileSystem(fsUri);
    Path keyPath = getPrivateKey(fs, privateKeyPath);

    final File localCopied = copyToLocal(fs, keyPath);
    localCopied.deleteOnExit();
    try {
        return new GoogleCredential.Builder().setTransport(transport).setJsonFactory(JSON_FACTORY)
                .setServiceAccountId(id.get()).setServiceAccountPrivateKeyFromP12File(localCopied)
                .setServiceAccountScopes(serviceAccountScopes).build();
    } finally {
        boolean isDeleted = localCopied.delete();
        if (!isDeleted) {
            throw new RuntimeException(localCopied.getAbsolutePath() + " has not been deleted.");
        }
    }
}

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

/**
 * Gets a test instance of this class that uses only the given mapping.
 *
 * @param instanceTypes       map of virtualization types to instance types
 * @param localizationContext the localization context
 * @return new mapping object/*from  w  ww  .ja va 2s.co m*/
 */
public static VirtualizationMappings getTestInstance(final Map<String, List<String>> instanceTypes,
        LocalizationContext localizationContext) {
    Map<String, String> propertyMap = Maps.transformValues(instanceTypes, new Function<List<String>, String>() {
        @Override
        public String apply(@Nonnull List<String> input) {
            return JOINER.join(input);
        }
    });
    PropertyResolver virtualizationMappingsResolver = PropertyResolvers.newMapPropertyResolver(propertyMap);
    File tempDir = Files.createTempDir();
    tempDir.deleteOnExit();
    VirtualizationMappingsConfigProperties virtualizationMappingsConfigProperties = new VirtualizationMappingsConfigProperties(
            new SimpleConfiguration(), tempDir, localizationContext);
    return new VirtualizationMappings(virtualizationMappingsConfigProperties, virtualizationMappingsResolver);
}

From source file:com.pinterest.secor.util.FileUtil.java

public static void deleteOnExit(String path) {
    File file = new File(path);
    file.deleteOnExit();
}

From source file:com.seleniumtests.uipage.htmlelements.GenericPictureElement.java

protected static File createFileFromResource(String resource) {
    try {//from  www . java2  s .  c o m
        File tempFile = File.createTempFile("img", null);
        tempFile.deleteOnExit();
        FileUtils.copyInputStreamToFile(
                Thread.currentThread().getContextClassLoader().getResourceAsStream(resource), tempFile);

        return tempFile;
    } catch (IOException e) {
        throw new ConfigurationException("Resource cannot be found", e);
    }
}

From source file:hudson.model.UserIdMigratorTest.java

static File createTestDirectory(Class clazz, TestName testName) throws IOException {
    File tempDirectory = Files.createTempDirectory(Paths.get("target"), "userIdMigratorTest").toFile();
    tempDirectory.deleteOnExit();
    copyTestDataIfExists(clazz, testName, tempDirectory);
    return new File(tempDirectory, "users");
}

From source file:net.sf.keystore_explorer.crypto.signing.MidletSigner.java

/**
 * Sign a MIDlet overwriting the supplied JAD file.
 *
 * @param jadFile// w  ww . j  a va2  s  .c o m
 *            JAD file
 * @param jarFile
 *            JAR file
 * @param privateKey
 *            Private RSA key to sign with
 * @param certificateChain
 *            Certificate chain for private key
 * @param certificateNumber
 *            Certificate number
 * @throws IOException
 *             If an I/O problem occurs while signing the MIDlet
 * @throws CryptoException
 *             If a crypto problem occurs while signing the MIDlet
 */
public static void sign(File jadFile, File jarFile, RSAPrivateKey privateKey,
        X509Certificate[] certificateChain, int certificateNumber) throws IOException, CryptoException {
    File tmpFile = File.createTempFile("kse", "tmp");
    tmpFile.deleteOnExit();

    sign(jadFile, tmpFile, jarFile, privateKey, certificateChain, certificateNumber);

    CopyUtil.copyClose(new FileInputStream(tmpFile), new FileOutputStream(jadFile));

    tmpFile.delete();
}

From source file:com.seleniumtests.util.FileUtility.java

public static void zipFolder(final File folder, final File destZipFile) {
    try {/*from w ww.j  a  v a2s.  c  om*/
        File tempZip = File.createTempFile(destZipFile.getName(), ".zip");
        tempZip.deleteOnExit();
        ZipUtil.pack(folder, tempZip);
        FileUtils.copyFile(tempZip, destZipFile);
    } catch (IOException e) {
        logger.error("cannot create zip file", e);
    }

}

From source file:com.wavemaker.testsupport.UtilTest.java

public static String lockSemaphore(String semaphoreName, int iter, int sleep) throws Exception {

    String tmpdir = System.getProperty("java.io.tmpdir");
    File tempFile = new File(new File(tmpdir), semaphoreName + ".lock");

    int slept = 0;
    while (slept < iter) {
        if (!tempFile.exists()) {
            try {
                tempFile.createNewFile();
                tempFile.deleteOnExit();
                break;
            } catch (IOException e) {
                // ignore
            }/*w w  w . jav  a2  s  .c om*/
        }

        Thread.sleep(sleep);
        slept++;
    }

    return tempFile.getAbsolutePath();
}

From source file:com.moz.fiji.schema.layout.FijiTableLayouts.java

/**
 * Creates a temporary JSON file with the specified layout.
 *
 * @param desc Layout descriptor.//from   w  w w .  ja  va 2s .com
 * @return Temporary JSON file containing the specified layout.
 * @throws IOException on I/O error.
 */
public static File getTempFile(TableLayoutDesc desc) throws IOException {
    final File layoutFile = File.createTempFile("layout-" + desc.getName(), "json");
    layoutFile.deleteOnExit();
    final OutputStream fos = new FileOutputStream(layoutFile);
    IOUtils.write(ToJson.toJsonString(desc), fos);
    ResourceUtils.closeOrLog(fos);
    return layoutFile;
}

From source file:org.cloudifysource.rest.util.RestUtils.java

/**
 * Creates a folder a unique name based on the given basicFolderName, inside the specified parent folder.
 * If the folder by that name already exists in the parent folder - a number is appended to that name, until
 * a unique name is found. e.g.: "myfolder1", "myfolder2" ... "myfolder99" (max index is set by maxAppender).
 * If all those names are already in use (meaning there are existing folders with these names) -
 * we create a completely new random name using "File.createTempFile".
 * //  www  . j a  v a  2 s .c o  m
 * @param parentFolder The folder to contain the new folder created by this method.
 * @param basicFolderName The base name to be used for the new folder. Numbers might be appended to this name to 
 * reach uniqueness. 
 * @param maxAppender The maximum number appended to the basic folder name to reach uniqueness. If a unique name
 * is not found for the folder and the maximum is reached, a new random name using "File.createTempFile".
 * @return The unique name
 * @throws IOException Indicates a failure to generate a unique folder name
 */
public static String createUniqueFolderName(final File parentFolder, final String basicFolderName,
        final int maxAppender) throws IOException {

    int index = 0;
    boolean uniqueNameFound = false;
    String folderName = basicFolderName;

    while (!uniqueNameFound && index < maxAppender) {
        //create a new name (temp1, temp2... temp99)
        folderName = basicFolderName + (++index);

        File restTempFolder = new File(parentFolder, folderName);
        if (!restTempFolder.exists()) {
            uniqueNameFound = true;
        }
    }

    if (!uniqueNameFound) {
        //create folder with a new unique name
        File tempFile = File.createTempFile(folderName, ".tmp");
        tempFile.deleteOnExit();
        folderName = StringUtils.substringBeforeLast(tempFile.getName(), ".tmp");
        uniqueNameFound = true;
    }

    if (uniqueNameFound) {
        return folderName;
    } else {
        throw new IOException(CloudifyMessageKeys.UPLOAD_DIRECTORY_CREATION_FAILED.getName());
    }
}