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

The following examples show how to use java.nio.file.Files#createDirectory() . 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 File: HadoopS3RecoverableWriterITCase.java    From flink with Apache License 2.0 6 votes vote down vote up
private void cleanupLocalDir() throws Exception {
	final String defaultTmpDir = getFileSystem().getLocalTmpDir();
	final java.nio.file.Path defaultTmpPath = Paths.get(defaultTmpDir);

	if (Files.exists(defaultTmpPath)) {
		try (Stream<java.nio.file.Path> files = Files.list(defaultTmpPath)) {
			files.forEach(p -> {
				try {
					Files.delete(p);
				} catch (IOException e) {
					e.printStackTrace();
				}
			});
		}
	} else {
		Files.createDirectory(defaultTmpPath);
	}
}
 
Example 2
Source File: JimfsUnixLikeFileSystemTest.java    From jimfs with Apache License 2.0 6 votes vote down vote up
@Test
public void testIsSameFile() throws IOException {
  Files.createDirectory(path("/foo"));
  Files.createSymbolicLink(path("/bar"), path("/foo"));
  Files.createFile(path("/bar/test"));

  assertThatPath("/foo").isSameFileAs("/foo");
  assertThatPath("/bar").isSameFileAs("/bar");
  assertThatPath("/foo/test").isSameFileAs("/foo/test");
  assertThatPath("/bar/test").isSameFileAs("/bar/test");
  assertThatPath("/foo").isNotSameFileAs("test");
  assertThatPath("/bar").isNotSameFileAs("/test");
  assertThatPath("/foo").isSameFileAs("/bar");
  assertThatPath("/foo/test").isSameFileAs("/bar/test");

  Files.createSymbolicLink(path("/baz"), path("bar")); // relative path
  assertThatPath("/baz").isSameFileAs("/foo");
  assertThatPath("/baz/test").isSameFileAs("/foo/test");
}
 
Example 3
Source File: WCAReportImplTest.java    From ipst with Mozilla Public License 2.0 6 votes vote down vote up
@Test
public void testExportPostContigencyViolationsWithUncertaintiesLoadflowDivergence() throws IOException {
    Path folder = Files.createDirectory(fileSystem.getPath("/export-folder"));

    WCAReportImpl wcaReport = new WCAReportImpl(network, tableFormatterConfig);
    WCAPostContingencyStatus postContingencyStatus = new WCAPostContingencyStatus("fault1", new WCALoadflowResult(true, null));
    postContingencyStatus.setPostContingencyWithUncertaintiesLoadflowResult(new WCALoadflowResult(false, "post contingency with uncertainties loadflow diverged"));
    wcaReport.addPostContingencyStatus(postContingencyStatus);
    wcaReport.exportCsv(folder);

    Path report = folder.resolve(WCAReportImpl.POST_CONTINGENCY_VIOLATIONS_WITH_UNCERTAINTIES_FILE);
    assertTrue(Files.exists(report));
    String reportContent = String.join(System.lineSeparator(),
                                       WCAReportImpl.POST_CONTINGENCY_VIOLATIONS_WITH_UNCERTAINTIES_TITLE,
                                       "Basecase;Contingency;FailureStep;FailureDescription;ViolationType;Equipment;Value;Limit;Country;BaseVoltage;Side",
                                       networkId + ";fault1;Loadflow;post contingency with uncertainties loadflow diverged;;;;;;;");
    assertEquals(reportContent, CharStreams.toString(new InputStreamReader(Files.newInputStream(report))).trim());
}
 
Example 4
Source File: JimfsFileSystemCloseTest.java    From jimfs with Apache License 2.0 6 votes vote down vote up
@Test
public void testOpenDirectoryStreamsClosed() throws IOException {
  Path p = fs.getPath("/foo");
  Files.createDirectory(p);

  try (DirectoryStream<Path> stream = Files.newDirectoryStream(p)) {

    fs.close();

    try {
      stream.iterator();
      fail();
    } catch (ClosedDirectoryStreamException expected) {
    }
  }
}
 
