Example usage for java.nio.file Files createTempFile

List of usage examples for java.nio.file Files createTempFile

Introduction

In this page you can find the example usage for java.nio.file Files createTempFile.

Prototype

public static Path createTempFile(String prefix, String suffix, FileAttribute<?>... attrs) throws IOException 

Source Link

Document

Creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name.

Usage

From source file:org.forgerock.openidm.maintenance.upgrade.StaticFileUpdateTest.java

@BeforeMethod
public void createTempFile() throws IOException {
    tempFile = Files.createTempFile(tempPath, null, null);
}

From source file:org.pentaho.di.job.entries.copyfiles.JobEntryCopyFilesIT.java

@Test
public void copyFileWithoutOverwrite() throws Exception {
    entry.setoverwrite_files(false);//from www  .  j  a va  2 s.  com

    Path pathToFile = Files.createTempFile(source, "file", "");

    FileUtils.copyDirectory(source.toFile(), destination.toFile());
    String path = destination.resolve(pathToFile.getFileName()).toString();
    File file = new File(path);

    long createTime = file.lastModified();
    Result result = entry.execute(new Result(), 0);
    long copyTime = file.lastModified();

    assertTrue(result.getResult());
    assertEquals(0, result.getNrErrors());
    assertTrue("File shouldn't be overwritten", createTime == copyTime);
}

From source file:org.schedulesdirect.api.exception.JsonEncodingException.java

/**
 * Generate the capture file for this exception, if requested
 */// w  w w .j a  v a 2  s . c o  m
protected void capture() {
    Config conf = Config.get();
    if (conf.captureJsonEncodingErrors()) {
        String msg = generateMsg();
        try {
            Path p = Paths.get(conf.captureRoot().getAbsolutePath(), "encode");
            if (!targetCleaned && Files.exists(p))
                try {
                    FileUtils.deleteDirectory(p.toFile());
                } catch (IOException e) {
                    LOG.warn(String.format("Unable to clean target dir! [%s]", p));
                }
            targetCleaned = true;
            Files.createDirectories(p);
            Path f = Files.createTempFile(p, prefix(), ".err");
            Files.write(f, msg.getBytes("UTF-8"));
        } catch (IOException e) {
            LOG.error("Unable to write capture file, logging it instead!", e);
            LOG.error(String.format("Invalid JSON received!%n%s", msg), this);
        }
    }
}

From source file:ubicrypt.core.UtilsTest.java

@Test
public void readIs() throws Exception {
    final SecureRandom rnd = new SecureRandom();
    rnd.setSeed(System.currentTimeMillis());
    final byte[] key = new byte[3 * (1 << 16)];
    rnd.nextBytes(key);/* ww  w .j ava  2  s .  c o  m*/

    final Path path = Files.createTempFile(TestUtils.tmp, "a", "b");
    Utils.write(path, new ByteArrayInputStream(key)).toBlocking().last();

    final byte[] bytes = IOUtils.toByteArray(Utils.readIs(path));
    final byte[] bytes2 = IOUtils.toByteArray(Files.newInputStream(path));
    assertThat(bytes.length).isEqualTo(bytes2.length);
    for (int i = 0; i < bytes.length; i++) {
        assertThat(bytes[i]).isEqualTo(bytes2[i]);
    }
}

From source file:org.schedulesdirect.api.exception.InvalidJsonObjectException.java

/**
 * Generate the capture file for this exception, if requested
 *///from   www .j a  v  a 2s  . c om
protected void capture() {
    Config conf = Config.get();
    if (conf.captureJsonParseErrors()) {
        String msg = generateMsg();
        try {
            Path p = Paths.get(conf.captureRoot().getAbsolutePath(), "json");
            if (!targetCleaned && Files.exists(p))
                try {
                    FileUtils.deleteDirectory(p.toFile());
                } catch (IOException e) {
                    LOG.warn(String.format("Unable to clean target dir! [%s]", p));
                }
            targetCleaned = true;
            Files.createDirectories(p);
            Path f = Files.createTempFile(p, prefix(), ".err");
            Files.write(f, msg.getBytes("UTF-8"));
        } catch (IOException e) {
            LOG.error("Unable to write capture file, logging it instead!", e);
            LOG.error(String.format("Invalid JSON received!%n%s", msg), this);
        }
    }
}

