java.nio.file.Path

Here are the examples of the java api class java.nio.file.Path taken from open source projects.

1. NodeEnvironmentEvilTests#testMissingWritePermissionOnShard()

View license
public void testMissingWritePermissionOnShard() throws IOException {
    assumeTrue("posix filesystem", isPosix);
    final String[] tempPaths = tmpPaths();
    Path path = PathUtils.get(randomFrom(tempPaths));
    Path fooIndex = path.resolve("nodes").resolve("0").resolve(NodeEnvironment.INDICES_FOLDER).resolve("foo");
    Path fooShard = fooIndex.resolve("0");
    Path fooShardIndex = fooShard.resolve("index");
    Path fooShardTranslog = fooShard.resolve("translog");
    Path fooShardState = fooShard.resolve("_state");
    Path pick = randomFrom(fooShard, fooShardIndex, fooShardTranslog, fooShardState);
    Files.createDirectories(pick);
    try (PosixPermissionsResetter attr = new PosixPermissionsResetter(pick)) {
        attr.setPermissions(new HashSet<>(Arrays.asList(PosixFilePermission.OTHERS_READ, PosixFilePermission.GROUP_READ, PosixFilePermission.OWNER_READ)));
        Settings build = Settings.builder().put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toAbsolutePath().toString()).putArray(Environment.PATH_DATA_SETTING.getKey(), tempPaths).build();
        IOException ioException = expectThrows(IOException.class, () -> {
            new NodeEnvironment(build, new Environment(build));
        });
        assertTrue(ioException.getMessage(), ioException.getMessage().startsWith("failed to write in data directory"));
    }
}

2. FileHandlerSymlinksTestCase#deleteSymlinksScenario()

View license
@After
public void deleteSymlinksScenario() throws IOException, URISyntaxException {
    Path rootPath = Paths.get(getClass().getResource("page.html").toURI()).getParent();
    Path newSymlink = rootPath.resolve("newSymlink");
    Path newDir = rootPath.resolve("newDir");
    Path page = newDir.resolve("page.html");
    Path innerDir = newDir.resolve("innerDir");
    Path innerSymlink = newDir.resolve("innerSymlink");
    Path innerPage = innerDir.resolve("page.html");
    Files.deleteIfExists(innerSymlink);
    Files.deleteIfExists(newSymlink);
    Files.deleteIfExists(innerPage);
    Files.deleteIfExists(page);
    Files.deleteIfExists(innerDir);
    Files.deleteIfExists(newDir);
}

3. AppleBundle#appendDsymRenameStepToMatchBundleName()

Project: buck
Source File: AppleBundle.java
View license
private void appendDsymRenameStepToMatchBundleName(ImmutableList.Builder<Step> stepsBuilder, BuildableContext buildableContext) {
    Preconditions.checkArgument(hasBinary && appleDsym.isPresent());
    // rename dSYM bundle to match bundle name
    Path dsymPath = appleDsym.get().getPathToOutput();
    Path dsymSourcePath = bundleRoot.getParent().resolve(dsymPath.getFileName());
    Path dsymDestinationPath = bundleRoot.getParent().resolve(bundleRoot.getFileName() + "." + AppleBundleExtension.DSYM.toFileExtension());
    stepsBuilder.add(new RmStep(getProjectFilesystem(), dsymDestinationPath, true, true));
    stepsBuilder.add(new MoveStep(getProjectFilesystem(), dsymSourcePath, dsymDestinationPath));
    String dwarfFilename = AppleDsym.getDwarfFilenameForDsymTarget(appleDsym.get().getBuildTarget());
    // rename DWARF file inside dSYM bundle to match bundle name
    Path dwarfFolder = dsymDestinationPath.resolve(AppleDsym.DSYM_DWARF_FILE_FOLDER);
    Path dwarfSourcePath = dwarfFolder.resolve(dwarfFilename);
    Path dwarfDestinationPath = dwarfFolder.resolve(MorePaths.getNameWithoutExtension(bundleRoot));
    stepsBuilder.add(new MoveStep(getProjectFilesystem(), dwarfSourcePath, dwarfDestinationPath));
    // record dSYM so we can fetch it from cache
    buildableContext.recordArtifact(dsymDestinationPath);
}

4. FileHandlerSymlinksTestCase#testCreateSymlinks()

View license
@Test
public void testCreateSymlinks() throws IOException, URISyntaxException {
    Path rootPath = Paths.get(getClass().getResource("page.html").toURI()).getParent();
    Path newDir = rootPath.resolve("newDir");
    Assert.assertFalse(Files.isSymbolicLink(newDir));
    Path innerDir = newDir.resolve("innerDir");
    Assert.assertFalse(Files.isSymbolicLink(innerDir));
    Path newSymlink = rootPath.resolve("newSymlink");
    Assert.assertTrue(Files.isSymbolicLink(newSymlink));
    Path innerSymlink = newSymlink.resolve("innerSymlink");
    Assert.assertTrue(Files.isSymbolicLink(innerSymlink));
    Path f = innerSymlink.getRoot();
    for (int i = 0; i < innerSymlink.getNameCount(); i++) {
        f = f.resolve(innerSymlink.getName(i).toString());
        System.out.println(f + " " + Files.isSymbolicLink(f));
    }
    f = f.resolve(".");
    System.out.println(f + " " + Files.isSymbolicLink(f));
}

5. ExecutableFinderTest#testSearchPathsSymlinkToExecutableOutsideSearchPathReturnsPath()

Project: buck
Source File: ExecutableFinderTest.java
View license
@Test
public void testSearchPathsSymlinkToExecutableOutsideSearchPathReturnsPath() throws IOException {
    Path dir1 = tmp.newFolder("foo");
    Path dir2 = tmp.newFolder("bar");
    Path dir3 = tmp.newFolder("baz");
    tmp.newFolder("unsearched");
    Path binary = createExecutable("unsearched/binary");
    Path file1 = dir2.resolve("blech");
    Files.createSymbolicLink(file1, binary);
    assertEquals(Optional.of(file1), new ExecutableFinder().getOptionalExecutable(Paths.get("blech"), ImmutableList.of(dir1, dir2, dir3), ImmutableList.<String>of()));
}

6. MoreFilesTest#testSortFilesByAccessTime()

Project: buck
Source File: MoreFilesTest.java
View license
@Test
public void testSortFilesByAccessTime() throws IOException {
    Path dir = tmp.newFolder();
    Path fileW = dir.resolve("w");
    Path fileX = dir.resolve("x");
    Path fileY = dir.resolve("y");
    Path fileZ = dir.resolve("z");
    Files.write(fileW, "w".getBytes(UTF_8));
    Files.write(fileX, "x".getBytes(UTF_8));
    Files.write(fileY, "y".getBytes(UTF_8));
    Files.write(fileZ, "z".getBytes(UTF_8));
    Files.setAttribute(fileW, "lastAccessTime", FileTime.fromMillis(9000));
    Files.setAttribute(fileX, "lastAccessTime", FileTime.fromMillis(0));
    Files.setAttribute(fileY, "lastAccessTime", FileTime.fromMillis(1000));
    Files.setAttribute(fileZ, "lastAccessTime", FileTime.fromMillis(2000));
    File[] files = dir.toFile().listFiles();
    MoreFiles.sortFilesByAccessTime(files);
    assertEquals("Files short be sorted from most recently accessed to least recently accessed.", ImmutableList.of(fileW.toFile(), fileZ.toFile(), fileY.toFile(), fileX.toFile()), Arrays.asList(files));
}

7. FilesystemBackedBuildFileTreeTest#respectsIgnorePaths()

View license
@Test
public void respectsIgnorePaths() throws IOException {
    Path tempDir = tmp.getRoot();
    Path fooBuck = tempDir.resolve("foo/BUCK");
    Path fooBarBuck = tempDir.resolve("foo/bar/BUCK");
    Path fooBazBuck = tempDir.resolve("foo/baz/BUCK");
    Files.createDirectories(fooBarBuck.getParent());
    Files.createDirectories(fooBazBuck.getParent());
    touch(fooBuck);
    touch(fooBarBuck);
    touch(fooBazBuck);
    Config config = ConfigBuilder.createFromText("[project]", "ignore = foo/bar");
    ProjectFilesystem filesystem = new ProjectFilesystem(tempDir, config);
    BuildFileTree buildFiles = new FilesystemBackedBuildFileTree(filesystem, "BUCK");
    Collection<Path> children = buildFiles.getChildPaths(BuildTarget.builder(tempDir, "//foo", "foo").build());
    assertEquals(ImmutableSet.of(Paths.get("baz")), children);
    Path ancestor = buildFiles.getBasePathOfAncestorTarget(Paths.get("foo/bar/xyzzy")).get();
    assertEquals(Paths.get("foo"), ancestor);
}

8. ProjectWorkspaceTest#testCopyRecursively()

Project: buck
Source File: ProjectWorkspaceTest.java
View license
@Test
public void testCopyRecursively() throws IOException {
    Path templateDir = java.nio.file.Files.createTempDirectory("template");
    Path sourceDir = java.nio.file.Files.createTempDirectory("source");
    Path testSubdir = sourceDir.resolve("subdir");
    java.nio.file.Files.createDirectory(testSubdir);
    Path testFile = testSubdir.resolve("test.file");
    java.nio.file.Files.write(testFile, ImmutableList.of("Hello world"), Charsets.UTF_8);
    Path testFile2 = testSubdir.resolve("test.file2");
    java.nio.file.Files.write(testFile2, ImmutableList.of("Goodbye world"), Charsets.UTF_8);
    ProjectWorkspace workspace = new ProjectWorkspace(templateDir, tmpFolder.getRoot());
    workspace.copyRecursively(sourceDir, Paths.get("destdir"));
    assertEquals("Hello world" + System.lineSeparator(), workspace.getFileContents("destdir/subdir/test.file"));
    assertEquals("Goodbye world" + System.lineSeparator(), workspace.getFileContents("destdir/subdir/test.file2"));
}

9. HgCmdLineInterfaceIntegrationTest#explodeReposZip()

View license
private static Path explodeReposZip() throws IOException {
    Path testDataDir = TestDataHelper.getTestDataDirectory(HgCmdLineInterfaceIntegrationTest.class);
    Path hgRepoZipPath = testDataDir.resolve(HG_REPOS_ZIP);
    Path tempFolderPath = tempFolder.getRoot().toPath();
    Path hgRepoZipCopyPath = tempFolderPath.resolve(HG_REPOS_ZIP);
    Files.copy(hgRepoZipPath, hgRepoZipCopyPath, REPLACE_EXISTING);
    Path reposPath = tempFolderPath.resolve(REPOS_DIR);
    Unzip.extractZipFile(hgRepoZipCopyPath, reposPath, Unzip.ExistingFileMode.OVERWRITE_AND_CLEAN_DIRECTORIES);
    return reposPath;
}

10. JimfsUnixLikeFileSystemTest#testDelete_pathPermutations()

View license
@Test
public void testDelete_pathPermutations() throws IOException {
    Path bar = path("/work/foo/bar");
    Files.createDirectories(bar);
    for (Path path : permutations(bar)) {
        Files.createDirectories(bar);
        assertThatPath(path).isSameFileAs(bar);
        Files.delete(path);
        assertThatPath(bar).doesNotExist();
        assertThatPath(path).doesNotExist();
    }
    Path baz = path("/test/baz");
    Files.createDirectories(baz);
    Path hello = baz.resolve("hello.txt");
    for (Path path : permutations(hello)) {
        Files.createFile(hello);
        assertThatPath(path).isSameFileAs(hello);
        Files.delete(path);
        assertThatPath(hello).doesNotExist();
        assertThatPath(path).doesNotExist();
    }
}

11. ModuleFinderTest#testOfManyJarFiles()

Project: openjdk
Source File: ModuleFinderTest.java
View license
/**
     * Test ModuleFinder.of with many JAR files
     */
public void testOfManyJarFiles() throws Exception {
    Path dir = Files.createTempDirectory(USER_DIR, "mods");
    Path jar1 = createModularJar(dir.resolve("[email protected]"), "[email protected]");
    Path jar2 = createModularJar(dir.resolve("[email protected]"), "m2");
    // shadowed
    Path jar3 = createModularJar(dir.resolve("[email protected]"), "[email protected]");
    Path jar4 = createModularJar(dir.resolve("[email protected]"), "m3");
    ModuleFinder finder = ModuleFinder.of(jar1, jar2, jar3, jar4);
    assertTrue(finder.findAll().size() == 3);
    assertTrue(finder.find("m1").isPresent());
    assertTrue(finder.find("m2").isPresent());
    assertTrue(finder.find("m3").isPresent());
    assertFalse(finder.find("java.rhubarb").isPresent());
    // check that [email protected] (and not [email protected]) is found
    ModuleDescriptor m1 = finder.find("m1").get().descriptor();
    assertEquals(m1.version().get().toString(), "1.0");
}

