Example usage for java.nio.file Files createTempDirectory

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

Introduction

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

Prototype

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

Source Link

Document

Creates a new directory in the default temporary-file directory, using the given prefix to generate its name.

Usage

From source file:com.bekwam.resignator.commands.UnsignCommand.java

private Path createTempDir() throws CommandExecutionException {
    Path appDir = Paths.get(System.getProperty("user.home"), ".resignator");

    try {/*from   w ww .  j  a v  a 2s.com*/
        tempDir = Files.createTempDirectory(appDir, "");
    } catch (IOException exc) {
        String msg = String.format("can't create tempDir %s", tempDir.toString());
        logger.error(msg, exc);
        throw new CommandExecutionException(msg);
    }
    return appDir;
}

From source file:com.spectralogic.ds3client.metadata.MetadataAccessImpl_Test.java

@Test
public void testMetadataAccessFailureHandler() throws IOException, InterruptedException {
    Assume.assumeFalse(Platform.isWindows());

    try {/* w  w  w  .  j av a 2s .  c  om*/
        final String tempPathPrefix = null;
        final Path tempDirectory = Files.createTempDirectory(Paths.get("."), tempPathPrefix);

        final String fileName = "Gracie.txt";

        final Path filePath = Files.createFile(Paths.get(tempDirectory.toString(), fileName));

        try {
            tempDirectory.toFile().setExecutable(false);

            final ImmutableMap.Builder<String, Path> fileMapper = ImmutableMap.builder();

            fileMapper.put(filePath.toString(), filePath);
            new MetadataAccessImpl(fileMapper.build()).getMetadataValue(filePath.toString());
        } finally {
            tempDirectory.toFile().setExecutable(true);
            FileUtils.deleteDirectory(tempDirectory.toFile());
        }
    } catch (final Throwable t) {
        fail("Throwing exceptions from metadata est verbotten");
    }
}

From source file:org.apache.druid.data.input.impl.prefetch.PrefetchableTextFilesFirehoseFactoryTest.java

private static File createFirehoseTmpDir(String dirPrefix) throws IOException {
    return Files.createTempDirectory(tempDir.getRoot().toPath(), dirPrefix).toFile();
}

From source file:com.spectralogic.ds3client.metadata.MetadataReceivedListenerImpl_Test.java

@Test
public void testGettingMetadataFailureDoesntThrow() throws IOException, InterruptedException {
    Assume.assumeFalse(Platform.isWindows());

    try {/*from   w ww  .j a v a 2 s.c  om*/
        final String tempPathPrefix = null;
        final Path tempDirectory = Files.createTempDirectory(Paths.get("."), tempPathPrefix);

        final String fileName = "Gracie.txt";

        final Path filePath = Files.createFile(Paths.get(tempDirectory.toString(), fileName));

        try {
            // set permissions
            if (!Platform.isWindows()) {
                final PosixFileAttributes attributes = Files.readAttributes(filePath,
                        PosixFileAttributes.class);
                final Set<PosixFilePermission> permissions = attributes.permissions();
                permissions.clear();
                permissions.add(PosixFilePermission.OWNER_READ);
                permissions.add(PosixFilePermission.OWNER_WRITE);
                Files.setPosixFilePermissions(filePath, permissions);
            }

            // get permissions
            final ImmutableMap.Builder<String, Path> fileMapper = ImmutableMap.builder();
            fileMapper.put(filePath.toString(), filePath);
            final Map<String, String> metadataFromFile = new MetadataAccessImpl(fileMapper.build())
                    .getMetadataValue(filePath.toString());

            FileUtils.deleteDirectory(tempDirectory.toFile());

            // put old permissions back
            final Metadata metadata = new MetadataImpl(new MockedHeadersReturningKeys(metadataFromFile));

            new MetadataReceivedListenerImpl(tempDirectory.toString()).metadataReceived(fileName, metadata);
        } finally {
            FileUtils.deleteDirectory(tempDirectory.toFile());
        }
    } catch (final Throwable t) {
        fail("Throwing exceptions from metadata est verbotten");
    }
}

From source file:org.corehunter.tests.data.simple.SimpleDistanceMatrixDataTest.java

@Test
public void toCsvFile() throws IOException {
    dataName = "out.csv";
    expectedHeaders = HEADERS_UNIQUE_NAMES;

    SimpleDistanceMatrixData distanceData = new SimpleDistanceMatrixData(expectedHeaders, DISTANCES);

    Path path = Paths.get(TEST_OUTPUT);

    Files.createDirectories(path);

    path = Files.createTempDirectory(path, "DistanceMatrix-Csv");

    path = Paths.get(path.toString(), dataName);

    Files.deleteIfExists(path);//  w  ww  .ja  v  a 2  s  . c o m

    System.out.println(" |- Write distance File " + dataName);
    distanceData.writeData(path, FileType.CSV);

    testData(SimpleDistanceMatrixData.readData(path, FileType.CSV));
}

