Java Code Examples for java.nio.file.Files#createTempDirectory()

The following examples show how to use java.nio.file.Files#createTempDirectory() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: copybara   File: GerritDestinationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testNoAllowEmptyPatchSet_delete() throws Exception {
  Path workTree = Files.createTempDirectory("populate");
  GitRepository repo = repo().withWorkTree(workTree);

  writeFile(workTree, "foo/bar/baz/foo.txt", "content!");
  writeFile(workTree, "other.txt", "not important");
  repo.add().all().run();
  repo.simpleCommand("commit", "-m", "Old parent");

  GitRevision oldParent = repo.resolveReference("HEAD");

  Files.delete(workTree.resolve("foo/bar/baz/foo.txt"));
  repo.add().all().run();
  repo.simpleCommand("commit", "-m", "previous patchset");

  GitRevision currentRev = repo.resolveReference("HEAD");
  repo.simpleCommand("update-ref", "refs/changes/10/12310/1", currentRev.getSha1());
  repo.simpleCommand("reset", "--hard", "HEAD~1");

  mockChangeFound(currentRev, 12310);

  runAllowEmptyPatchSetFalse(oldParent.getSha1());
}
 
Example 2
private static Path getTempRoot(Properties props) {
    String tempRoot = props.getProperty(JBOSS_EMBEDDED_ROOT, null);
    if (tempRoot == null) {
        return null;
    }

    try {
        File root = new File(tempRoot);
        if (!root.exists()) {
            //Attempt to try to create the directory, in case something like target/embedded was specified
            Files.createDirectories(root.toPath());
        }
        validateDirectory("jboss.test.clean.root", root);
        return Files.createTempDirectory(root.toPath(),"configs");//let OS handle the temp creation
    } catch (IOException e) {
        throw EmbeddedLogger.ROOT_LOGGER.cannotSetupEmbeddedServer(e);
    }
}
 
Example 3
@Test
void run() throws IOException {
    Path installFolder = Files.createTempDirectory("robozonky-install");
    Path robozonkyCli = Files.createTempFile(installFolder, "robozonky-", ".cli");
    Path distFolder = Files.createTempDirectory(installFolder, "dist");
    RunScriptGenerator generator = RunScriptGenerator.forWindows(distFolder.toFile(), robozonkyCli.toFile());
    assertThat(generator.getChildRunScript())
        .hasName("robozonky.bat");
    assertThat(generator.getRootFolder()
        .toPath())
            .isEqualTo(installFolder);
    File result = generator.apply(Arrays.asList("-a x", "-b"));
    String contents = Files.readString(result.toPath());
    String expected = "set \"JAVA_OPTS=%JAVA_OPTS% -a x -b\"\r\n" +
            distFolder + "\\robozonky.bat" + " @" + robozonkyCli;
    // toCharArray() is a hack to make this pass on Windows. The actual reason for failing is not know.
    assertThat(contents.toCharArray())
        .isEqualTo(expected.toCharArray());
}
 
Example 4
@Test
public void should_update_docs_for_sagan_when_current_version_newer_and_only_overview_adoc_exists()
		throws IOException {
	given(this.saganClient.updateRelease(BDDMockito.anyString(),
			BDDMockito.anyList())).willReturn(a2_0_0_ReleaseProject());

	Path tmp = Files.createTempDirectory("releaser-test");
	createFile(tmp, "sagan-index.adoc", "new text");
	SaganUpdater saganUpdater = new SaganUpdater(this.saganClient, this.properties) {
		@Override
		File docsModule(File projectFile) {
			return tmp.toFile();
		}
	};

	saganUpdater.updateSagan(new File("."), "master", version("3.0.0.RC1"),
			version("3.0.0.RC1"), projects);

	then(this.saganClient).should().patchProject(
			BDDMockito.argThat(argument -> "new text".equals(argument.rawOverview)));
}
 
Example 5
private void handleByImageMagick(Document doc, String fileNameSuffix) throws IOException {
    // Use ImageMagick to convert the image to pdf

    // Create a temp directory for each input document
    Path tempPath = Files.createTempDirectory(doc.getDocName());

    // Dump the binary content to a file in the temp directory
    File tempInputFile = new File(tempPath + File.separator + "file." + fileNameSuffix);
    FileUtils.writeByteArrayToFile(tempInputFile, doc.getBinaryContent());

    File tempOutputPdfFile = new File(tempPath + File.separator + "file.pdf");
    String[] cmd = { getImageMagickProg(), tempInputFile.getAbsolutePath(),
                     tempOutputPdfFile.getAbsolutePath()};

    try {
        externalProcessHandler(tempPath, cmd, doc.getDocName());
    }
    finally {
        tempInputFile.delete();
        tempPath.toFile().delete();
    }
}
 