12. AccessSystemLogger#main()

Project: openjdk
Source File: AccessSystemLogger.java
View license
// copy AccessSystemLogger.class to ./boot
public static void main(String[] args) throws IOException {
    Path testDir = Paths.get(System.getProperty("user.dir", "."));
    Path bootDir = Paths.get(testDir.toString(), "boot");
    Path classes = Paths.get(System.getProperty("test.classes", "build/classes"));
    Path thisClass = Paths.get(classes.toString(), AccessSystemLogger.class.getSimpleName() + ".class");
    if (Files.notExists(bootDir)) {
        Files.createDirectory(bootDir);
    }
    Path dest = Paths.get(bootDir.toString(), AccessSystemLogger.class.getSimpleName() + ".class");
    Files.copy(thisClass, dest, StandardCopyOption.REPLACE_EXISTING);
}

13. AccessSystemLogger#main()

Project: openjdk
Source File: AccessSystemLogger.java
View license
// copy AccessSystemLogger.class to ./boot
public static void main(String[] args) throws IOException {
    Path testDir = Paths.get(System.getProperty("user.dir", "."));
    Path bootDir = Paths.get(testDir.toString(), "boot");
    Path classes = Paths.get(System.getProperty("test.classes", "build/classes"));
    Path thisClass = Paths.get(classes.toString(), AccessSystemLogger.class.getSimpleName() + ".class");
    if (Files.notExists(bootDir)) {
        Files.createDirectory(bootDir);
    }
    Path dest = Paths.get(bootDir.toString(), AccessSystemLogger.class.getSimpleName() + ".class");
    Files.copy(thisClass, dest, StandardCopyOption.REPLACE_EXISTING);
}

14. AccessSystemLogger#main()

Project: openjdk
Source File: AccessSystemLogger.java
View license
// copy AccessSystemLogger.class to ./boot
public static void main(String[] args) throws IOException {
    Path testDir = Paths.get(System.getProperty("user.dir", "."));
    Path bootDir = Paths.get(testDir.toString(), "boot");
    Path classes = Paths.get(System.getProperty("test.classes", "build/classes"));
    Path thisClass = Paths.get(classes.toString(), AccessSystemLogger.class.getSimpleName() + ".class");
    if (Files.notExists(bootDir)) {
        Files.createDirectory(bootDir);
    }
    Path dest = Paths.get(bootDir.toString(), AccessSystemLogger.class.getSimpleName() + ".class");
    Files.copy(thisClass, dest, StandardCopyOption.REPLACE_EXISTING);
}

15. AccessSystemLogger#main()

Project: openjdk
Source File: AccessSystemLogger.java
View license
// copy AccessSystemLogger.class to ./boot
public static void main(String[] args) throws IOException {
    Path testDir = Paths.get(System.getProperty("user.dir", "."));
    Path bootDir = Paths.get(testDir.toString(), "boot");
    Path classes = Paths.get(System.getProperty("test.classes", "build/classes"));
    Path thisClass = Paths.get(classes.toString(), AccessSystemLogger.class.getSimpleName() + ".class");
    if (Files.notExists(bootDir)) {
        Files.createDirectory(bootDir);
    }
    Path dest = Paths.get(bootDir.toString(), AccessSystemLogger.class.getSimpleName() + ".class");
    Files.copy(thisClass, dest, StandardCopyOption.REPLACE_EXISTING);
}

16. ContentHandlersTest#step1_ContentHandlerFactory()

Project: openjdk
Source File: ContentHandlersTest.java
View license
private static void step1_ContentHandlerFactory() throws IOException {
    String factoryClassFqn = "net.java.openjdk.test.TestContentHandlerFactory";
    Path tmp = Files.createDirectory(Paths.get("ContentHandlersTest-1"));
    Path src = templatesHome().resolve("test.template");
    Path dst = tmp.resolve("Test.java");
    Files.copy(src, dst);
    Path build = Files.createDirectory(tmp.resolve("build"));
    Path dst1 = fromTemplate(templatesHome().resolve("broken_factory.template"), factoryClassFqn, tmp);
    javac(build, dst, dst1);
    Result r = java(emptyMap(), singleton(build), "Test", factoryClassFqn);
    if (r.exitValue == 0 || !r.output.startsWith(stackTraceStringForBrokenFactory(factoryClassFqn))) {
        throw new RuntimeException("Expected a different kind of failure: " + r.output);
    }
}

17. JLinkNegativeTest#testDuplicateModule2()

Project: openjdk
Source File: JLinkNegativeTest.java
View license
public void testDuplicateModule2() throws IOException {
    String moduleName = "dupRes2Jmod";
    List<String> classNames = Arrays.asList("java.A", "javax.B");
    Path module1 = helper.generateModuleCompiledClasses(helper.getJmodSrcDir(), helper.getJmodClassesDir(), moduleName, classNames);
    Path module2 = helper.generateModuleCompiledClasses(helper.getJarSrcDir(), helper.getJarClassesDir(), moduleName, classNames);
    Path jmod = JImageGenerator.getJModTask().addClassPath(module1).jmod(helper.createNewJmodFile(moduleName)).create().assertSuccess();
    Path jar = JImageGenerator.createJarFile(helper.getJarDir().resolve(moduleName + ".jar"), module2);
    Path newJar = helper.getJmodDir().resolve(jar.getFileName());
    Files.move(jar, newJar);
    try {
        helper.generateDefaultImage(moduleName).assertFailure("Error: Two versions of module dupRes2Jmod found in");
    } finally {
        deleteDirectory(jmod);
        deleteDirectory(newJar);
    }
}

18. ModuleInfoTest#testRequiresLoop()

Project: openjdk
Source File: ModuleInfoTest.java
View license
/**
     * Verify that a multi-module loop is detected.
     */
@Test
public void testRequiresLoop(Path base) throws Exception {
    Path src = base.resolve("src");
    Path src_m1 = src.resolve("m1");
    tb.writeFile(src_m1.resolve("module-info.java"), "module m1 { requires m2; }");
    Path src_m2 = src.resolve("m2");
    tb.writeFile(src_m2.resolve("module-info.java"), "module m2 { requires m3; }");
    Path src_m3 = src.resolve("m3");
    tb.writeFile(src_m3.resolve("module-info.java"), "module m3 { requires m1; }");
    Path classes = base.resolve("classes");
    Files.createDirectories(classes);
    String log = new JavacTask(tb).options("-XDrawDiagnostics", "-modulesourcepath", src.toString()).outdir(classes).files(findJavaFiles(src)).run(Task.Expect.FAIL).writeAll().getOutput(Task.OutputKind.DIRECT);
    if (!log.contains("module-info.java:1:22: compiler.err.cyclic.requires: m3"))
        throw new Exception("expected output not found");
}

19. ModuleInfoTest#testRequiresPublicLoop()

Project: openjdk
Source File: ModuleInfoTest.java
View license
/**
     * Verify that a multi-module loop is detected.
     */
@Test
public void testRequiresPublicLoop(Path base) throws Exception {
    Path src = base.resolve("src");
    Path src_m1 = src.resolve("m1");
    tb.writeFile(src_m1.resolve("module-info.java"), "module m1 { requires m2; }");
    Path src_m2 = src.resolve("m2");
    tb.writeFile(src_m2.resolve("module-info.java"), "module m2 { requires public m3; }");
    Path src_m3 = src.resolve("m3");
    tb.writeFile(src_m3.resolve("module-info.java"), "module m3 { requires m1; }");
    Path classes = base.resolve("classes");
    Files.createDirectories(classes);
    String log = new JavacTask(tb).options("-XDrawDiagnostics", "-modulesourcepath", src.toString()).outdir(classes).files(findJavaFiles(src)).run(Task.Expect.FAIL).writeAll().getOutput(Task.OutputKind.DIRECT);
    if (!log.contains("module-info.java:1:29: compiler.err.cyclic.requires: m3"))
        throw new Exception("expected output not found");
}

20. XModuleTest#testWithUpgradeModulePath()

Project: openjdk
Source File: XModuleTest.java
View license
@Test
public void testWithUpgradeModulePath(Path base) throws Exception {
    Path modSrc = base.resolve("modSrc");
    Path modules = base.resolve("modules");
    new ModuleBuilder(tb, "m1").classes("package pkg1; public interface E { }").build(modSrc, modules);
    Path upgrSrc = base.resolve("upgradeSrc");
    Path upgrade = base.resolve("upgrade");
    new ModuleBuilder(tb, "m1").classes("package pkg1; public interface D { }").build(upgrSrc, upgrade);
    Path src = base.resolve("src");
    tb.writeJavaFiles(src, "package p; interface A extends pkg1.D { }");
    new JavacTask(tb, Task.Mode.CMDLINE).options("-modulepath", modules.toString(), "-upgrademodulepath", upgrade.toString(), "-Xmodule:m1").files(findJavaFiles(src)).run().writeAll();
}

21. FileUtilsTest#deleteQuietly_deletes_directory_and_content()

Project: sonarqube
Source File: FileUtilsTest.java
View license
@Test
public void deleteQuietly_deletes_directory_and_content() throws IOException {
    Path target = temporaryFolder.newFolder().toPath();
    Path childFile1 = Files.createFile(target.resolve("file1.txt"));
    Path childDir1 = Files.createDirectory(target.resolve("subDir1"));
    Path childFile2 = Files.createFile(childDir1.resolve("file2.txt"));
    Path childDir2 = Files.createDirectory(childDir1.resolve("subDir2"));
    assertThat(target).isDirectory();
    assertThat(childFile1).isRegularFile();
    assertThat(childDir1).isDirectory();
    assertThat(childFile2).isRegularFile();
    assertThat(childDir2).isDirectory();
    FileUtils.deleteQuietly(target.toFile());
    assertThat(target).doesNotExist();
    assertThat(childFile1).doesNotExist();
    assertThat(childDir1).doesNotExist();
    assertThat(childFile2).doesNotExist();
    assertThat(childDir2).doesNotExist();
}

22. FileUtilsTest#deleteDirectory_deletes_directory_and_content()

Project: sonarqube
Source File: FileUtilsTest.java
View license
@Test
public void deleteDirectory_deletes_directory_and_content() throws IOException {
    Path target = temporaryFolder.newFolder().toPath();
    Path childFile1 = Files.createFile(target.resolve("file1.txt"));
    Path childDir1 = Files.createDirectory(target.resolve("subDir1"));
    Path childFile2 = Files.createFile(childDir1.resolve("file2.txt"));
    Path childDir2 = Files.createDirectory(childDir1.resolve("subDir2"));
    assertThat(target).isDirectory();
    assertThat(childFile1).isRegularFile();
    assertThat(childDir1).isDirectory();
    assertThat(childFile2).isRegularFile();
    assertThat(childDir2).isDirectory();
    FileUtils.deleteQuietly(target.toFile());
    assertThat(target).doesNotExist();
    assertThat(childFile1).doesNotExist();
    assertThat(childDir1).doesNotExist();
    assertThat(childFile2).doesNotExist();
    assertThat(childDir2).doesNotExist();
}

23. FileUtilsTest#deleteQuietly_deletes_directory_and_content()

Project: sonarqube
Source File: FileUtilsTest.java
View license
@Test
public void deleteQuietly_deletes_directory_and_content() throws IOException {
    Path target = temporaryFolder.newFolder().toPath();
    Path childFile1 = Files.createFile(target.resolve("file1.txt"));
    Path childDir1 = Files.createDirectory(target.resolve("subDir1"));
    Path childFile2 = Files.createFile(childDir1.resolve("file2.txt"));
    Path childDir2 = Files.createDirectory(childDir1.resolve("subDir2"));
    assertThat(target).isDirectory();
    assertThat(childFile1).isRegularFile();
    assertThat(childDir1).isDirectory();
    assertThat(childFile2).isRegularFile();
    assertThat(childDir2).isDirectory();
    FileUtils.deleteQuietly(target.toFile());
    assertThat(target).doesNotExist();
    assertThat(childFile1).doesNotExist();
    assertThat(childDir1).doesNotExist();
    assertThat(childFile2).doesNotExist();
    assertThat(childDir2).doesNotExist();
}