From source file:com.dowdandassociates.gentoo.bootstrap.DefaultKeyPairInformation.java

@PostConstruct
private void setup() {
    boolean nameSet = (null != name);
    boolean filenameSet = (null != filename);
    boolean keyExists = false;
    if (nameSet) {
        log.info("Checking if key pair \"" + name + "\" exists");
        keyExists = !(ec2Client/*from w  w w . ja  v  a2s  .com*/
                .describeKeyPairs(new DescribeKeyPairsRequest()
                        .withFilters(new Filter().withName("key-name").withValues(name)))
                .getKeyPairs().isEmpty());
    }

    if (keyExists && !filenameSet) {
        log.warn("Key pair \"" + name + "\" exists, but private key location is not specified");
        keyExists = false;
    }

    if (!keyExists) {
        if (!nameSet) {
            name = "gentoo-bootstrap-"
                    + DateFormatUtils.formatUTC(System.currentTimeMillis(), "yyyyMMdd'T'HHmmssSSS'Z'");
        }

        if (!filenameSet) {
            try {
                filename = Files
                        .createTempFile(name, ".pem",
                                PosixFilePermissions
                                        .asFileAttribute(PosixFilePermissions.fromString("rw-------")))
                        .toString();
            } catch (IOException ioe) {
                log.warn("Cannot create temp file", ioe);
                filename = name + ".pem";
            }
        }

        log.info("Creating key pair \"" + name + "\"");

        CreateKeyPairResult createResult = ec2Client
                .createKeyPair(new CreateKeyPairRequest().withKeyName(name));

        try {
            log.info("Saving pem file to \"" + filename + "\"");

            BufferedWriter outfile = new BufferedWriter(new FileWriter(filename));

            try {
                outfile.write(createResult.getKeyPair().getKeyMaterial());
            } catch (IOException ioe) {
                String message = "Error writing to file \"" + filename + "\"";
                log.error(message, ioe);
                throw new RuntimeException(message, ioe);
            } finally {
                outfile.close();
            }
        } catch (IOException ioe) {
            String message = "Error opening file \"" + filename + "\"";
            log.error(message, ioe);
            throw new RuntimeException(message, ioe);
        }

        builtKeyPair = true;

        log.info("Key pair \"" + name + "\" built");
    } else {
        builtKeyPair = false;
        log.info("Key pair \"" + name + "\" exists");
    }

    if (filename.startsWith("~" + File.separator)) {
        filename = System.getProperty("user.home") + filename.substring(1);
    }
}

From source file:org.apache.taverna.download.impl.DownloadManagerImpl.java