Example 6
@NotNull
private Sdk createDummySdk(String sdkName) {
  try {
    Path sdkPath = Files.createTempDirectory("test-sdk-");
    Files.createDirectories(sdkPath.resolve("jre/lib"));
    Files.createFile(sdkPath.resolve("jre/lib/foo.jar"));
    return PantsSdkUtil.createAndRegisterJdk(sdkName, sdkPath.toString(), getTestRootDisposable());
  }
  catch (IOException e) {
    throw new UncheckedIOException(e);
  }
}
 
Example 7
Source Project: qpid-broker-j   File: AppenderUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDirectoryLogTarget() throws Exception
{
    Path unwriteableLogTargetPath = Files.createTempDirectory(getTestName());
    File unwriteableLogTarget = unwriteableLogTargetPath.toFile();

    try
    {
        doValidateLogTarget(unwriteableLogTargetPath.toFile());
    }
    finally
    {
        unwriteableLogTarget.delete();
    }
}
 
Example 8
@Before
public void setup() throws IOException {
    final java.nio.file.Path tmpDir = Files.createTempDirectory("hdfs-reader-test-");
    rootPath = new Path(tmpDir.toString());
    finalPath = new Path(rootPath, "final");
    tmpPath = new Path(rootPath, "tmp");
    localFs = FileSystem.getLocal(new Configuration());
    localFs.mkdirs(rootPath);
    localFs.mkdirs(finalPath);
    localFs.mkdirs(tmpPath);

    PrometheusMetrics.clearCollectors();
}
 
Example 9
@Test (expected = IllegalArgumentException.class)
public void testCopyFromFail() throws Throwable {
    Path dir = Files.createTempDirectory("copy_from_fail_test");
    Path testFile = dir.resolve("test.cfg");
    copyTestFile(testFile);
    ConfigTag configA = new StandardConfigFile(testFile).load();
    ConfigTag configB = configA.copy();
    configA.deleteTag("Tag1");
    configB.copyFrom(configA);
    ensureSame(configA, configB);
}
 
Example 10
@BeforeAll
public static void before() throws Exception {
    root = Files.createTempDirectory("quarkus-test");
    Files.write(root.resolve("a.txt"), "A file".getBytes(StandardCharsets.UTF_8));
    Files.write(root.resolve("b.txt"), "another file".getBytes(StandardCharsets.UTF_8));
    Files.createDirectories(root.resolve("foo"));
    Files.write(root.resolve("foo/sub.txt"), "subdir file".getBytes(StandardCharsets.UTF_8));
}
 
Example 11
Source Project: uima-uimaj   File: MigrateJCas.java    License: Apache License 2.0 5 votes vote down vote up
private static Path getTempDir() throws IOException {
  if (tempDir == null) {
    tempDir = Files.createTempDirectory("migrateJCas");
    tempDir.toFile().deleteOnExit();
  }
  return tempDir;
}
 
Example 12
Source Project: kafka-webview   File: UploadManagerTest.java    License: MIT License 5 votes vote down vote up
/**
 * Tests uploading a Deserializer file.
 */
@Test
public void testHandleKeyStoreUpload() throws IOException {
    // Make a temp directory
    final Path tempDirectory = Files.createTempDirectory(null);

    // Create a "multi-part" file
    final String mockContent = "test content";
    final MockMultipartFile myFile = new MockMultipartFile(
        "data",
        "filename.txt",
        "text/plain",
        mockContent.getBytes(StandardCharsets.UTF_8)
    );

    final String outputFilename = "MyUpload.jar";
    final String expectedUploadedPath = tempDirectory.toString() + "/keyStores/" + outputFilename;

    // Create manager
    final UploadManager uploadManager = new UploadManager(tempDirectory.toString());

    // Handle the "upload"
    final String result = uploadManager.handleKeystoreUpload(myFile, outputFilename);

    // Validate
    assertEquals("Has expected result filename", expectedUploadedPath, result);

    // Validate contents
    final Path filePath = new File(result).toPath();
    final byte[] contentBytes = Files.readAllBytes(filePath);
    final String contentString = new String(contentBytes, StandardCharsets.UTF_8);
    assertEquals("Contents are expected", mockContent, contentString);

    // Now test deleting a keystore
    final boolean deleteResult = uploadManager.deleteKeyStore(outputFilename);
    assertEquals("Should be true", true, deleteResult);
    assertFalse("File no longer exists", Files.exists(filePath));
}
 
Example 13
Source Project: vespa   File: StandaloneContainer.java    License: Apache License 2.0 5 votes vote down vote up
private static <T> T withTempDirectory(ThrowingFunction<Path, T> f) throws Exception {
    Path directory = Files.createTempDirectory("application");
    try {
        return f.apply(directory);
    } finally {
        IOUtils.recursiveDeleteDir(directory.toFile());
    }
}
 