24. FileUtilsTest#deleteDirectory_deletes_directory_and_content()

Project: sonarqube
Source File: FileUtilsTest.java
View license
@Test
public void deleteDirectory_deletes_directory_and_content() throws IOException {
    Path target = temporaryFolder.newFolder().toPath();
    Path childFile1 = Files.createFile(target.resolve("file1.txt"));
    Path childDir1 = Files.createDirectory(target.resolve("subDir1"));
    Path childFile2 = Files.createFile(childDir1.resolve("file2.txt"));
    Path childDir2 = Files.createDirectory(childDir1.resolve("subDir2"));
    assertThat(target).isDirectory();
    assertThat(childFile1).isRegularFile();
    assertThat(childDir1).isDirectory();
    assertThat(childFile2).isRegularFile();
    assertThat(childDir2).isDirectory();
    FileUtils.deleteQuietly(target.toFile());
    assertThat(target).doesNotExist();
    assertThat(childFile1).doesNotExist();
    assertThat(childDir1).doesNotExist();
    assertThat(childFile2).doesNotExist();
    assertThat(childDir2).doesNotExist();
}

25. DirArtifactCacheTest#testDeleteNothing()

Project: buck
Source File: DirArtifactCacheTest.java
View license
@Test
public void testDeleteNothing() throws IOException {
    Path cacheDir = tmpDir.newFolder();
    Path fileX = cacheDir.resolve("x");
    Path fileY = cacheDir.resolve("y");
    Path fileZ = cacheDir.resolve("z");
    dirArtifactCache = new DirArtifactCache("dir", new ProjectFilesystem(tmpDir.getRoot()), Paths.get("."), /* doStore */
    true, /* maxCacheSizeBytes */
    Optional.of(1024L));
    Files.write(fileX, "x".getBytes(UTF_8));
    Files.write(fileY, "y".getBytes(UTF_8));
    Files.write(fileZ, "z".getBytes(UTF_8));
    assertEquals(3, cacheDir.toFile().listFiles().length);
    dirArtifactCache.deleteOldFiles();
    assertEquals(3, cacheDir.toFile().listFiles().length);
}

26. DirArtifactCacheTest#testDeleteNothingAbsentLimit()

Project: buck
Source File: DirArtifactCacheTest.java
View license
@Test
public void testDeleteNothingAbsentLimit() throws IOException {
    Path cacheDir = tmpDir.newFolder();
    Path fileX = cacheDir.resolve("x");
    Path fileY = cacheDir.resolve("y");
    Path fileZ = cacheDir.resolve("z");
    dirArtifactCache = new DirArtifactCache("dir", new ProjectFilesystem(tmpDir.getRoot()), Paths.get("."), /* doStore */
    true, /* maxCacheSizeBytes */
    Optional.<Long>absent());
    Files.write(fileX, "x".getBytes(UTF_8));
    Files.write(fileY, "y".getBytes(UTF_8));
    Files.write(fileZ, "z".getBytes(UTF_8));
    assertEquals(3, cacheDir.toFile().listFiles().length);
    dirArtifactCache.deleteOldFiles();
    assertEquals(3, cacheDir.toFile().listFiles().length);
}

27. AsynchronousDirectoryContentsCleanerTest#contentsOfTrashDirectoryCleanedAsynchronously()

View license
@Test
public void contentsOfTrashDirectoryCleanedAsynchronously() throws Exception {
    FileSystem vfs = Jimfs.newFileSystem(Configuration.unix());
    Path dirToDelete = vfs.getPath("/tmp/fake-tmp-dir");
    Path fooDir = dirToDelete.resolve("foo");
    Path fooBarDir = fooDir.resolve("bar");
    Files.createDirectories(fooBarDir.resolve("baz"));
    Path fooBarBlechTxtFile = fooBarDir.resolve("blech.txt");
    Files.write(fooBarBlechTxtFile, "hello world\n".getBytes(UTF_8));
    AsynchronousDirectoryContentsCleaner cleaner = new AsynchronousDirectoryContentsCleaner(dirToDelete, MoreExecutors.directExecutor());
    assertThat(Files.exists(dirToDelete), is(true));
    assertThat(Files.exists(fooBarDir), is(true));
    assertThat(Files.exists(fooBarBlechTxtFile), is(true));
    // This executes synchronously, since we passed in a direct executor above.
    cleaner.startCleaningDirectory();
    assertThat(Files.exists(dirToDelete), is(true));
    assertThat(Files.exists(fooBarDir), is(false));
    assertThat(Files.exists(fooBarBlechTxtFile), is(false));
}

28. ExecutableFinderTest#testSearchPathsFileFoundReturnsPath()

Project: buck
Source File: ExecutableFinderTest.java
View license
@Test
public void testSearchPathsFileFoundReturnsPath() throws IOException {
    Path dir1 = tmp.newFolder("foo");
    Path dir2 = tmp.newFolder("bar");
    Path dir3 = tmp.newFolder("baz");
    Path file = createExecutable("bar/blech");
    assertEquals(Optional.of(file), new ExecutableFinder().getOptionalExecutable(Paths.get("blech"), ImmutableList.of(dir1, dir2, dir3), ImmutableList.<String>of()));
}

29. ExecutableFinderTest#testSearchPathsNonExecutableFileIsIgnored()

Project: buck
Source File: ExecutableFinderTest.java
View license
@Test
public void testSearchPathsNonExecutableFileIsIgnored() throws IOException {
    // file.canExecute() always true for Windows
    Assume.assumeFalse(Platform.detect() == Platform.WINDOWS);
    Path dir1 = tmp.newFolder("foo");
    // Note this is not executable.
    tmp.newFile("foo/blech");
    Path dir2 = tmp.newFolder("bar");
    Path dir3 = tmp.newFolder("baz");
    Path file = createExecutable("bar/blech");
    assertEquals(Optional.of(file), new ExecutableFinder().getOptionalExecutable(Paths.get("blech"), ImmutableList.of(dir1, dir2, dir3), ImmutableList.<String>of()));
}

30. ExecutableFinderTest#testSearchPathsMultipleFileFoundReturnsFirstPath()

Project: buck
Source File: ExecutableFinderTest.java
View license
@Test
public void testSearchPathsMultipleFileFoundReturnsFirstPath() throws IOException {
    Path dir1 = tmp.newFolder("foo");
    Path dir2 = tmp.newFolder("bar");
    Path dir3 = tmp.newFolder("baz");
    Path file1 = createExecutable("bar/blech");
    createExecutable("baz/blech");
    assertEquals(Optional.of(file1), new ExecutableFinder().getOptionalExecutable(Paths.get("blech"), ImmutableList.of(dir1, dir2, dir3), ImmutableList.<String>of()));
}

31. ResolverIntegrationTest#shouldDetectNewestJar()

Project: buck
Source File: ResolverIntegrationTest.java
View license
@Test
public void shouldDetectNewestJar() throws Exception {
    Path groupDir = thirdParty.resolve("example");
    Path existingNewerJar = groupDir.resolve("no-deps-1.1.jar");
    Path existingNewestJar = groupDir.resolve("no-deps-1.2.jar");
    Files.createDirectories(groupDir);
    Path sourceJar = repo.resolve("com/example/no-deps/1.0/no-deps-1.0.jar");
    Files.copy(sourceJar, existingNewerJar);
    Files.copy(sourceJar, existingNewestJar);
    Artifact artifact = new DefaultArtifact("com.example", "no-deps", "jar", "1.0");
    Optional<Path> result = new Resolver(newConfig()).getNewerVersionFile(artifact, groupDir);
    assertTrue(result.isPresent());
    assertThat(result.get(), equalTo(existingNewestJar));
}

32. CellTest#shouldResolveFallbackCell()

Project: buck
Source File: CellTest.java
View license
@Test
public void shouldResolveFallbackCell() throws IOException, InterruptedException {
    FileSystem vfs = Jimfs.newFileSystem(Configuration.unix());
    Path root = vfs.getPath("/opt/local/");
    Path cell1Root = root.resolve("repo1");
    Files.createDirectories(cell1Root);
    Path cell2Root = root.resolve("repo2");
    Files.createDirectories(cell2Root);
    ProjectFilesystem filesystem1 = new ProjectFilesystem(cell1Root.toAbsolutePath());
    ProjectFilesystem filesystem2 = new ProjectFilesystem(cell2Root.toAbsolutePath());
    BuckConfig config = FakeBuckConfig.builder().setFilesystem(filesystem1).setSections("[repositories]", "example = " + filesystem2.getRootPath().toString()).build();
    Cell cell1 = new TestCellBuilder().setBuckConfig(config).setFilesystem(filesystem1).build();
    Path path = cell1.getCellRoots().getCellPath(Optional.of("example"));
    assertEquals(path, cell2Root);
}

33. StringifyAlterRuleKeyTest#findAbsolutePathsInMapOfPaths()

Project: buck
Source File: StringifyAlterRuleKeyTest.java
View license
@Test
public void findAbsolutePathsInMapOfPaths() {
    Path path1 = MorePathsForTests.rootRelativePath("some/thing");
    Path path2 = Paths.get("some/thing");
    Path path3 = Paths.get("other/thing");
    Path path4 = MorePathsForTests.rootRelativePath("other/thing");
    Map<Path, Path> input = ImmutableMap.of(path1, path2, path3, path4);
    Assert.assertEquals(ImmutableSet.of(path1, path4), ImmutableSet.copyOf(StringifyAlterRuleKey.findAbsolutePaths(input)));
}

34. TestSynchronousFileFinder#testFindDirectoriesAndRegularFiles()

View license
@Test
public void testFindDirectoriesAndRegularFiles() throws Exception {
    File baseDir = new File("target", UUID.randomUUID().toString()).getAbsoluteFile();
    //Create the following
    //Directories - target/${uuid}/a/bc, target/${uuid}/d/ef
    Path dirPath1 = Paths.get(baseDir.getAbsolutePath().toString() + File.separatorChar + "a" + File.separatorChar + "bc");
    Path dirPath2 = Paths.get(baseDir.getAbsolutePath().toString() + File.separatorChar + "d" + File.separatorChar + "ef");
    //Files - target/${uuid}/a/file.txt, target/${uuid}/d/file.txt
    Path filePath1 = Paths.get(dirPath1.getParent().toString() + File.separatorChar + "file.txt");
    Path filePath2 = Paths.get(dirPath2.getParent().toString() + File.separatorChar + "file.txt");
    Files.createDirectories(dirPath1);
    Files.createDirectories(dirPath2);
    Files.createFile(filePath1);
    Files.createFile(filePath2);
    FileFinder ff = new SynchronousFileFinder(Paths.get(baseDir.getAbsolutePath(), "*/*"), FileFilterOption.FILTER_DIRECTORY_REGULAR_FILES);
    Set<Path> paths = ff.find();
    Assert.assertEquals(4L, paths.size());
    Assert.assertTrue(paths.containsAll(Arrays.asList(dirPath1, dirPath2, filePath1, filePath2)));
}

35. OldIndexBackwardsCompatibilityIT#getNodeDir()

View license
private Path getNodeDir(String indexFile) throws IOException {
    Path unzipDir = createTempDir();
    Path unzipDataDir = unzipDir.resolve("data");
    // decompress the index
    Path backwardsIndex = getBwcIndicesPath().resolve(indexFile);
    try (InputStream stream = Files.newInputStream(backwardsIndex)) {
        TestUtil.unzip(stream, unzipDir);
    }
    // check it is unique
    assertTrue(Files.exists(unzipDataDir));
    Path[] list = FileSystemUtils.files(unzipDataDir);
    if (list.length != 1) {
        throw new IllegalStateException("Backwards index must contain exactly one cluster");
    }
    // the bwc scripts packs the indices under this path
    return list[0].resolve("nodes/0/");
}

36. JimfsUnixLikeFileSystemTest#testPaths_areSortedCaseSensitive()

View license
@Test
public void testPaths_areSortedCaseSensitive() {
    Path p1 = path("a");
    Path p2 = path("B");
    Path p3 = path("c");
    Path p4 = path("D");
    assertThat(Ordering.natural().immutableSortedCopy(Arrays.asList(p3, p4, p1, p2))).isEqualTo(ImmutableList.of(p2, p4, p1, p3));
// would be p1, p2, p3, p4 if sorting were case insensitive
}

37. JimfsWindowsLikeFileSystemTest#testPaths_areSortedCaseInsensitive()