From source file:de.unirostock.sems.cbarchive.web.VcImporter.java

private static File cloneHg(String link, ArchiveFromHg archive) throws IOException, TransformerException,
        JDOMException, ParseException, CombineArchiveException, CombineArchiveWebException {
    // create new temp dir
    File tempDir = Files
            .createTempDirectory(Fields.TEMP_FILE_PREFIX,
                    PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------")))
            .toFile();/*from   w  ww  .  j  av a2  s . c  o  m*/
    if (!tempDir.isDirectory() && !tempDir.mkdirs())
        throw new CombineArchiveWebException(
                "The temporary directories could not be created: " + tempDir.getAbsolutePath());

    // temp file for CombineArchive
    File archiveFile = File.createTempFile(Fields.TEMP_FILE_PREFIX, "ca-imported");
    archiveFile.delete(); // delete the tmp file, so the CombineArchive Lib will create a new file
    // create the archive
    CombineArchive ca = new CombineArchive(archiveFile);

    Repository repo = Repository.clone(tempDir, link);
    if (repo == null) {
        ca.close();
        LOGGER.error("Cannot clone Mercurial Repository ", link, " into ", tempDir);
        throw new CombineArchiveWebException("Cannot clone Mercurial Repository " + link + " into " + tempDir);
    }

    List<File> relevantFiles = scanRepository(tempDir, repo);
    System.out.println("before LogCommand");
    LogCommand logCmd = new LogCommand(repo);
    System.out.println("after LogCommand");
    for (File cur : relevantFiles) {
        List<Changeset> relevantVersions = logCmd.execute(cur.getAbsolutePath());

        ArchiveEntry caFile = ca.addEntry(tempDir, cur, Formatizer.guessFormat(cur));

        // lets create meta!
        List<Date> modified = new ArrayList<Date>();
        List<VCard> creators = new ArrayList<VCard>();

        HashMap<String, VCard> users = new HashMap<String, VCard>();
        for (Changeset cs : relevantVersions) {
            LOGGER.debug("cs: " + cs.getTimestamp().getDate() + " -- " + cs.getUser());
            modified.add(cs.getTimestamp().getDate());

            String vcuser = cs.getUser();
            String firstName = "";
            String lastName = "";
            String mail = "";

            String[] tokens = vcuser.split(" ");
            int lastNameToken = tokens.length - 1;
            // is there a mail address?
            if (tokens[lastNameToken].contains("@")) {
                mail = tokens[lastNameToken];
                if (mail.startsWith("<") && mail.endsWith(">"))
                    mail = mail.substring(1, mail.length() - 1);
                lastNameToken--;
            }

            // search for a non-empty last name
            while (lastNameToken >= 0) {
                if (tokens[lastNameToken].length() > 0) {
                    lastName = tokens[lastNameToken];
                    break;
                }
                lastNameToken--;
            }

            // and first name of course...
            for (int i = 0; i < lastNameToken; i++) {
                if (tokens[i].length() > 0)
                    firstName += tokens[i] + " ";
            }
            firstName = firstName.trim();

            String userid = "[" + firstName + "] -- [" + lastName + "] -- [" + mail + "]";
            LOGGER.debug("this is user: " + userid);
            if (users.get(userid) == null) {
                users.put(userid, new VCard(lastName, firstName, mail, null));
            }
        }

        for (VCard vc : users.values())
            creators.add(vc);

        caFile.addDescription(new OmexMetaDataObject(
                new OmexDescription(creators, modified, modified.get(modified.size() - 1))));

    }

    ca.pack();
    ca.close();
    repo.close();

    // clean up the directory
    FileUtils.deleteDirectory(tempDir);

    // add the combine archive to the dataholder
    if (archive != null) {
        //TODO ugly workaround with the lock. 
        archive.setArchiveFile(archiveFile, null);
        archive.getArchive().close();
    }

    return archiveFile;
}

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

@Test
public void testThatFileReportsAsRegularOnWindows() throws IOException, InterruptedException {
    Assume.assumeTrue(Platform.isWindows());

    final String tempPathPrefix = null;
    final Path tempDirectory = Files.createTempDirectory(Paths.get("."), tempPathPrefix);

    final String A_FILE_NAME = "aFile.txt";

    final AtomicBoolean caughtException = new AtomicBoolean(false);

    try {/*from  w  w  w  .  j av a2s  . c o m*/
        Files.createFile(Paths.get(tempDirectory.toString(), A_FILE_NAME));
        new FileObjectPutter(tempDirectory).buildChannel(A_FILE_NAME);
    } catch (final UnrecoverableIOException e) {
        assertTrue(e.getMessage().contains(A_FILE_NAME));
        caughtException.set(true);
    } finally {
        FileUtils.deleteDirectory(tempDirectory.toFile());
    }

    assertFalse(caughtException.get());
}

From source file:com.spectralogic.ds3client.metadata.MetadataAccessImpl_Test.java

@Test
public void testMetadataAccessFailureHandlerWithEventHandler() throws IOException, InterruptedException {
    Assume.assumeFalse(Platform.isWindows());

    final String tempPathPrefix = null;
    final Path tempDirectory = Files.createTempDirectory(Paths.get("."), tempPathPrefix);

    final String fileName = "Gracie.txt";

    final Path filePath = Files.createFile(Paths.get(tempDirectory.toString(), fileName));

    try {/*from ww  w.  j  a v a2s  . c  om*/
        tempDirectory.toFile().setExecutable(false);

        final ImmutableMap.Builder<String, Path> fileMapper = ImmutableMap.builder();

        fileMapper.put(filePath.toString(), filePath);

        final AtomicInteger numTimesFailureHandlerCalled = new AtomicInteger(0);

        try (final InputStream inputStream = Runtime.getRuntime().exec("ls -lR").getInputStream()) {
            LOG.info(IOUtils.toString(inputStream));
        }
        new MetadataAccessImpl(fileMapper.build(), new FailureEventListener() {
            @Override
            public void onFailure(final FailureEvent failureEvent) {
                numTimesFailureHandlerCalled.incrementAndGet();
                assertEquals(FailureEvent.FailureActivity.RecordingMetadata, failureEvent.doingWhat());
            }
        }, "localhost").getMetadataValue("forceAFailureByUsingANonExistentFileBecauseTheDockerImageRunsAsRoot");

        assertEquals(1, numTimesFailureHandlerCalled.get());
    } finally {
        tempDirectory.toFile().setExecutable(true);
        FileUtils.deleteDirectory(tempDirectory.toFile());
    }
}

From source file:org.corehunter.tests.data.simple.SimpleDistanceMatrixDataTest.java

@Test
public void toCsvFileWithAllIds() throws IOException {
    expectedHeaders = HEADERS_UNIQUE_NAMES;
    SimpleDistanceMatrixData distanceData = new SimpleDistanceMatrixData(expectedHeaders, DISTANCES);

    Set<Integer> ids = distanceData.getIDs();

    Path dirPath = Paths.get(TEST_OUTPUT);

    Files.createDirectories(dirPath);

    dirPath = Files.createTempDirectory(dirPath, "DistanceMatrix-AllIds");

    // create solution
    SubsetSolution solution = new SubsetSolution(ids);
    for (int sel : SELECTION) {
        solution.select(sel);/*from   ww w .j a va2s .c  o m*/
    }

    Path path;

    // write with integer ids
    dataName = "with-ids.csv";

    path = Paths.get(dirPath.toString(), dataName);

    System.out.println(" |- Write distance matrix file (with solution) " + dataName);

    distanceData.writeData(path, FileType.CSV, solution, true, true, true);

    assertTrue("Output is not correct!", FileUtils.contentEquals(new File(
            SimpleDistanceMatrixDataTest.class.getResource("/distances/out/all-with-ids.csv").getPath()),
            path.toFile()));

    // write without integer ids
    dataName = "no-ids.csv";

    path = Paths.get(dirPath.toString(), dataName);

    System.out.println(" |- Write distance matrix file (with solution) " + dataName);

    distanceData.writeData(path, FileType.CSV, solution, false, true, true);

    assertTrue("Output is not correct!",
            FileUtils.contentEquals(new File(
                    SimpleDistanceMatrixDataTest.class.getResource("/distances/out/all-no-ids.csv").getPath()),
                    path.toFile()));

}

From source file:net.ripe.rpki.validator.commands.BottomUpCertificateRepositoryObjectValidator.java

private File getUniqueTempDir() {
    try {//w  w  w.  j  a va2 s.co  m
        return Files.createTempDirectory(Paths.get(ConfigurationUtil.getTempDirectory()), "val").toFile();
    } catch (IOException e) {
        throw new ValidatorIOException("Could not create temp directory", e);
    }
}