Example 14
Source Project: aion   File: NativeZmqLoader.java    License: MIT License 5 votes vote down vote up
/**
 * Load native libs for ZMQ, unless:
 *   (1) this class has already loaded it once successfully (i.e. {@link #isLoaded()} is true), or
 *   (2) {@link #NO_EMBEDDED_LIB_FLAG} is set
 *
 * The following OSes are supported: Linux, Mac OS X, Windows.
 *
 * @implNote this method will write the native libs into a temporary location on disk
 * @throws IOException if failed to read/write native libs to/from temporary location
 */
public void load() {
    if(!LOADED_EMBEDDED_LIBRARY && System.getProperty(NO_EMBEDDED_LIB_FLAG) == null) {
        try {
            final Path libDir = Files.createTempDirectory("zmq_native");
            libDir.toFile().deleteOnExit();
            load(System.getProperty("os.name").toLowerCase(), libDir);
        } catch (IOException ioe) {
            throw new RuntimeException("Failed to persist and load native library for ZMQ", ioe);
        }
    } 
}
 
Example 15
FaultyFileSystem(Path root) throws IOException {
    if (root == null) {
        root = Files.createTempDirectory("faultyFS");
        removeRootAfterClose = true;
    } else {
        if (! Files.isDirectory(root)) {
            throw new IllegalArgumentException("must be a directory.");
        }
        removeRootAfterClose = false;
    }
    this.root = root;
    delegate = root.getFileSystem();
    isOpen = true;
}
 
Example 16
Source Project: HolandaCatalinaFw   File: FolderContext.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Unzip the specific file and create a temporal folder with all the content and returns
 * the new base folder for the context.
 * @param zipFilePath Specific file.
 * @return New base folder.
 */
private Path unzip(Path zipFilePath) throws IOException {
    ZipFile zipFile = new ZipFile(zipFilePath.toFile());
    Path tempFolder = Files.createTempDirectory(
            SystemProperties.getPath(SystemProperties.Net.Http.Folder.ZIP_CONTAINER),
            SystemProperties.get(SystemProperties.Net.Http.Folder.ZIP_TEMP_PREFIX));
    tempFolder.toFile().deleteOnExit();
    int errors;
    Set<String> processedNames = new TreeSet<>();
    do {
        errors = 0;
        Enumeration<? extends ZipEntry> entryEnumeration = zipFile.entries();
        while (entryEnumeration.hasMoreElements()) {
            ZipEntry zipEntry = entryEnumeration.nextElement();
            if(!processedNames.contains(zipEntry.getName())) {
                try {
                    if (zipEntry.isDirectory()) {
                        Files.createDirectory(tempFolder.resolve(zipEntry.getName()));
                    } else {
                        Path file = Files.createFile(tempFolder.resolve(zipEntry.getName()));
                        try (InputStream inputStream = zipFile.getInputStream(zipEntry);
                             FileOutputStream fileOutputStream = new FileOutputStream(file.toFile())) {
                            byte[] buffer = new byte[2048];
                            int readSize = inputStream.read(buffer);
                            while (readSize >= 0) {
                                fileOutputStream.write(buffer, 0, readSize);
                                fileOutputStream.flush();
                                readSize = inputStream.read(buffer);
                            }
                        }
                    }
                } catch (IOException ex) {
                    errors++;
                }
                processedNames.add(zipEntry.getName());
            }
        }
    } while(errors > 0);
    return tempFolder;
}
 
Example 17
FaultyFileSystem(Path root) throws IOException {
    if (root == null) {
        root = Files.createTempDirectory("faultyFS");
        removeRootAfterClose = true;
    } else {
        if (! Files.isDirectory(root)) {
            throw new IllegalArgumentException("must be a directory.");
        }
        removeRootAfterClose = false;
    }
    this.root = root;
    delegate = root.getFileSystem();
    isOpen = true;
}
 
Example 18
Source Project: eo   File: ProgramTest.java    License: MIT License 5 votes vote down vote up
/**
 * Program can parse a type with multiple methods.
 * @throws Exception If some problem inside
 */
@Test(expected = CompileException.class)
public void failsOnBrokenSyntax() throws Exception {
    final Program program = new Program(
        new InputOf("this code is definitely wrong"),
        Files.createTempDirectory("")
    );
    program.compile();
}
 
Example 19
protected Path tempDir(String name) throws IOException {
	Path dir = Files.createTempDirectory(name);
	tmps.add(dir);
	return dir;
}
 
Example 20
Source Project: indexr   File: DictMerge.java    License: Apache License 2.0 4 votes vote down vote up
public DictMerge() throws IOException {
    dir = Files.createTempDirectory("indexr_dictmerge");
}