View license
@Test
public void testPaths_areSortedCaseInsensitive() {
    Path p1 = path("a");
    Path p2 = path("B");
    Path p3 = path("c");
    Path p4 = path("D");
    assertThat(Ordering.natural().immutableSortedCopy(Arrays.asList(p3, p4, p1, p2))).isEqualTo(ImmutableList.of(p1, p2, p3, p4));
// would be p2, p4, p1, p3 if sorting were case sensitive
}

38. ContentHandlersTest#step4_BuiltIn()

Project: openjdk
Source File: ContentHandlersTest.java
View license
private static void step4_BuiltIn() throws IOException {
    Path tmp = Files.createDirectory(Paths.get("ContentHandlersTest-4"));
    Path src = templatesHome().resolve("test.template");
    Path dst = tmp.resolve("Test.java");
    Files.copy(src, dst);
    Path build = Files.createDirectory(tmp.resolve("build"));
    javac(build, dst);
    Result r = java(emptyMap(), singleton(build), "Test");
    if (r.exitValue != 0 || !r.output.contains("sun.net.www.content.text.PlainTextInputStream"))
        throw new RuntimeException(r.output);
}

39. Basic#createMRMJarFoo()

Project: openjdk
Source File: Basic.java
View license
/** Similar to createFoo, but with a Multi-Release Modular jar. */
@Test
public void createMRMJarFoo() throws IOException {
    Path mp = Paths.get("createMRMJarFoo");
    createTestDir(mp);
    Path modClasses = MODULE_CLASSES.resolve(FOO.moduleName);
    Path mrjarDir = MRJAR_DIR.resolve(FOO.moduleName);
    Path modularJar = mp.resolve(FOO.moduleName + ".jar");
    // Positive test, create
    jar("--create", "--file=" + modularJar.toString(), "--main-class=" + FOO.mainClass, "--module-version=" + FOO.version, "-m", mrjarDir.resolve("META-INF/MANIFEST.MF").toRealPath().toString(), "-C", mrjarDir.toString(), "META-INF/versions/9/module-info.class", "-C", modClasses.toString(), ".").assertSuccess();
    java(mp, FOO.moduleName + "/" + FOO.mainClass).assertSuccess().resultChecker( r -> assertModuleData(r, FOO));
}

40. Basic#updateMRMJarFoo()

Project: openjdk
Source File: Basic.java
View license
@Test
public void updateMRMJarFoo() throws IOException {
    Path mp = Paths.get("updateMRMJarFoo");
    createTestDir(mp);
    Path modClasses = MODULE_CLASSES.resolve(FOO.moduleName);
    Path mrjarDir = MRJAR_DIR.resolve(FOO.moduleName);
    Path modularJar = mp.resolve(FOO.moduleName + ".jar");
    jar("--create", "--file=" + modularJar.toString(), "--no-manifest", "-C", modClasses.toString(), "jdk").assertSuccess();
    jar("--update", "--file=" + modularJar.toString(), "--main-class=" + FOO.mainClass, "--module-version=" + FOO.version, "-m", mrjarDir.resolve("META-INF/MANIFEST.MF").toRealPath().toString(), "-C", mrjarDir.toString(), "META-INF/versions/9/module-info.class", "-C", modClasses.toString(), "module-info.class").assertSuccess();
    java(mp, FOO.moduleName + "/" + FOO.mainClass).assertSuccess().resultChecker( r -> assertModuleData(r, FOO));
}

41. Basic#partialUpdateMRMJarFooNotAllFiles()

Project: openjdk
Source File: Basic.java
View license
@Test
public void partialUpdateMRMJarFooNotAllFiles() throws IOException {
    Path mp = Paths.get("partialUpdateMRMJarFooNotAllFiles");
    createTestDir(mp);
    Path modClasses = MODULE_CLASSES.resolve(FOO.moduleName);
    Path mrjarDir = MRJAR_DIR.resolve(FOO.moduleName);
    Path modularJar = mp.resolve(FOO.moduleName + ".jar");
    jar("--create", "--file=" + modularJar.toString(), "--module-version=" + FOO.version, "-C", modClasses.toString(), ".").assertSuccess();
    jar("--update", "--file=" + modularJar.toString(), "--main-class=" + FOO.mainClass, "-m", mrjarDir.resolve("META-INF/MANIFEST.MF").toRealPath().toString(), "-C", mrjarDir.toString(), "META-INF/versions/9/module-info.class").assertSuccess();
    java(mp, FOO.moduleName + "/" + FOO.mainClass).assertSuccess().resultChecker( r -> assertModuleData(r, FOO));
}

42. Basic#servicesCreateWithoutFailureMRMJAR()

Project: openjdk
Source File: Basic.java
View license
@Test
public void servicesCreateWithoutFailureMRMJAR() throws IOException {
    Path mp = Paths.get("servicesCreateWithoutFailureMRMJAR");
    createTestDir(mp);
    Path modClasses = MODULE_CLASSES.resolve("baz");
    Path mrjarDir = MRJAR_DIR.resolve("baz");
    Path modularJar = mp.resolve("baz" + ".jar");
    jar("--create", "--file=" + modularJar.toString(), "-m", mrjarDir.resolve("META-INF/MANIFEST.MF").toRealPath().toString(), "-C", modClasses.toString(), "module-info.class", "-C", mrjarDir.toString(), "META-INF/versions/9/module-info.class", "-C", modClasses.toString(), "jdk/test/baz/BazService.class", "-C", modClasses.toString(), "jdk/test/baz/internal/BazServiceImpl.class").assertSuccess();
}

43. Basic#setupMRJARModuleInfo()

Project: openjdk
Source File: Basic.java
View license
static void setupMRJARModuleInfo(String moduleName) throws IOException {
    Path modClasses = MODULE_CLASSES.resolve(moduleName);
    Path metaInfDir = MRJAR_DIR.resolve(moduleName).resolve("META-INF");
    Path versionSection = metaInfDir.resolve("versions").resolve("9");
    createTestDir(versionSection);
    Path versionModuleInfo = versionSection.resolve("module-info.class");
    System.out.println("copying " + modClasses.resolve("module-info.class") + " to " + versionModuleInfo);
    Files.copy(modClasses.resolve("module-info.class"), versionModuleInfo);
    Manifest manifest = new Manifest();
    manifest.getMainAttributes().putValue("Manifest-Version", "1.0");
    manifest.getMainAttributes().putValue("Multi-Release", "true");
    try (OutputStream os = Files.newOutputStream(metaInfDir.resolve("MANIFEST.MF"))) {
        manifest.write(os);
    }
}

44. JLinkNegativeTest#testDuplicateModule3()

Project: openjdk
Source File: JLinkNegativeTest.java
View license
public void testDuplicateModule3() throws IOException {
    String moduleName1 = "dupRes3Jar1";
    String moduleName2 = "dupRes3Jar2";
    List<String> classNames = Arrays.asList("java.A", "javax.B");
    Path module1 = helper.generateModuleCompiledClasses(helper.getJarSrcDir(), helper.getJarClassesDir(), moduleName1, classNames);
    Path module2 = helper.generateModuleCompiledClasses(helper.getJarSrcDir(), helper.getJarClassesDir(), moduleName2, classNames);
    try (OutputStream out = Files.newOutputStream(module2.resolve("module-info.class"))) {
        ModuleInfoWriter.write(new ModuleDescriptor.Builder(moduleName1).requires("java.base").build(), out);
    }
    Path jar1 = JImageGenerator.createJarFile(helper.getJarDir().resolve(moduleName1 + ".jar"), module1);
    Path jar2 = JImageGenerator.createJarFile(helper.getJarDir().resolve(moduleName2 + ".jar"), module2);
    try {
        helper.generateDefaultImage(moduleName1).assertFailure("Error: Two versions of module dupRes3Jar1 found in");
    } finally {
        deleteDirectory(jar1);
        deleteDirectory(jar2);
    }
}

45. AddReadsTest#testAddReadsUnnamedModule()

Project: openjdk
Source File: AddReadsTest.java
View license
@Test
public void testAddReadsUnnamedModule(Path base) throws Exception {
    Path jar = prepareTestJar(base);
    Path moduleSrc = base.resolve("module-src");
    Path m1 = moduleSrc.resolve("m1");
    Path classes = base.resolve("classes");
    Files.createDirectories(classes);
    tb.writeJavaFiles(m1, "module m1 { }", "package impl; public class Impl { api.Api api; }");
    new JavacTask(tb).options("-classpath", jar.toString(), "-XaddReads:m1=ALL-UNNAMED", "-XDrawDiagnostics").outdir(classes).files(findJavaFiles(moduleSrc)).run().writeAll();
}

46. DoclintOtherModules#testSimple()

Project: openjdk
Source File: DoclintOtherModules.java
View license
@Test
public void testSimple(Path base) throws Exception {
    Path src = base.resolve("src");
    Path m1 = src.resolve("m1");
    Path m2 = src.resolve("m2");
    tb.writeJavaFiles(m1, "module m1 {}", "package m1; /** @see m2.B */ @Deprecated public class A {}");
    tb.writeJavaFiles(m2, "module m2 { requires m1; exports m2; }", "package m2; public class B extends Foo {} @Deprecated class Foo {}");
    Path classes = base.resolve("classes");
    Files.createDirectories(classes);
    String log = new JavacTask(tb).options("-XDrawDiagnostics", "-modulesourcepath", src.toString(), "-Xlint:deprecation", "-Xdoclint:-reference", "-Werror").outdir(classes).files(findJavaFiles(m1)).run(Task.Expect.SUCCESS).writeAll().getOutput(Task.OutputKind.DIRECT);
    if (!log.isEmpty())
        throw new Exception("expected output not found: " + log);
}

47. ModuleInfoTest#testDuplicateRequires()

Project: openjdk
Source File: ModuleInfoTest.java
View license
/**
     * Verify that duplicate requires are detected.
     */
@Test
public void testDuplicateRequires(Path base) throws Exception {
    Path src = base.resolve("src");
    Path src_m1 = src.resolve("m1");
    tb.writeFile(src_m1.resolve("module-info.java"), "module m1 { }");
    Path src_m2 = src.resolve("m2");
    tb.writeFile(src_m2.resolve("module-info.java"), "module m2 { requires m1; requires m1; }");
    Path classes = base.resolve("classes");
    Files.createDirectories(classes);
    String log = new JavacTask(tb).options("-XDrawDiagnostics", "-modulesourcepath", src.toString()).outdir(classes).files(findJavaFiles(src)).run(Task.Expect.FAIL).writeAll().getOutput(Task.OutputKind.DIRECT);
    if (!log.contains("module-info.java:1:35: compiler.err.duplicate.requires: m1"))
        throw new Exception("expected output not found");
}

48. ModuleInfoTest#testDuplicateExports_modules()

Project: openjdk
Source File: ModuleInfoTest.java
View license
/**
     * Verify that duplicate exported packages are detected.
     */
@Test
public void testDuplicateExports_modules(Path base) throws Exception {
    Path src = base.resolve("src");
    Path src_m1 = src.resolve("m1");
    tb.writeFile(src_m1.resolve("module-info.java"), "module m1 { }");
    Path src_m2 = src.resolve("m2");
    tb.writeFile(src_m2.resolve("module-info.java"), "module m2 { exports p to m1, m1; }");
    Path classes = base.resolve("classes");
    Files.createDirectories(classes);
    String log = new JavacTask(tb).options("-XDrawDiagnostics", "-modulesourcepath", src.toString()).outdir(classes).files(findJavaFiles(src)).run(Task.Expect.FAIL).writeAll().getOutput(Task.OutputKind.DIRECT);
    if (!log.contains("module-info.java:1:30: compiler.err.duplicate.exports: m1"))
        throw new Exception("expected output not found");
}

49. ModulePathTest#oneModuleHidesAnother()

Project: openjdk
Source File: ModulePathTest.java
View license
@Test
public void oneModuleHidesAnother(Path base) throws Exception {
    Path modules = base.resolve("modules");
    new ModuleBuilder(tb, "m1").exports("pkg1").classes("package pkg1; public class E { }").build(modules);
    Path deepModuleDirSrc = base.resolve("deepModuleDirSrc");
    Path deepModuleDir = modules.resolve("deepModuleDir");
    new ModuleBuilder(tb, "m1").exports("pkg2").classes("package pkg2; public class E { }").build(deepModuleDirSrc, deepModuleDir);
    Path src = base.resolve("src");
    tb.writeJavaFiles(src, "module m2 { requires m1; }", " package p; class A { void main() { pkg2.E.class.getName(); } }");
    new JavacTask(tb, Task.Mode.CMDLINE).options("-XDrawDiagnostics", "-modulepath", deepModuleDir + PATH_SEP + modules).files(findJavaFiles(src)).run().writeAll();
}