@Override
public void download(URI source, Path destination, String digestAlgorithm, URI digestSource)
        throws DownloadException {

    MessageDigest md = null;/*from w  w w . j a  va2  s  . co m*/
    if (digestAlgorithm != null) {
        try {
            md = MessageDigest.getInstance(digestAlgorithm);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException("Unsupported digestAlgorithm: " + digestAlgorithm, e);
        }
    }

    // download the file
    Path tempFile;
    try {
        tempFile = Files.createTempFile(destination.getParent(), "." + destination.getFileName(), ".tmp");
    } catch (IOException e1) {
        // perhaps a permission problem?
        throw new DownloadException("Can't create temporary file in folder " + destination.getParent(), e1);
    }
    logger.info(String.format("Downloading %1$s to %2$s", source, tempFile));
    downloadToFile(source, tempFile);

    if (digestSource != null) {
        // download the digest file
        String expectedDigest;
        expectedDigest = downloadHash(digestSource).trim().toLowerCase(Locale.ROOT);
        // check if the digest matches
        try {
            try (InputStream s = Files.newInputStream(tempFile)) {
                DigestUtils.updateDigest(md, s);
                String actualDigest = Hex.encodeHexString(md.digest());
                if (!actualDigest.equals(expectedDigest)) {
                    throw new DownloadException(
                            String.format("Error downloading file: checksum mismatch (%1$s != %2$s)",
                                    actualDigest, expectedDigest));
                }
            }
        } catch (IOException e) {
            throw new DownloadException(String.format("Error checking digest for %1$s", destination), e);
        }
    }
    // All fine, move to destination
    try {
        logger.info(String.format("Copying %1$s to %2$s", tempFile, destination));
        Files.move(tempFile, destination, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        throw new DownloadException(String.format("Error downloading %1$s to %2$s.", source, destination), e);
    }

}

From source file:com.spectralogic.ds3client.helpers.FileObjectPutter_Test.java

@Test
public void testRelativeSymlink() throws IOException, URISyntaxException {
    assumeFalse(Platform.isWindows());/*from  www . ja  v a2  s .c om*/
    final Path tempDir = Files.createTempDirectory("ds3_file_object_rel_test_");
    final Path tempPath = Files.createTempFile(tempDir, "temp_", ".txt");

    try {
        try (final SeekableByteChannel channel = Files.newByteChannel(tempPath, StandardOpenOption.CREATE,
                StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) {
            channel.write(ByteBuffer.wrap(testData));
        }

        final Path symLinkPath = tempDir.resolve("sym_" + tempPath.getFileName().toString());
        final Path relPath = Paths.get("..", getParentDir(tempPath), tempPath.getFileName().toString());

        LOG.info("Creating symlink from " + symLinkPath.toString() + " to " + relPath.toString());

        Files.createSymbolicLink(symLinkPath, relPath);
        getFileWithPutter(tempDir, symLinkPath);

    } finally {
        Files.deleteIfExists(tempPath);
        Files.deleteIfExists(tempDir);
    }
}

From source file:eu.itesla_project.online.tools.CreateMclaMat.java

private void createMat(Network network, Path outputFolder) throws IOException {
    System.out.println("creating mat file for network" + network.getId());
    ArrayList<String> generatorsIds = NetworkUtils.getGeneratorsIds(network);
    ArrayList<String> loadsIds = NetworkUtils.getLoadsIds(network);
    SamplingNetworkData samplingNetworkData = new SamplingDataCreator(network, generatorsIds, loadsIds)
            .createSamplingNetworkData();
    Path networkDataMatFile = Files.createTempFile(outputFolder, "mcsamplerinput_" + network.getId() + "_",
            ".mat");
    System.out/*from   ww w  .j  av  a 2s  .  c  o  m*/
            .println("saving data of network " + network.getId() + " in file " + networkDataMatFile.toString());
    new MCSMatFileWriter(networkDataMatFile).writeSamplingNetworkData(samplingNetworkData);
}

From source file:org.pentaho.di.job.entries.copyfiles.JobEntryCopyFilesIT.java

@Test
public void copyFileFromSubDirectoryWithoutOverwrite() throws Exception {
    entry.setIncludeSubfolders(true);//from  www  .  ja va2  s .  co  m
    entry.setoverwrite_files(false);

    Path pathToSub = Files.createTempDirectory(source, "sub");
    Path pathToFile = Files.createTempFile(pathToSub, "file", "");

    FileUtils.copyDirectory(source.toFile(), destination.toFile());
    String path = destination.resolve(pathToSub.getFileName()).resolve(pathToFile.getFileName()).toString();
    File file = new File(path);

    long createTime = file.lastModified();
    Result result = entry.execute(new Result(), 0);
    long copyTime = file.lastModified();

    assertTrue(result.getResult());
    assertEquals(0, result.getNrErrors());
    assertTrue("File shouldn't be overwritten", createTime == copyTime);
}