Example 5
Source File: DiskCacheManager.java    From BIMserver with GNU Affero General Public License v3.0 6 votes vote down vote up
public DiskCacheManager(BimServer bimServer, Path cacheDir) {
	this.bimServer = bimServer;
	this.cacheDir = cacheDir;
	try {
		if (!Files.exists(cacheDir)) {
				Files.createDirectory(cacheDir);
		}
		for (Path file : PathUtils.list(this.cacheDir)) {
			if (file.getFileName().toString().endsWith(".__tmp")) {
				Files.delete(file);
			} else {
				cachedFileNames.add(file.getFileName().toString());
			}
		}
	} catch (IOException e) {
		LOGGER.error("", e);
	}
}
 
Example 6
Source File: FileUploadsTest.java    From flink with Apache License 2.0 6 votes vote down vote up
@Test
public void testCleanup() throws IOException {
	Path rootDir = Paths.get("root");
	Path rootFile = rootDir.resolve("rootFile");
	Path subDir = rootDir.resolve("sub");
	Path subFile = subDir.resolve("subFile");

	Path tmp = temporaryFolder.getRoot().toPath();
	Files.createDirectory(tmp.resolve(rootDir));
	Files.createDirectory(tmp.resolve(subDir));
	Files.createFile(tmp.resolve(rootFile));
	Files.createFile(tmp.resolve(subFile));

	try (FileUploads fileUploads = new FileUploads(tmp.resolve(rootDir))) {
		Assert.assertTrue(Files.exists(tmp.resolve(rootDir)));
		Assert.assertTrue(Files.exists(tmp.resolve(subDir)));
		Assert.assertTrue(Files.exists(tmp.resolve(rootFile)));
		Assert.assertTrue(Files.exists(tmp.resolve(subFile)));
	}
	Assert.assertFalse(Files.exists(tmp.resolve(rootDir)));
	Assert.assertFalse(Files.exists(tmp.resolve(subDir)));
	Assert.assertFalse(Files.exists(tmp.resolve(rootFile)));
	Assert.assertFalse(Files.exists(tmp.resolve(subFile)));
}
 
Example 7
Source File: AbsolutePathTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String... cmdline) throws Exception {
    ToolBox tb = new ToolBox();

    // compile test.Test
    new JavacTask(tb)
            .outdir(".") // this is needed to get the classfiles in test
            .sources("package test; public class Test{}")
            .run();

    // build test.jar containing test.Test
    // we need the jars in a directory different from the working
    // directory to trigger the bug.
    Files.createDirectory(Paths.get("jars"));
    new JarTask(tb, "jars/test.jar")
            .files("test/Test.class")
            .run();

    // build second jar in jars directory using
    // an absolute path reference to the first jar
    new JarTask(tb, "jars/test2.jar")
            .classpath(new File("jars/test.jar").getAbsolutePath())
            .run();

    // this should not fail
    new JavacTask(tb)
            .outdir(".")
            .classpath("jars/test2.jar")
            .sources("import test.Test; class Test2 {}")
            .run()
            .writeAll();
}
 
Example 8
Source File: SetDefaultProvider.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Test override of default FileSystemProvider where the main application
 * is a module that is patched by an exploded patch.
 */
public void testExplodedModuleWithJarPatch() throws Exception {
    Path patchdir = Files.createTempDirectory("patch");
    Files.createDirectory(patchdir.resolve("m.properties"));
    Path patch = createJarFile(patchdir);
    String modulePath = System.getProperty("jdk.module.path");
    int exitValue = exec(SET_DEFAULT_FSP,
                         "--patch-module", "m=" + patch,
                         "-p", modulePath,
                         "-m", "m/p.Main");
    assertTrue(exitValue == 0);
}
 