50. MultiModuleModeTest#testDuplicateModules()

Project: openjdk
Source File: MultiModuleModeTest.java
View license
@Test
public void testDuplicateModules(Path base) throws Exception {
    Path src = base.resolve("src");
    Path src_m1 = src.resolve("m1");
    tb.writeJavaFiles(src_m1, "module m1 { }");
    Path src_m2 = src.resolve("m2");
    tb.writeJavaFiles(src_m2, "module m1 { }");
    Path classes = base.resolve("classes");
    tb.createDirectories(classes);
    String log = new JavacTask(tb).options("-XDrawDiagnostics", "-modulesourcepath", src.toString()).outdir(classes).files(findJavaFiles(src)).run(Task.Expect.FAIL).writeAll().getOutput(Task.OutputKind.DIRECT);
    if (!log.contains("module-info.java:1:1: compiler.err.duplicate.module: m1"))
        throw new Exception("expected output not found");
}

51. MultiModuleModeTest#testCantFindModule()

Project: openjdk
Source File: MultiModuleModeTest.java
View license
@Test
public void testCantFindModule(Path base) throws Exception {
    Path src = base.resolve("src");
    Path src_m1 = src.resolve("m1");
    tb.writeJavaFiles(src_m1, "module m1 { }");
    Path misc = base.resolve("misc");
    tb.writeJavaFiles(misc, "package p; class C { }");
    Path classes = base.resolve("classes");
    tb.createDirectories(classes);
    String log = new JavacTask(tb).options("-XDrawDiagnostics", "-modulesourcepath", src.toString()).outdir(classes).files(join(findJavaFiles(src), findJavaFiles(misc))).run(Task.Expect.FAIL).writeAll().getOutput(Task.OutputKind.DIRECT);
    if (!log.contains("C.java:1:1: compiler.err.unnamed.pkg.not.allowed.named.modules"))
        throw new Exception("expected output not found");
}

52. NPECompilingModuleInfoTest#testCompileNoError()

View license
@Test
public void testCompileNoError(Path base) throws Exception {
    Path mod = base.resolve("mod");
    tb.writeJavaFiles(mod, "module mod { exports pkg; }");
    Path pkg = mod.resolve("pkg");
    Path customClass = pkg.resolve("module-info.java");
    tb.writeFile(customClass, "package pkg; class C {}");
    Path classes = base.resolve("classes");
    tb.createDirectories(classes);
    new JavacTask(tb).outdir(classes).files(findJavaFiles(mod)).run().writeAll().getOutputLines(Task.OutputKind.DIRECT);
}

53. ReportNonExistentPackageTest#testPackageWithMemberWOPackageDeclaration()

View license
@Test
public void testPackageWithMemberWOPackageDeclaration(Path base) throws Exception {
    Path src = base.resolve("src");
    tb.writeJavaFiles(src, "module m { exports p1; }");
    Path p1 = src.resolve("p1");
    Path C = p1.resolve("C.java");
    tb.writeFile(C, "// comment");
    Path classes = base.resolve("classes");
    Files.createDirectories(classes);
    String log = new JavacTask(tb).options("-XDrawDiagnostics").outdir(classes).files(findJavaFiles(src)).run(Task.Expect.FAIL).writeAll().getOutput(Task.OutputKind.DIRECT);
    if (!log.contains("module-info.java:1:20: compiler.err.package.empty.or.not.found: p1"))
        throw new Exception("expected output not found");
}

54. RemovedJDKInternals#compileAll()

Project: openjdk
Source File: RemovedJDKInternals.java
View license
/**
     * Compiles classes used by the test
     */
@BeforeTest
public void compileAll() throws Exception {
    CompilerUtils.cleanDir(PATCHES_DIR);
    CompilerUtils.cleanDir(CLASSES_DIR);
    // compile sun.misc types
    Path sunMiscSrc = Paths.get(TEST_SRC, "patches", JDK_UNSUPPORTED);
    Path patchDir = PATCHES_DIR.resolve(JDK_UNSUPPORTED);
    assertTrue(CompilerUtils.compile(sunMiscSrc, patchDir, "-Xmodule:" + JDK_UNSUPPORTED));
    // compile com.sun.image.codec.jpeg types
    Path codecSrc = Paths.get(TEST_SRC, "patches", "java.desktop");
    Path codecDest = PATCHES_DIR;
    assertTrue(CompilerUtils.compile(codecSrc, codecDest));
    // patch jdk.unsupported and set -cp to codec types
    assertTrue(CompilerUtils.compile(Paths.get(TEST_SRC, "src"), CLASSES_DIR, "-Xpatch:jdk.unsupported=" + patchDir, "-cp", codecDest.toString()));
}

55. AppPropertiesTest#constructorShouldUseHomeDirIfPropertiesNotInWorkingDir()

Project: SAGU
Source File: AppPropertiesTest.java
View license
@Test
public void constructorShouldUseHomeDirIfPropertiesNotInWorkingDir() throws Exception {
    final Path working = Files.createTempDirectory("working");
    final Path home = Files.createTempDirectory("home");
    final Path saguHome = Paths.get(home.toString(), ".sagu");
    Files.createDirectory(saguHome);
    final Path propFile = Files.createFile(Paths.get(saguHome.toString(), "SAGU.properties"));
    Files.write(propFile, singleton("accessKey=TEST"));
    final AppProperties properties = new AppProperties(working.toString(), saguHome.toString());
    assertThat(properties.getAccessKey(), is("TEST"));
}

56. TestIOUtils#testSSD()

Project: lucene-solr
Source File: TestIOUtils.java
View license
public void testSSD() throws Exception {
    assumeFalse("windows is not supported", Constants.WINDOWS);
    Path dir = createTempDir();
    dir = FilterPath.unwrap(dir).toRealPath();
    // fake ssd
    FileStore root = new MockFileStore(dir.toString() + " (/dev/zzz1)", "btrfs", "/dev/zzz1");
    // make a fake /dev/zzz1 for it
    Path devdir = dir.resolve("dev");
    Files.createDirectories(devdir);
    Files.createFile(devdir.resolve("zzz1"));
    // make a fake /sys/block/zzz/queue/rotational file for it
    Path sysdir = dir.resolve("sys").resolve("block").resolve("zzz").resolve("queue");
    Files.createDirectories(sysdir);
    try (OutputStream o = Files.newOutputStream(sysdir.resolve("rotational"))) {
        o.write("0\n".getBytes(StandardCharsets.US_ASCII));
    }
    Map<String, FileStore> mappings = Collections.singletonMap(dir.toString(), root);
    FileSystem mockLinux = new MockLinuxFileSystemProvider(dir.getFileSystem(), mappings, dir).getFileSystem(null);
    Path mockPath = mockLinux.getPath(dir.toString());
    assertFalse(IOUtils.spinsLinux(mockPath));
}

57. TestIOUtils#testRotatingPlatters()

Project: lucene-solr
Source File: TestIOUtils.java
View license
public void testRotatingPlatters() throws Exception {
    assumeFalse("windows is not supported", Constants.WINDOWS);
    Path dir = createTempDir();
    dir = FilterPath.unwrap(dir).toRealPath();
    // fake ssd
    FileStore root = new MockFileStore(dir.toString() + " (/dev/zzz1)", "reiser4", "/dev/zzz1");
    // make a fake /dev/zzz1 for it
    Path devdir = dir.resolve("dev");
    Files.createDirectories(devdir);
    Files.createFile(devdir.resolve("zzz1"));
    // make a fake /sys/block/zzz/queue/rotational file for it
    Path sysdir = dir.resolve("sys").resolve("block").resolve("zzz").resolve("queue");
    Files.createDirectories(sysdir);
    try (OutputStream o = Files.newOutputStream(sysdir.resolve("rotational"))) {
        o.write("1\n".getBytes(StandardCharsets.US_ASCII));
    }
    Map<String, FileStore> mappings = Collections.singletonMap(dir.toString(), root);
    FileSystem mockLinux = new MockLinuxFileSystemProvider(dir.getFileSystem(), mappings, dir).getFileSystem(null);
    Path mockPath = mockLinux.getPath(dir.toString());
    assertTrue(IOUtils.spinsLinux(mockPath));
}

58. TestIOUtils#testManyPartitions()

Project: lucene-solr
Source File: TestIOUtils.java
View license
public void testManyPartitions() throws Exception {
    assumeFalse("windows is not supported", Constants.WINDOWS);
    Path dir = createTempDir();
    dir = FilterPath.unwrap(dir).toRealPath();
    // fake ssd
    FileStore root = new MockFileStore(dir.toString() + " (/dev/zzz12)", "zfs", "/dev/zzz12");
    // make a fake /dev/zzz11 for it
    Path devdir = dir.resolve("dev");
    Files.createDirectories(devdir);
    Files.createFile(devdir.resolve("zzz12"));
    // make a fake /sys/block/zzz/queue/rotational file for it
    Path sysdir = dir.resolve("sys").resolve("block").resolve("zzz").resolve("queue");
    Files.createDirectories(sysdir);
    try (OutputStream o = Files.newOutputStream(sysdir.resolve("rotational"))) {
        o.write("0\n".getBytes(StandardCharsets.US_ASCII));
    }
    Map<String, FileStore> mappings = Collections.singletonMap(dir.toString(), root);
    FileSystem mockLinux = new MockLinuxFileSystemProvider(dir.getFileSystem(), mappings, dir).getFileSystem(null);
    Path mockPath = mockLinux.getPath(dir.toString());
    assertFalse(IOUtils.spinsLinux(mockPath));
}

59. MockFileSystemTestCase#testHashCodeEquals()

View license
/** Test that Path.hashcode/equals are sane */
public void testHashCodeEquals() throws IOException {
    Path dir = wrap(createTempDir());
    Path f1 = dir.resolve("file1");
    Path f1Again = dir.resolve("file1");
    Path f2 = dir.resolve("file2");
    assertEquals(f1, f1);
    assertFalse(f1.equals(null));
    assertEquals(f1, f1Again);
    assertEquals(f1.hashCode(), f1Again.hashCode());
    assertFalse(f1.equals(f2));
    dir.getFileSystem().close();
}

60. AbstractFullDistribZkTestBase#getRelativeSolrHomePath()

View license
private File getRelativeSolrHomePath(File solrHome) {
    final Path solrHomePath = solrHome.toPath();
    final Path curDirPath = new File("").getAbsoluteFile().toPath();
    if (!solrHomePath.getRoot().equals(curDirPath.getRoot())) {
        // root of current directory and solrHome are not the same, therefore cannot relativize
        return solrHome;
    }
    final Path root = solrHomePath.getRoot();
    // relativize current directory to root: /tmp/foo -> /tmp/foo/../..
    final File relativizedCurDir = new File(curDirPath.toFile(), curDirPath.relativize(root).toString());
    // exclude the root from solrHome: /tmp/foo/solrHome -> tmp/foo/solrHome
    final Path solrHomeRelativeToRoot = root.relativize(solrHomePath);
    // create the relative solrHome: /tmp/foo/../../tmp/foo/solrHome
    return new File(relativizedCurDir, solrHomeRelativeToRoot.toString()).getAbsoluteFile();
}

61. ApkDecoder#copyOtherResFiles()

Project: AndResGuard
Source File: ApkDecoder.java
View license
private void copyOtherResFiles() throws IOException {
    if (mRawResourceFiles.isEmpty())
        return;
    Path resPath = mRawResFile.toPath();
    Path destPath = mOutResFile.toPath();
    for (Path path : mRawResourceFiles) {
        Path relativePath = resPath.relativize(path);
        Path dest = destPath.resolve(relativePath);
        System.out.printf("copy res file not in resources.arsc file:%s\n", relativePath.toString());
        FileOperation.copyFileUsingStream(path.toFile(), dest.toFile());
    }
}

62. Paths#assertHasParent()

Project: assertj-core
Source File: Paths.java
View license
public void assertHasParent(final AssertionInfo info, final Path actual, final Path expected) {
    assertNotNull(info, actual);
    checkExpectedParentPathIsNotNull(expected);
    final Path canonicalActual;
    try {
        canonicalActual = actual.toRealPath();
    } catch (IOException e) {
        throw new PathsException(FAILED_TO_RESOLVE_ACTUAL_REAL_PATH, e);
    }
    final Path canonicalExpected;
    try {
        canonicalExpected = expected.toRealPath();
    } catch (IOException e) {
        throw new PathsException(FAILED_TO_RESOLVE_ARGUMENT_REAL_PATH, e);
    }
    final Path actualParent = canonicalActual.getParent();
    if (actualParent == null)
        throw failures.failure(info, shouldHaveParent(actual, expected));
    if (!actualParent.equals(canonicalExpected))
        throw failures.failure(info, shouldHaveParent(actual, actualParent, expected));
}

