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.spectralogic.ds3client.helpers.FileObjectGetter_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 {/*w  w  w  .j  a  v  a2 s  . com*/
        Files.createFile(Paths.get(tempDirectory.toString(), A_FILE_NAME));
        new FileObjectGetter(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:it.polimi.diceH2020.launcher.utility.FileUtility.java

public @NotNull File createTempZip(@NotNull Map<String, String> inputFiles) throws IOException {
    File folder = Files.createTempDirectory(settings.getWorkingDirectory().toPath(), null).toFile();
    policy.markForDeletion(folder);/*  www.ja v  a 2s.  c o m*/

    List<File> tempFiles = new LinkedList<>();
    for (Map.Entry<String, String> entry : inputFiles.entrySet()) {
        File tmp = new File(folder, entry.getKey());
        if (tmp.getParentFile().mkdirs() || tmp.getParentFile().isDirectory()) {
            tempFiles.add(tmp);
            Files.write(tmp.toPath(), Compressor.decompress(entry.getValue()).getBytes(),
                    StandardOpenOption.CREATE_NEW);
        } else
            throw new IOException("could not prepare directory structure for ZIP file");
    }

    String fileName = String.format("%s.zip", folder.getName());
    File zip = new File(settings.getWorkingDirectory(), fileName);
    policy.markForDeletion(zip);
    zipFolder(folder, zip);

    tempFiles.forEach(policy::delete);
    policy.delete(folder);

    return zip;
}

From source file:io.syndesis.git.GitWorkflow.java

/**
 * Creates a new remote git repository and does the initial commit&push of all the project files
 * the files to it.//www . ja v a2s .  c o m
 *
 * @param remoteGitRepoHttpUrl- the HTML (not ssh) url to a git repository
 * @param repoName              - the name of the git repository
 * @param author                author
 * @param message-              commit message
 * @param files-                map of file paths along with their content
 * @param credentials-          Git credentials, for example username/password, authToken, personal access token
 */
public void createFiles(String remoteGitRepoHttpUrl, String repoName, User author, String message,
        Map<String, byte[]> files, UsernamePasswordCredentialsProvider credentials) {

    try {
        // create temporary directory
        Path workingDir = Files.createTempDirectory(Paths.get(gitProperties.getLocalGitRepoPath()), repoName);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Created temporary directory {}", workingDir.toString());
        }

        // git init
        Git git = Git.init().setDirectory(workingDir.toFile()).call();
        writeFiles(workingDir, files);

        RemoteAddCommand remoteAddCommand = git.remoteAdd();
        remoteAddCommand.setName("origin");
        remoteAddCommand.setUri(new URIish(remoteGitRepoHttpUrl));
        remoteAddCommand.call();

        commitAndPush(git, authorName(author), author.getEmail(), message, credentials);
        removeWorkingDir(workingDir);
    } catch (IOException | GitAPIException | URISyntaxException e) {
        throw SyndesisServerException.launderThrowable(e);
    }
}

From source file:fi.helsinki.cs.iot.hub.JavascriptPluginTest.java

/**
 * @throws java.lang.Exception// w w w . jav a  2 s  .c om
 */
@Before
public void setUp() throws Exception {
    libdir = Files.createTempDirectory(Paths.get(System.getProperty("user.dir")), "jtest");
    //Delete the temporary directory
    libdir.toFile().deleteOnExit();
    PluginManager.getInstance().setJavascriptPluginHelper(new JavascriptPluginHelperImpl(libdir));
}

From source file:edu.harvard.iq.dataverse.ThemeWidgetFragment.java

private void createTempDir() {
    try {/*from   w  w w .ja va2s  .  c  o  m*/
        File tempRoot = Files.createDirectories(Paths.get("../docroot/logos/temp")).toFile();
        tempDir = Files.createTempDirectory(tempRoot.toPath(), editDv.getId().toString()).toFile();
    } catch (IOException e) {
        throw new RuntimeException("Error creating temp directory", e); // improve error handling
    }
}

From source file:act.installer.pubchem.PubchemTTLMergerTest.java

@Before
public void setUp() throws Exception {
    // Create a temporary directory where the RocksDB will live.
    tempDirPath = Files.createTempDirectory(PubchemTTLMergerTest.class.getName(), new FileAttribute[0]);
}

From source file:io.github.infolis.algorithm.Indexer.java

@Override
public void execute() throws IOException {
    File indexDir;//from   w w w .j  a va2  s. co  m
    if (null != getExecution().getIndexDirectory() && !getExecution().getIndexDirectory().isEmpty()) {
        indexDir = new File(getExecution().getIndexDirectory());
    } else {
        indexDir = new File(
                Files.createTempDirectory(InfolisConfig.getTmpFilePath().toAbsolutePath(), INDEX_DIR_PREFIX)
                        .toString());
        FileUtils.forceDeleteOnExit(indexDir);
    }
    log.debug("Indexing to: " + indexDir.getAbsolutePath());
    getExecution().setOutputDirectory(indexDir.getAbsolutePath().toString());

    IndexWriterConfig indexWriterConfig = new IndexWriterConfig(Version.LUCENE_35, createAnalyzer());
    indexWriterConfig.setOpenMode(OpenMode.CREATE);
    FSDirectory fsIndexDir = FSDirectory.open(indexDir);

    List<InfolisFile> files = new ArrayList<>();
    for (String fileUri : getExecution().getInputFiles()) {
        try {
            files.add(this.getInputDataStoreClient().get(InfolisFile.class, fileUri));
        } catch (Exception e) {
            error(log, "Could not retrieve file " + fileUri + ": " + e.getMessage());
            getExecution().setStatus(ExecutionStatus.FAILED);
            persistExecution();
            return;
        }
    }

    Date start = new Date();
    log.debug("Starting to index");
    IndexWriter writer = new IndexWriter(fsIndexDir, indexWriterConfig);
    try {
        int counter = 0;
        for (InfolisFile file : files) {
            counter++;
            log.trace("Indexing file " + file);
            writer.addDocument(toLuceneDocument(getInputFileResolver(), file));
            updateProgress(counter, files.size());

        }
    } catch (FileNotFoundException fnfe) {
        // NOTE: at least on windows, some temporary files raise this
        // exception with an "access denied" message checking if the
        // file can be read doesn't help
        throw new RuntimeException("Could not write index entry: " + fnfe);
    } finally {
        log.debug("Merging all Lucene segments ...");
        writer.forceMerge(1);
        writer.close();
    }
    getExecution().setStatus(ExecutionStatus.FINISHED);
    fsIndexDir.close();
    log.debug(String.format("Indexing %s documents took %s ms", files.size(),
            new Date().getTime() - start.getTime()));
}

From source file:org.apache.spark.sql.hive.thriftserver.rsc.RSCDriver.java

public RSCDriver(SparkConf conf, RSCConf livyConf) throws Exception {
    Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwx------");
    this.localTmpDir = Files.createTempDirectory("rsc-tmp", PosixFilePermissions.asFileAttribute(perms))
            .toFile();/* ww  w  .j a  v a2  s .  co  m*/
    this.executor = Executors.newCachedThreadPool();
    this.clients = new ConcurrentLinkedDeque<>();

    this.conf = conf;
    this.livyConf = livyConf;
    this.jcLock = new Object();
    this.shutdownLock = new Object();

    this.idleTimeout = new AtomicReference<>();
}

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

@Test
public void testThatSymbolicLinksAreResolved() {
    Assume.assumeFalse(Platform.isWindows());
    final String message = "Hello World";
    final String file = "file.txt";
    try {//  w  w  w  .  j  av a  2 s.co m
        final Path tempDirectory = Files.createTempDirectory(Paths.get(System.getProperty("java.io.tmpdir")),
                "ds3");
        final Path realDirectory = Files.createDirectory(Paths.get(tempDirectory.toString(), "dir"));
        final Path symbolicDirectory = Paths.get(tempDirectory.toString(), "symbolic");
        Files.createSymbolicLink(symbolicDirectory, realDirectory);
        Files.createFile(Paths.get(realDirectory.toString(), file));
        final ByteBuffer bb = ByteBuffer.wrap(message.getBytes());

        final SeekableByteChannel getterChannel = new FileObjectGetter(symbolicDirectory).buildChannel(file);
        getterChannel.write(bb);
        getterChannel.close();
        final String content = new String(Files.readAllBytes(Paths.get(realDirectory.toString(), file)));
        assertTrue(message.equals(content));
    } catch (final IOException e) {
        fail("Symbolic links are not handled correctly");
    }
}

From source file:de.unibi.cebitec.bibiserv.web.beans.runinthecloud.BashExecutor.java

/**
 * Receive and create the uniqueFolderDirectory in bibiserv/spool/tmp/.
 *
 * @return Path to UniqueFolder//from w w w.j av a  2 s  .c  om
 */
private Path getUniqueFolderDirectory() {
    try {
        return Files.createTempDirectory(Paths.get(rootPath), "ritc_");
    } catch (IOException iex) {
        log.error(iex.getMessage(), iex);
        return null;
    }
}