Example 9
Source File: JmodNegativeTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@DataProvider(name = "partOfPathDoesNotExist")
public Object[][] partOfPathDoesNotExist() throws IOException {
    Path jmod = MODS_DIR.resolve("output.jmod");
    FileUtils.deleteFileIfExistsWithRetry(jmod);
    FileUtils.deleteFileIfExistsWithRetry(Paths.get("doesNotExist"));

    Path emptyDir = Paths.get("empty");
    if (Files.exists(emptyDir))
        FileUtils.deleteFileTreeWithRetry(emptyDir);
    Files.createDirectory(emptyDir);

    List<Supplier<JmodResult>> tasks = Arrays.asList(
        () -> jmod("create",
                   "--hash-modules", "anyPattern",
                   "--module-path","empty" + pathSeparator + "doesNotExist",
                   "output.jmod"),
        () -> jmod("create",
                   "--class-path", "empty" + pathSeparator + "doesNotExist",
                   "output.jmod"),
        () -> jmod("create",
                   "--class-path", "empty" + pathSeparator + "doesNotExist.jar",
                   "output.jmod"),
        () -> jmod("create",
                   "--cmds", "empty" + pathSeparator + "doesNotExist",
                   "output.jmod"),
        () -> jmod("create",
                   "--config", "empty" + pathSeparator + "doesNotExist",
                   "output.jmod"),
        () -> jmod("create",
                   "--libs", "empty" + pathSeparator + "doesNotExist",
                   "output.jmod") );

    String errMsg = "Error: path not found: doesNotExist";
    return tasks.stream().map(t -> new Object[] {t, errMsg} )
                         .toArray(Object[][]::new);
}
 
Example 10
Source File: Basic.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
static void viaProviderWithTemplate(String protocol,
                                    Consumer<Result> resultChecker,
                                    Path template, String... sysProps)
    throws Exception
{
    System.out.println("\nTesting " + protocol);
    Path testRoot = Paths.get("URLStreamHandlerProvider-" + protocol);
    if (Files.exists(testRoot))
        FileUtils.deleteFileTreeWithRetry(testRoot);
    Files.createDirectory(testRoot);

    Path srcPath = Files.createDirectory(testRoot.resolve("src"));
    Path srcClass = createProvider(protocol, template, srcPath);

    Path build = Files.createDirectory(testRoot.resolve("build"));
    javac(build, srcClass);
    createServices(build, protocol);
    Path testJar = testRoot.resolve("test.jar");
    jar(testJar, build);

    List<String> props = new ArrayList<>();
    for (String p : sysProps)
        props.add(p);

    Result r = java(props, asList(testJar, TEST_CLASSES),
                    "Child", protocol);

    resultChecker.accept(r);
}
 
Example 11
Source File: NameLimits.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
static boolean tryCreateDirectory(int len) throws IOException {
    Path name = generatePath(len);
    try {
        Files.createDirectory(name);
    } catch (IOException ioe) {
        System.err.format("Unable to create directory of length %d (full path %d), %s%n",
            name.toString().length(), name.toAbsolutePath().toString().length(), ioe);
        return false;
    }
    Files.delete(name);
    return true;
}
 
Example 12
Source File: NameLimits.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
static boolean tryCreateDirectory(int len) throws IOException {
    Path name = generatePath(len);
    try {
        Files.createDirectory(name);
    } catch (IOException ioe) {
        System.err.format("Unable to create directory of length %d (full path %d), %s%n",
            name.toString().length(), name.toAbsolutePath().toString().length(), ioe);
        return false;
    }
    Files.delete(name);
    return true;
}
 
Example 13
Source File: NameLimits.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
static boolean tryCreateDirectory(int len) throws IOException {
    Path name = generatePath(len);
    try {
        Files.createDirectory(name);
    } catch (IOException ioe) {
        System.err.format("Unable to create directory of length %d (full path %d), %s%n",
            name.toString().length(), name.toAbsolutePath().toString().length(), ioe);
        return false;
    }
    Files.delete(name);
    return true;
}
 