63. SourceFile#allSourceFiles()

Project: bazel
Source File: SourceFile.java
View license
/**
   * Returns information on all source files in a target. In particular, this includes:
   * <ul>
   *   <li>arc-compiled source files
   *   <li>non-arc-compiled source files
   *   <li>support files, such as BUILD and header files
   *   <li>Info.plist file
   * </ul>
   */
public static Iterable<SourceFile> allSourceFiles(FileSystem fileSystem, TargetControl control) {
    ImmutableList.Builder<SourceFile> result = new ImmutableList.Builder<>();
    for (Path plainSource : RelativePaths.fromStrings(fileSystem, control.getSourceFileList())) {
        result.add(new SourceFile(BuildType.BUILD, plainSource));
    }
    for (Path nonArcSource : RelativePaths.fromStrings(fileSystem, control.getNonArcSourceFileList())) {
        result.add(new SourceFile(BuildType.NON_ARC_BUILD, nonArcSource));
    }
    for (Path supportSource : RelativePaths.fromStrings(fileSystem, control.getSupportFileList())) {
        result.add(new SourceFile(BuildType.NO_BUILD, supportSource));
    }
    if (control.hasInfoplist()) {
        result.add(new SourceFile(BuildType.NO_BUILD, RelativePaths.fromString(fileSystem, control.getInfoplist())));
    }
    return result.build();
}

64. IdlClass#writeSourceJar()

Project: bazel
Source File: IdlClass.java
View license
private static void writeSourceJar(IdlClassOptions options, List<Path> idlSources, Manifest manifest) throws IOException {
    Path tempDir = options.tempDir.resolve("sourcejar");
    Path idlSourceBaseDir = options.idlSourceBaseDir;
    for (Path path : idlSources) {
        for (CompilationUnit unit : manifest.getCompilationUnitList()) {
            if (unit.getPath().equals(path.toString())) {
                String pkg = unit.getPkg();
                Path source = idlSourceBaseDir != null ? idlSourceBaseDir.resolve(path) : path;
                Path target = tempDir.resolve(pkg.replace('.', '/')).resolve(path.getFileName());
                Files.createDirectories(target.getParent());
                Files.copy(source, target);
                break;
            }
        }
    }
    writeOutputJar(options.outputSourceJar, tempDir);
}

65. MiniAapt#processXmlFilesForIds()

Project: buck
Source File: MiniAapt.java
View license
void processXmlFilesForIds(ProjectFilesystem filesystem, ImmutableSet.Builder<RDotTxtEntry> references) throws IOException, XPathExpressionException, ResourceParseException {
    Path absoluteResDir = resolver.getAbsolutePath(resDirectory);
    Path relativeResDir = resolver.getRelativePath(resDirectory);
    for (Path path : filesystem.getFilesUnderPath(absoluteResDir, ENDS_WITH_XML)) {
        String dirname = relativeResDir.relativize(path).getName(0).toString();
        if (isAValuesDir(dirname)) {
            // Ignore files under values* directories.
            continue;
        }
        processXmlFile(filesystem, path, references);
    }
}

66. ReactNativeBundle#getBuildSteps()

Project: buck
Source File: ReactNativeBundle.java
View license
@Override
public ImmutableList<Step> getBuildSteps(BuildContext context, BuildableContext buildableContext) {
    ImmutableList.Builder<Step> steps = ImmutableList.builder();
    // Generate the normal outputs.
    final Path jsOutput = jsOutputDir.resolve(bundleName);
    steps.add(new MakeCleanDirectoryStep(getProjectFilesystem(), jsOutput.getParent()));
    steps.add(new MakeCleanDirectoryStep(getProjectFilesystem(), resource));
    final Path sourceMapOutput = getPathToSourceMap(getBuildTarget(), getProjectFilesystem());
    steps.add(new MakeCleanDirectoryStep(getProjectFilesystem(), sourceMapOutput.getParent()));
    final Path depFile = getPathToDepFile(getBuildTarget(), getProjectFilesystem());
    steps.add(new MakeCleanDirectoryStep(getProjectFilesystem(), depFile.getParent()));
    appendWorkerSteps(steps, jsOutput, sourceMapOutput, depFile);
    buildableContext.recordArtifact(jsOutputDir);
    buildableContext.recordArtifact(resource);
    buildableContext.recordArtifact(sourceMapOutput.getParent());
    return steps.build();
}

67. FilesystemBackedBuildFileTree#isBuckOutput()

View license
/**
   * Assume that any directory called "buck-out", "buck-out/cache" or ".buckd" can be ignored. Not
   * the world's best heuristic, but it works in every existing code base we have access to.
   */
private boolean isBuckOutput(Path path) {
    Path sameFsBuckOut = path.getFileSystem().getPath(projectFilesystem.getBuckPaths().getBuckOut().toString());
    Path sameFsBuckCache = path.getFileSystem().getPath(BuckConstant.getDefaultCacheDir());
    for (Path segment : path) {
        if (sameFsBuckOut.equals(segment) || sameFsBuckCache.equals(segment)) {
            return true;
        }
    }
    return false;
}

68. SymlinkFilesIntoDirectoryStep#execute()

View license
@Override
public StepExecutionResult execute(ExecutionContext context) {
    // Note that because these paths are resolved to absolute paths, the symlinks will be absolute
    // paths, as well.
    Path outDir = filesystem.resolve(this.outDir);
    Path srcDir = filesystem.resolve(this.srcDir);
    for (Path entry : entries) {
        Path link = outDir.resolve(entry);
        Path target = srcDir.resolve(entry);
        try {
            Files.createDirectories(link.getParent());
            filesystem.createSymLink(link, target, false);
        } catch (IOException e) {
            context.logError(e, "Failed to create symlink from %s to %s.", link, target);
            return StepExecutionResult.ERROR;
        }
    }
    return StepExecutionResult.SUCCESS;
}

69. CxxPrepareForLinkStepTest#cxxLinkStepCreatesDirectoriesIfNeeded()

Project: buck
Source File: CxxPrepareForLinkStepTest.java
View license
@Test
public void cxxLinkStepCreatesDirectoriesIfNeeded() throws IOException, InterruptedException {
    ProjectFilesystem projectFilesystem = new FakeProjectFilesystem();
    Path argFilePath = projectFilesystem.getRootPath().resolve("/tmp/unexisting_parent_folder/argfile.txt");
    Path fileListPath = projectFilesystem.getRootPath().resolve("/tmp/unexisting_parent_folder/filelist.txt");
    Path output = projectFilesystem.getRootPath().resolve("output");
    Files.deleteIfExists(argFilePath);
    Files.deleteIfExists(fileListPath);
    Files.deleteIfExists(argFilePath.getParent());
    Files.deleteIfExists(fileListPath.getParent());
    runTestForArgFilePathAndOutputPath(argFilePath, fileListPath, output);
    // cleanup after test
    Files.deleteIfExists(argFilePath);
    Files.deleteIfExists(argFilePath.getParent());
    Files.deleteIfExists(fileListPath);
    Files.deleteIfExists(fileListPath.getParent());
}

70. DotNetFrameworkResolvingTest#shouldFindDotNet35Directory()

View license
@Test
public void shouldFindDotNet35Directory() throws IOException {
    ImmutableMap<String, String> env = ImmutableMap.of("ProgramFiles(x86)", programFiles);
    Path baseDir = baseFrameworkDir.resolve("v3.5");
    Files.createDirectories(baseDir);
    Path expected = baseDir.resolve("cake.dll");
    Files.write(expected, "".getBytes(UTF_8));
    DotNetFramework framework = DotNetFramework.resolveFramework(filesystem, env, NET35);
    Path actual = framework.findReferenceAssembly("cake.dll");
    assertEquals(expected, actual);
}

71. DotNetFrameworkResolvingTest#shouldFindVersionOfDotNetFrameworkGreaterThan35()

View license
@Test
public void shouldFindVersionOfDotNetFrameworkGreaterThan35() throws IOException {
    ImmutableMap<String, String> env = ImmutableMap.of("ProgramFiles(x86)", programFiles);
    Path baseDir = baseFrameworkDir.resolve(".NETFramework").resolve("v4.6");
    Files.createDirectories(baseDir);
    Path expected = baseDir.resolve("cake.dll");
    Files.write(expected, "".getBytes(UTF_8));
    DotNetFramework framework = DotNetFramework.resolveFramework(filesystem, env, NET46);
    Path actual = framework.findReferenceAssembly("cake.dll");
    assertEquals(expected, actual);
}

72. OnDiskMavenDownloaderTest#shouldDownloadFileFromLocalMavenRepoWindows()

Project: buck
Source File: OnDiskMavenDownloaderTest.java
View license
@Test
public void shouldDownloadFileFromLocalMavenRepoWindows() throws URISyntaxException, IOException {
    FileSystem filesystem = Jimfs.newFileSystem(Configuration.windows());
    Path root = filesystem.getPath("C:\\Users\\bob\\.m2");
    Files.createDirectories(root);
    URI uri = new URI("mvn:group:project:jar:0.1");
    Path output = filesystem.getPath("output.txt");
    Path source = root.resolve("group/project/0.1/project-0.1.jar");
    Files.createDirectories(source.getParent());
    Files.write(source, "cake".getBytes(UTF_8));
    Downloader downloader = new OnDiskMavenDownloader(root);
    downloader.fetch(BuckEventBusFactory.newInstance(), uri, output);
    String result = new String(Files.readAllBytes(output), UTF_8);
    assertThat("cake", Matchers.equalTo(result));
}

73. ExecutableFinderTest#testSearchPathsDirAndFileFoundReturnsFileNotDir()

Project: buck
Source File: ExecutableFinderTest.java
View license
@Test
public void testSearchPathsDirAndFileFoundReturnsFileNotDir() throws IOException {
    Path dir1 = tmp.newFolder("foo");
    // We don't want to find this folder.
    tmp.newFolder("foo", "foo");
    Path dir2 = tmp.newFolder("bar");
    Path file = createExecutable("bar/foo");
    assertEquals(Optional.of(file), new ExecutableFinder().getOptionalExecutable(Paths.get("foo"), ImmutableList.of(dir1, dir2), ImmutableList.<String>of()));
}

74. ExecutableFinderTest#testSearchPathsFileNotFoundReturnsAbsent()

Project: buck
Source File: ExecutableFinderTest.java
View license
@Test
public void testSearchPathsFileNotFoundReturnsAbsent() throws IOException {
    Path dir1 = tmp.newFolder("foo");
    Path dir2 = tmp.newFolder("bar");
    Path dir3 = tmp.newFolder("baz");
    assertEquals(Optional.<Path>absent(), new ExecutableFinder().getOptionalExecutable(Paths.get("blech"), ImmutableList.of(dir1, dir2, dir3), ImmutableList.<String>of()));
}

75. MoreFilesTest#deleteRecursivelyContentsOnlyLeavesParentDirectory()

Project: buck
Source File: MoreFilesTest.java
View license
@Test
public void deleteRecursivelyContentsOnlyLeavesParentDirectory() throws IOException {
    FileSystem vfs = Jimfs.newFileSystem(Configuration.unix());
    Path fakeTmpDir = vfs.getPath("/tmp/fake-tmp-dir");
    Path dirToDelete = fakeTmpDir.resolve("delete-me");
    Path childDir = dirToDelete.resolve("child-dir");
    Files.createDirectories(childDir);
    MoreFiles.deleteRecursivelyWithOptions(dirToDelete, EnumSet.of(MoreFiles.DeleteRecursivelyOptions.DELETE_CONTENTS_ONLY));
    assertThat(Files.exists(dirToDelete), is(true));
    assertThat(Files.exists(childDir), is(false));
}

76. MoreFilesTest#concatenatingTwoEmptyFilesReturnsFalse()

Project: buck
Source File: MoreFilesTest.java
View license
@Test
public void concatenatingTwoEmptyFilesReturnsFalse() throws Exception {
    FileSystem vfs = Jimfs.newFileSystem(Configuration.unix());
    Path fooPath = vfs.getPath("foo.txt");
    Files.write(fooPath, new byte[0]);
    Path barPath = vfs.getPath("bar.txt");
    Files.write(barPath, new byte[0]);
    Path outputPath = vfs.getPath("logs.txt");
    boolean concatenated = MoreFiles.concatenateFiles(outputPath, ImmutableList.of(fooPath, barPath));
    assertThat(concatenated, is(false));
    assertThat(Files.exists(outputPath), is(false));
}

77. MoreFilesTest#concatenatingTwoNonEmptyFilesReturnsTrueAndWritesConcatenatedFile()

Project: buck
Source File: MoreFilesTest.java
View license
@Test
public void concatenatingTwoNonEmptyFilesReturnsTrueAndWritesConcatenatedFile() throws Exception {
    FileSystem vfs = Jimfs.newFileSystem(Configuration.unix());
    Path fooPath = vfs.getPath("foo.txt");
    Files.write(fooPath, "hello world\n".getBytes(UTF_8));
    Path barPath = vfs.getPath("bar.txt");
    Files.write(barPath, "goodbye world\n".getBytes(UTF_8));
    Path outputPath = vfs.getPath("logs.txt");
    boolean concatenated = MoreFiles.concatenateFiles(outputPath, ImmutableList.of(fooPath, barPath));
    assertThat(concatenated, is(true));
    assertThat(Files.readAllLines(outputPath, UTF_8), Matchers.<List<String>>equalTo(ImmutableList.of("hello world", "goodbye world")));
}

78. ProjectFilesystemTest#testSortedDirectoryContents()

Project: buck
Source File: ProjectFilesystemTest.java
View license
@Test
public void testSortedDirectoryContents() throws IOException {
    tmp.newFolder("foo");
    Path a = tmp.newFile("foo/a.txt");
    Files.setLastModifiedTime(a, FileTime.fromMillis(1000));
    Path b = tmp.newFile("foo/b.txt");
    Files.setLastModifiedTime(b, FileTime.fromMillis(2000));
    Path c = tmp.newFile("foo/c.txt");
    Files.setLastModifiedTime(c, FileTime.fromMillis(3000));
    tmp.newFile("foo/non-matching");
    assertEquals(ImmutableSet.of(c, b, a), filesystem.getSortedMatchingDirectoryContents(Paths.get("foo"), "*.txt"));
}

79. StubJarIntegrationTest#shouldBuildAbiJarFromAbiJarWeCreated()

Project: buck
Source File: StubJarIntegrationTest.java
View license
@Test
public void shouldBuildAbiJarFromAbiJarWeCreated() throws IOException {
    Path mid = Paths.get("junit-mid.jar");
    Path source = testDataDir.resolve("junit.jar");
    new StubJar(source).writeTo(filesystem, mid);
    Path out = Paths.get("junit-abi.jar");
    new StubJar(filesystem.resolve(mid)).writeTo(filesystem, out);
    assertTrue(filesystem.getFileSize(out) > 0);
    assertEquals(filesystem.getFileSize(mid), filesystem.getFileSize(out));
}

80. CalculateAbiStepTest#fallsBackToCalculatingAbiFromInputJarIfClassFileIsMalformed()

Project: buck
Source File: CalculateAbiStepTest.java
View license
@Test
public void fallsBackToCalculatingAbiFromInputJarIfClassFileIsMalformed() throws IOException {
    Path outDir = temp.newFolder().toPath().toAbsolutePath();
    ProjectFilesystem filesystem = new ProjectFilesystem(outDir);
    Path binJar = outDir.resolve("bad.jar");
    try (Zip zip = new Zip(binJar, true)) {
        zip.add("Broken.class", "cafebabe bacon and cheese".getBytes(UTF_8));
    }
    String expectedHash = filesystem.computeSha1(binJar);
    Path abiJar = outDir.resolve("abi.jar");
    ExecutionContext executionContext = TestExecutionContext.newBuilder().build();
    FakeBuildableContext context = new FakeBuildableContext();
    new CalculateAbiStep(context, filesystem, binJar, abiJar).execute(executionContext);
    ImmutableMap<String, Object> metadata = context.getRecordedMetadata();
    Object seenHash = metadata.get(AbiRule.ABI_KEY_ON_DISK_METADATA);
    assertEquals(expectedHash, seenHash);
}

81. IjModuleGraphTest#testUnblockedDivergentPathDepthCalculation()

Project: buck
Source File: IjModuleGraphTest.java
View license
@Test
public void testUnblockedDivergentPathDepthCalculation() {
    IjModuleGraph.BlockedPathNode rootNode = new IjModuleGraph.BlockedPathNode();
    Path blockedPath = Paths.get("/a/b/c/block");
    int blockedPathNameCount = blockedPath.getNameCount();
    rootNode.markAsBlocked(blockedPath, 0, blockedPathNameCount);
    // Paths diverge one level above the block
    Path unblockedPath = Paths.get("/a/b/c/noblock/e/f");
    assertThat(IjModuleGraph.calculatePathDepth(unblockedPath, 2, rootNode), Matchers.equalTo(blockedPathNameCount - 1));
    // Paths diverge two levels above the block
    Path unblockedPath2 = Paths.get("/a/b/x/noblock/e/f");
    assertThat(IjModuleGraph.calculatePathDepth(unblockedPath2, 2, rootNode), Matchers.equalTo(blockedPathNameCount - 2));
}

82. ResolverIntegrationTest#shouldNotDownloadOlderJar()

Project: buck
Source File: ResolverIntegrationTest.java
View license
@Test
public void shouldNotDownloadOlderJar() throws Exception {
    Path existingNewerJar = thirdParty.resolve("example/no-deps-1.1.jar");
    Files.createDirectories(existingNewerJar.getParent());
    Files.copy(repo.resolve("com/example/no-deps/1.0/no-deps-1.0.jar"), existingNewerJar);
    Path groupDir = thirdParty.resolve("example");
    Path repoOlderJar = groupDir.resolve("no-deps-1.0.jar");
    assertFalse(Files.exists(repoOlderJar));
    resolveWithArtifacts("com.example:no-deps:jar:1.0");
    assertTrue(Files.exists(groupDir));
    // assert newer jar is in the third-party dir
    assertTrue(Files.exists(existingNewerJar));
    assertFalse(Files.exists(repoOlderJar));
    // assert BUCK file was created
    assertTrue(Files.exists(groupDir.resolve("BUCK")));
}

83. FilesystemBackedBuildFileTreeTest#shouldIgnoreBuckOutputDirectoriesByDefault()

View license
@Test
public void shouldIgnoreBuckOutputDirectoriesByDefault() throws IOException {
    Path root = tmp.getRoot();
    ProjectFilesystem filesystem = new ProjectFilesystem(root, new Config());
    Path buckOut = root.resolve(filesystem.getBuckPaths().getBuckOut());
    Files.createDirectories(buckOut);
    touch(buckOut.resolve("BUCK"));
    Path sibling = buckOut.resolve("someFile");
    touch(sibling);
    // Config doesn't set any "ignore" entries.
    BuildFileTree buildFileTree = new FilesystemBackedBuildFileTree(filesystem, "BUCK");
    Optional<Path> ancestor = buildFileTree.getBasePathOfAncestorTarget(filesystem.getBuckPaths().getBuckOut().resolve("someFile"));
    assertFalse(ancestor.isPresent());
}

84. FilesystemBackedBuildFileTreeTest#shouldIgnoreBuckCacheDirectoriesByDefault()

View license
@Test
public void shouldIgnoreBuckCacheDirectoriesByDefault() throws IOException {
    Path root = tmp.getRoot();
    Path cacheDir = root.resolve(BuckConstant.getDefaultCacheDir());
    Files.createDirectories(cacheDir);
    touch(cacheDir.resolve("BUCK"));
    Path sibling = cacheDir.resolve("someFile");
    touch(sibling);
    // Config doesn't set any "ignore" entries.
    ProjectFilesystem filesystem = new ProjectFilesystem(root, new Config());
    BuildFileTree buildFileTree = new FilesystemBackedBuildFileTree(filesystem, "BUCK");
    Optional<Path> ancestor = buildFileTree.getBasePathOfAncestorTarget(cacheDir.resolve("someFile"));
    assertFalse(ancestor.isPresent());
}

85. StringifyAlterRuleKeyTest#findAbsolutePathsInRecursiveStructure()

Project: buck
Source File: StringifyAlterRuleKeyTest.java
View license
@Test
public void findAbsolutePathsInRecursiveStructure() {
    FakeProjectFilesystem projectFilesystem = new FakeProjectFilesystem();
    Path path1 = MorePathsForTests.rootRelativePath("some/thing");
    Path path2 = MorePathsForTests.rootRelativePath("other/thing");
    Path path3 = MorePathsForTests.rootRelativePath("yet/another/thing");
    Object input = ImmutableList.of(ImmutableMap.of(Optional.absent(), path1), ImmutableSet.of(Optional.of(path2)), Optional.absent(), Optional.of(new PathSourcePath(projectFilesystem, path3)));
    Assert.assertEquals(ImmutableSet.of(path1, path2, path3), ImmutableSet.copyOf(StringifyAlterRuleKey.findAbsolutePaths(input)));
}

86. SourcePathResolverTest#testGetAbsolutePathForArchiveMemberSourcePath()

Project: buck
Source File: SourcePathResolverTest.java
View license
@Test
public void testGetAbsolutePathForArchiveMemberSourcePath() {
    ProjectFilesystem filesystem = new FakeProjectFilesystem();
    BuildRuleResolver resolver = new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer());
    SourcePathResolver pathResolver = new SourcePathResolver(resolver);
    BuildRule rule = resolver.addToIndex(new FakeBuildRule(BuildTargetFactory.newInstance("//foo:bar"), filesystem, pathResolver));
    Path archivePath = filesystem.getBuckPaths().getGenDir().resolve("foo.jar");
    Path archiveAbsolutePath = filesystem.resolve(archivePath);
    SourcePath archiveSourcePath = new BuildTargetSourcePath(rule.getBuildTarget(), archivePath);
    Path memberPath = Paths.get("foo.class");
    ArchiveMemberSourcePath path = new ArchiveMemberSourcePath(archiveSourcePath, memberPath);
    ArchiveMemberPath absolutePath = pathResolver.getAbsoluteArchiveMemberPath(path);
    assertEquals(archiveAbsolutePath, absolutePath.getArchivePath());
    assertEquals(memberPath, absolutePath.getMemberPath());
}

87. WorkerProcessProtocolZeroTest#testSendCommand()

View license
@Test
public void testSendCommand() throws IOException {
    StringWriter jsonSentToWorkerProcess = new StringWriter();
    WorkerProcessProtocol protocol = new WorkerProcessProtocolZero(fakeProcessExecutor, fakeLaunchedProcess, new JsonWriter(jsonSentToWorkerProcess), dummyJsonReader);
    int messageID = 123;
    Path argsPath = Paths.get("args");
    Path stdoutPath = Paths.get("stdout");
    Path stderrPath = Paths.get("stderr");
    protocol.sendCommand(messageID, argsPath, stdoutPath, stderrPath);
    String expectedJson = String.format("{\"id\":%d,\"type\":\"command\"," + "\"args_path\":\"%s\",\"stdout_path\":\"%s\",\"stderr_path\":\"%s\"}", messageID, argsPath.toString(), stdoutPath.toString(), stderrPath.toString());
    assertThat(jsonSentToWorkerProcess.toString(), Matchers.containsString(expectedJson));
}

88. FakeProjectFilesystemTest#testSortedDirectoryContents()

Project: buck
Source File: FakeProjectFilesystemTest.java
View license
@Test
public void testSortedDirectoryContents() throws IOException {
    SettableFakeClock clock = new SettableFakeClock(1000, 0);
    FakeProjectFilesystem filesystem = new FakeProjectFilesystem(clock);
    filesystem.mkdirs(Paths.get("foo"));
    Path a = Paths.get("foo/a.txt");
    filesystem.touch(a);
    clock.setCurrentTimeMillis(2000);
    Path b = Paths.get("foo/b.txt");
    filesystem.touch(b);
    clock.setCurrentTimeMillis(3000);
    Path c = Paths.get("foo/c.txt");
    filesystem.touch(c);
    filesystem.touch(Paths.get("foo/non-matching"));
    assertEquals(ImmutableSet.of(c, b, a), filesystem.getSortedMatchingDirectoryContents(Paths.get("foo"), "*.txt"));
}

89. FakeProjectFilesystemTest#testCreateZip()