Example 14
Source File: FileStorage.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void createDirectory(String dir) {
    try {
        Files.createDirectory(Paths.get(dir));
    } catch (IOException ex) {
        // probably already exists
    }
}
 
Example 15
Source File: KDC.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void prepare() {
    try {
        Files.createDirectory(Paths.get(base));
        Files.write(Paths.get(base + "/kdc.conf"), Arrays.asList(
                "[kdcdefaults]",
                "\n[realms]",
                realm + "= {",
                "  kdc_listen = " + this.port,
                "  kdc_tcp_listen = " + this.port,
                "  database_name = " + base + "/principal",
                "  key_stash_file = " + base + "/.k5.ATHENA.MIT.EDU",
                SUPPORTED_ETYPES == null ? ""
                        : ("  supported_enctypes = "
                        + (SUPPORTED_ETYPES + ",")
                                .replaceAll(",", ":normal ")),
                "}"
        ));
        Files.write(Paths.get(base + "/krb5.conf"), Arrays.asList(
                "[libdefaults]",
                "default_realm = " + realm,
                "default_keytab_name = FILE:" + base + "/krb5.keytab",
                "forwardable = true",
                "dns_lookup_kdc = no",
                "dns_lookup_realm = no",
                "dns_canonicalize_hostname = false",
                "\n[realms]",
                realm + " = {",
                "  kdc = localhost:" + port,
                "}",
                "\n[logging]",
                "kdc = FILE:" + base + "/krb5kdc.log"
        ));
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 16
Source File: ArduinoLibraryInstallerTest.java    From tcMenu with Apache License 2.0 5 votes vote down vote up
private void putLibraryInPlace(Path location, String name, String version) throws IOException {
    if(!Files.exists(dirArduinoLibs)) Files.createDirectory(dirArduinoLibs);

    Path tcMenuDir = Files.createDirectory(location.resolve(name));
    Path libProps = tcMenuDir.resolve("library.properties");
    String contents = "version=" + version + "\r\n";
    Files.write(libProps, contents.getBytes());
    Path src = tcMenuDir.resolve("src");
    Files.createDirectory(src);
    Files.write(src.resolve("afile.txt"), "This is some text to copy".getBytes());
}
 
Example 17
Source File: FilePermissionsTest.java    From appengine-plugins-core with Apache License 2.0 5 votes vote down vote up
@Test
public void testDirectoryCannotBeCreatedDueToUnwritableParent() throws IOException {
  Path dir = Files.createDirectory(Paths.get(parent.toString(), "child"));
  Assume.assumeTrue(dir.toFile().setWritable(false)); // On windows this isn't true
  dir.toFile().setWritable(false);
  try {
    FilePermissions.verifyDirectoryCreatable(Paths.get(dir.toString(), "bar"));
    Assert.fail("Can create directory in non-writable parent");
  } catch (AccessDeniedException ex) {
    Assert.assertNotNull(ex.getMessage());
    Assert.assertTrue(ex.getMessage().contains(dir.getFileName().toString()));
  }
}
 
Example 18
Source File: SslContextProviderServiceTest.java    From crate with Apache License 2.0 4 votes vote down vote up
@Test
public void test_service_reloads_configuration_on_change_of_symlinked_files() throws Exception {
    /*
     * Emulate kubernetes like folder structure (CertManager/mounted secrets)
     * See https://github.com/crate/crate/issues/10022 for context
     *
     * root@test-7b9c78557b-2xh5w:/# ls -las /usr/local/share/credentials/
     * total 0
     * 0 drwxrwxrwt 3 root root  160 May 29 07:54 .
     * 0 drwxrwsr-x 1 root staff  85 May 29 07:07 ..
     * 0 drwxr-xr-x 2 root root  120 May 29 07:54 ..2020_05_29_07_54_27.931224672
     * 0 lrwxrwxrwx 1 root root   31 May 29 07:54 ..data -> ..2020_05_29_07_54_27.931224672
     * 0 lrwxrwxrwx 1 root root   19 May 29 07:53 keystore.jks -> ..data/keystore.jks
     */

    Path tempDir = createTempDir();
    Path dataTarget05 = Files.createDirectory(tempDir.resolve("2020_05"));
    Path dataTarget06 = Files.createDirectory(tempDir.resolve("2020_06"));
    Path dataLink = tempDir.resolve("data");

    Files.createSymbolicLink(dataLink, dataTarget05);
    Files.write(dataLink.resolve("keystore.jks"), List.of("version1"));

    Path keystoreLink = tempDir.resolve("keystore.jks");
    Path keystoreTarget = tempDir.resolve("data/keystore.jks");
    Files.createSymbolicLink(keystoreLink, keystoreTarget);

    Settings settings = Settings.builder()
        .put(SslConfigSettings.SSL_KEYSTORE_FILEPATH.getKey(), keystoreLink.toString())
        .put(SslConfigSettings.SSL_RESOURCE_POLL_INTERVAL_NAME, "1")
        .build();

    final AtomicBoolean reloadCalled = new AtomicBoolean(false);
    SslContextProviderService sslContextProviderService = new SslContextProviderService(
        settings,
        THREAD_POOL,
        new SslContextProvider() {

                @Override
                public SslContext getSslContext() {
                    return null;
                }

                @Override
                public void reloadSslContext() {
                    reloadCalled.set(true);
                }
            }
    );
    sslContextProviderService.start();

    Files.write(dataTarget06.resolve("keystore.jks"), List.of("version2"));
    Files.deleteIfExists(dataLink);
    Files.createSymbolicLink(dataLink, dataTarget06);
    Files.deleteIfExists(dataTarget05.resolve("keystore.jks"));

    assertBusy(() -> {
        assertThat(reloadCalled.get(), is(true));
    });
}
 
Example 19
Source File: GitFileAttributeViewTest.java    From ParallelGit with Apache License 2.0 4 votes vote down vote up
@Test
public void whenDirectoryIsEmpty_getObjectIdShouldReturnZeroId() throws IOException {
  initGitFileSystem();
  Files.createDirectory(gfs.getPath("/dir"));
  assertEquals(zeroId(), objectId("/dir"));
}
 
Example 20
Source File: ContentHandlersTest.java    From openjdk-jdk9 with GNU General Public License v2.0 3 votes vote down vote up
private static void step2_ServiceLoader() throws IOException {
    String factoryClassFqn = "net.java.openjdk.test.TestContentHandlerFactory";

    Path tmp = Files.createDirectory(Paths.get("ContentHandlersTest-2"));

    Path src = templatesHome().resolve("test.template");
    Path dst = tmp.resolve("Test.java");
    Files.copy(src, dst);

    Path dst1 = fromTemplate(templatesHome().resolve("broken_constructor_factory.template"),
            factoryClassFqn, tmp);

    Path build = Files.createDirectory(tmp.resolve("build"));

    javac(build, dst);

    Path explodedJar = Files.createDirectory(tmp.resolve("exploded-jar"));
    Path services = Files.createDirectories(explodedJar.resolve("META-INF")
            .resolve("services"));

    Path s = services.resolve("java.net.ContentHandlerFactory");

    try (FileWriter fw = new FileWriter(s.toFile())) {
        fw.write(factoryClassFqn);
    }

    javac(explodedJar, dst1);
    jar(tmp.resolve("test.jar"), explodedJar);

    Files.copy(tmp.resolve("test.jar"), build.resolve("test.jar"));

    Result r = java(emptyMap(), asList(build.resolve("test.jar"), build), "Test");

    if (r.exitValue == 0 || !verifyOutput(r.output, factoryClassFqn))
        throw new RuntimeException(r.output);
}