Project: buck
Source File: FakeProjectFilesystemTest.java
View license
@Test
public void testCreateZip() throws IOException {
    FakeProjectFilesystem filesystem = new FakeProjectFilesystem();
    byte[] contents = "contents".getBytes();
    Path file = Paths.get("file");
    filesystem.writeBytesToPath(contents, file);
    Path dir = Paths.get("dir");
    filesystem.mkdirs(dir);
    filesystem.writeBytesToPath(contents, dir.resolve("file"));
    Path output = tmp.newFile("output.zip");
    filesystem.createZip(ImmutableList.of(file, dir, dir.resolve("file")), output);
    try (Zip zip = new Zip(output, /* forWriting */
    false)) {
        assertEquals(ImmutableSet.of("", "dir/"), zip.getDirNames());
        assertEquals(ImmutableSet.of("file", "dir/file"), zip.getFileNames());
        assertArrayEquals(contents, zip.readFully("file"));
        assertArrayEquals(contents, zip.readFully("dir/file"));
    }
}

90. DefaultFileHashCacheTest#whenDirectoryIsPutThenInvalidatedCacheDoesNotContainPathOrChildren()

Project: buck
Source File: DefaultFileHashCacheTest.java
View license
@Test
public void whenDirectoryIsPutThenInvalidatedCacheDoesNotContainPathOrChildren() throws IOException {
    ProjectFilesystem filesystem = new FakeProjectFilesystem();
    DefaultFileHashCache cache = new DefaultFileHashCache(filesystem, Optional.<Path>absent());
    Path dir = filesystem.getRootPath().getFileSystem().getPath("dir");
    filesystem.mkdirs(dir);
    Path child1 = dir.resolve("child1");
    filesystem.touch(child1);
    Path child2 = dir.resolve("child2");
    filesystem.touch(child2);
    cache.get(filesystem.resolve(dir));
    assertTrue(cache.willGet(filesystem.resolve(dir)));
    assertTrue(cache.willGet(filesystem.resolve(child1)));
    assertTrue(cache.willGet(filesystem.resolve(child2)));
    cache.invalidate(filesystem.resolve(dir));
    assertNull(cache.loadingCache.getIfPresent(dir));
    assertNull(cache.loadingCache.getIfPresent(child1));
    assertNull(cache.loadingCache.getIfPresent(child2));
}

91. ZipStepTest#shouldCreateANewZipFileFromScratch()

Project: buck
Source File: ZipStepTest.java
View license
@Test
public void shouldCreateANewZipFileFromScratch() throws IOException {
    Path parent = tmp.newFolder("zipstep");
    Path out = parent.resolve("output.zip");
    Path toZip = tmp.newFolder("zipdir");
    Files.createFile(toZip.resolve("file1.txt"));
    Files.createFile(toZip.resolve("file2.txt"));
    Files.createFile(toZip.resolve("file3.txt"));
    ZipStep step = new ZipStep(filesystem, Paths.get("zipstep/output.zip"), ImmutableSet.<Path>of(), false, ZipCompressionLevel.DEFAULT_COMPRESSION_LEVEL, Paths.get("zipdir"));
    assertEquals(0, step.execute(TestExecutionContext.newInstance()).getExitCode());
    try (Zip zip = new Zip(out, false)) {
        assertEquals(ImmutableSet.of("file1.txt", "file2.txt", "file3.txt"), zip.getFileNames());
    }
}

92. ZipStepTest#willOnlyIncludeEntriesInThePathsArgumentIfAnyAreSet()

Project: buck
Source File: ZipStepTest.java
View license
@Test
public void willOnlyIncludeEntriesInThePathsArgumentIfAnyAreSet() throws IOException {
    Path parent = tmp.newFolder("zipstep");
    Path out = parent.resolve("output.zip");
    Path toZip = tmp.newFolder("zipdir");
    Files.createFile(toZip.resolve("file1.txt"));
    Files.createFile(toZip.resolve("file2.txt"));
    Files.createFile(toZip.resolve("file3.txt"));
    ZipStep step = new ZipStep(filesystem, Paths.get("zipstep/output.zip"), ImmutableSet.of(Paths.get("zipdir/file2.txt")), false, ZipCompressionLevel.DEFAULT_COMPRESSION_LEVEL, Paths.get("zipdir"));
    assertEquals(0, step.execute(TestExecutionContext.newInstance()).getExitCode());
    try (Zip zip = new Zip(out, false)) {
        assertEquals(ImmutableSet.of("file2.txt"), zip.getFileNames());
    }
}

93. ZipStepTest#shouldBeAbleToJunkPaths()

Project: buck
Source File: ZipStepTest.java
View license
@Test
public void shouldBeAbleToJunkPaths() throws IOException {
    Path parent = tmp.newFolder("zipstep");
    Path out = parent.resolve("output.zip");
    Path toZip = tmp.newFolder("zipdir");
    Files.createDirectories(toZip.resolve("child"));
    Files.createFile(toZip.resolve("child/file1.txt"));
    ZipStep step = new ZipStep(filesystem, Paths.get("zipstep/output.zip"), ImmutableSet.<Path>of(), true, ZipCompressionLevel.DEFAULT_COMPRESSION_LEVEL, Paths.get("zipdir"));
    assertEquals(0, step.execute(TestExecutionContext.newInstance()).getExitCode());
    try (Zip zip = new Zip(out, false)) {
        assertEquals(ImmutableSet.of("file1.txt"), zip.getFileNames());
    }
}

94. AntUtils#newSystemFileFilter()

Project: che
Source File: AntUtils.java
View license
/**
     * Creates FileFilter that helps filter system.
     * Ant may add two tools.jar in classpath. It uses two JavaHome locations. One from java system property and one from OS environment
     * variable. Ant sources: org.apache.tools.ant.launch.Locator.getToolsJar.
     */
public static FileFilter newSystemFileFilter() {
    final java.io.File antHome = AntUtils.getAntHome();
    final java.io.File javaHome = getJavaHome();
    final java.io.File javaHome2 = getJavaHome2();
    final Path antHomePath = antHome == null ? null : antHome.toPath();
    final Path javaHomePath = javaHome == null ? null : javaHome.toPath();
    final Path javaHomePath2 = javaHome2 == null ? null : javaHome2.toPath();
    return new FileFilter() {

        @Override
        public boolean accept(java.io.File file) {
            final Path path = file.toPath();
            // Skip ant and system jars
            return !(javaHomePath != null && path.startsWith(javaHomePath) || javaHomePath2 != null && path.startsWith(javaHomePath2) || antHomePath != null && path.startsWith(antHomePath));
        }
    };
}

95. FileReadingCollectorTest#setUpClass()

Project: crate
Source File: FileReadingCollectorTest.java
View license
@BeforeClass
public static void setUpClass() throws Exception {
    Path copy_from = Files.createTempDirectory("copy_from");
    Path copy_from_gz = Files.createTempDirectory("copy_from_gz");
    Path copy_from_empty = Files.createTempDirectory("copy_from_empty");
    tmpFileGz = File.createTempFile("fileReadingCollector", ".json.gz", copy_from_gz.toFile());
    tmpFile = File.createTempFile("fileReadingCollector", ".json", copy_from.toFile());
    tmpFileEmptyLine = File.createTempFile("emptyLine", ".json", copy_from_empty.toFile());
    try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(tmpFileGz))))) {
        writer.write("{\"name\": \"Arthur\", \"id\": 4, \"details\": {\"age\": 38}}\n");
        writer.write("{\"id\": 5, \"name\": \"Trillian\", \"details\": {\"age\": 33}}\n");
    }
    try (FileWriter writer = new FileWriter(tmpFile)) {
        writer.write("{\"name\": \"Arthur\", \"id\": 4, \"details\": {\"age\": 38}}\n");
        writer.write("{\"id\": 5, \"name\": \"Trillian\", \"details\": {\"age\": 33}}\n");
    }
    try (FileWriter writer = new FileWriter(tmpFileEmptyLine)) {
        writer.write("{\"name\": \"Arthur\", \"id\": 4, \"details\": {\"age\": 38}}\n");
        writer.write("\n");
        writer.write("{\"id\": 5, \"name\": \"Trillian\", \"details\": {\"age\": 33}}\n");
    }
}

96. TestLiveDirectoryScanner#testRolledFilesOrderReverseNumberInSpoolDir()

View license
@Test
public void testRolledFilesOrderReverseNumberInSpoolDir() throws Exception {
    Path rolledFile1 = new File(testDir, "my.log.12").toPath();
    Path rolledFile2 = new File(testDir, "my.log.2").toPath();
    Files.createFile(rolledFile1);
    Files.createFile(rolledFile2);
    Path liveFile = new File(testDir, "my.log").toPath();
    Files.createFile(liveFile);
    LiveDirectoryScanner spooler = new LiveDirectoryScanner(testDir.getAbsolutePath(), null, LogRollModeFactory.REVERSE_COUNTER.get(liveFile.getFileName().toString(), ""));
    LiveFile lf = spooler.scan(null);
    Assert.assertNotNull(lf);
    Assert.assertEquals(new LiveFile(rolledFile1), lf);
    lf = spooler.scan(lf);
    Assert.assertNotNull(lf);
    Assert.assertEquals(new LiveFile(rolledFile2), lf);
    lf = spooler.scan(lf);
    Assert.assertNotNull(lf);
    Assert.assertEquals(new LiveFile(liveFile), lf);
}

97. TestLiveDirectoryScanner#testRolledFilesOrderAlphabeticalInSpoolDir()

View license
@Test
public void testRolledFilesOrderAlphabeticalInSpoolDir() throws Exception {
    Path rolledFile1 = new File(testDir, "my.log.13").toPath();
    Path rolledFile2 = new File(testDir, "my.log.2").toPath();
    Files.createFile(rolledFile1);
    Files.createFile(rolledFile2);
    Path liveFile = new File(testDir, "my.log").toPath();
    Files.createFile(liveFile);
    LiveDirectoryScanner spooler = new LiveDirectoryScanner(testDir.getAbsolutePath(), null, LogRollModeFactory.ALPHABETICAL.get(liveFile.getFileName().toString(), ""));
    LiveFile lf = spooler.scan(null);
    Assert.assertNotNull(lf);
    Assert.assertEquals(new LiveFile(rolledFile1), lf);
    lf = spooler.scan(lf);
    Assert.assertNotNull(lf);
    Assert.assertEquals(new LiveFile(rolledFile2), lf);
    lf = spooler.scan(lf);
    Assert.assertNotNull(lf);
    Assert.assertEquals(new LiveFile(liveFile), lf);
}

98. TestLiveDirectoryScanner#testUsingFirstFile()

View license
@Test
public void testUsingFirstFile() throws Exception {
    Path rolledFile1 = new File(testDir, "my.log.13").toPath();
    Path rolledFile2 = new File(testDir, "my.log.2").toPath();
    Files.createFile(rolledFile1);
    Files.createFile(rolledFile2);
    Path liveFile = new File(testDir, "my.log").toPath();
    Files.createFile(liveFile);
    LiveDirectoryScanner spooler = new LiveDirectoryScanner(testDir.getAbsolutePath(), rolledFile2.getFileName().toString(), LogRollModeFactory.ALPHABETICAL.get(liveFile.getFileName().toString(), ""));
    LiveFile lf = spooler.scan(null);
    Assert.assertEquals(new LiveFile(rolledFile2), lf);
    lf = spooler.scan(lf);
    Assert.assertNotNull(lf);
    Assert.assertEquals(new LiveFile(liveFile), lf);
}

99. TestUtils#runWorkflow()

Project: digdag
Source File: TestUtils.java
View license
public static void runWorkflow(String resource, ImmutableMap<String, String> params) throws IOException {
    Path workflow = Paths.get(resource);
    Path tempdir = Files.createTempDirectory("digdag-test");
    Path file = tempdir.resolve(workflow.getFileName());
    List<String> runCommand = new ArrayList<>(asList("run", "-c", "/dev/null", "-o", tempdir.toString(), "--project", tempdir.toString(), workflow.getFileName().toString()));
    params.forEach(( k,  v) -> runCommand.addAll(asList("-p", k + "=" + v)));
    try {
        copyResource(resource, file);
        CommandStatus status = main(runCommand);
        assertThat(status.errUtf8(), status.code(), is(0));
    } finally {
        FileUtils.deleteQuietly(tempdir.toFile());
    }
}

100. FileUtils#combinePaths()

Project: Doradus
Source File: FileUtils.java
View license
public static String combinePaths(String baseDir, String relativePath) {
    if (baseDir == null || baseDir.trim().isEmpty())
        return relativePath;
    Path basePath = Paths.get(baseDir);
    Path path = Paths.get(relativePath);
    path = basePath.resolve(path);
    path = path.normalize();
    return path.toString();
}