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. 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));
}

4. 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);
}

5. 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();
}

6. 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");
}

7. 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);
}

8. 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);
}

9. 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);
}

10. 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);
}

11. 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);
    }
}

12. 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);
    }
}

13. 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();
}

14. 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();
}

15. 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();
}

16. 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();
}

17. 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");
}

18. 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");
}

19. 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();
    }
}

20. 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);
}

21. 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"));
}

22. 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;
}

23. 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()));
}

24. 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));
}

25. 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));
}

26. 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()));
}

27. 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()));
}

28. 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()));
}

29. 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));
}

30. 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);
}

31. 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)));
}

32. 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);
}

33. 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);
}

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. 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();
}

36. 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);
}

37. 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");
}

38. 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");
}

39. 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();
}

40. 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");
}

41. 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");
}

42. 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);
}

43. 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");
}

44. 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()));
}

45. 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"));
}

46. 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));
}

47. 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));
}

48. 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));
}

49. 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();
}

50. 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();
}

51. 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);
}

52. 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));
}

53. 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));
}

54. 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));
}

55. 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();
}

56. 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);
    }
}

57. 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);
    }
}

58. 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
}

59. 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
}

60. 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/");
}

61. MultiModuleModeTest#testModuleNameMismatch()

Project: openjdk
Source File: MultiModuleModeTest.java
View license
@Test
public void testModuleNameMismatch(Path base) throws Exception {
    Path src = base.resolve("src");
    Path src_m1 = src.resolve("m1");
    tb.writeJavaFiles(src_m1, "module m2 { }");
    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:8: compiler.err.module.name.mismatch: m2, m1"))
        throw new Exception("expected output not found");
}

62. SuspendablesScannerTest#buildGraph()

Project: quasar
Source File: SuspendablesScannerTest.java
View license
@BeforeClass
public static void buildGraph() throws Exception {
    // find test classes directory
    final String resource = SuspendablesScannerTest.class.getName().replace('.', '/') + ".class";
    final URL url = SuspendablesScannerTest.class.getClassLoader().getResource(resource);
    final Path p1 = Paths.get(resource);
    final Path p2 = Paths.get(url.toURI()).toAbsolutePath();
    final Path p = p2.getRoot().resolve(p2.subpath(0, p2.getNameCount() - p1.getNameCount()));
    System.out.println("Test classes: " + p);
    scanner = new SuspendablesScanner(p);
    //        scanner = new AutoSuspendablesScanner(
    //                Paths.get(AutoSuspendablesScannerTest.class.getClassLoader()
    //                        .getResource(AutoSuspendablesScannerTest.class.getName().replace('.', '/') + ".class").toURI()));
    scanner.setAuto(true);
    scanner.run();
    scanner.putSuspendablesAndSupers(suspendables, suspendableSupers);
    System.out.println("SUSPENDABLES: " + suspendables);
    System.out.println("SUPERS: " + suspendableSupers);
}

63. PackageConflictTest#testDisjoint()

Project: openjdk
Source File: PackageConflictTest.java
View license
@Test
public void testDisjoint(Path base) throws Exception {
    Path m1 = base.resolve("m1");
    Path m2 = base.resolve("m2");
    tb.writeJavaFiles(m1, "module m1 { }", "package test; public class A { }");
    tb.writeJavaFiles(m2, "module m2 { }", "package test; public class B { }");
    Path classes = base.resolve("classes");
    Files.createDirectories(classes);
    new JavacTask(tb).options("-Werror", "-modulesourcepath", base.toString()).outdir(classes).files(findJavaFiles(base)).run().writeAll();
}

64. UpgradeModulePathTest#simpleUsage()

Project: openjdk
Source File: UpgradeModulePathTest.java
View license
@Test
public void simpleUsage(Path base) throws Exception {
    Path modules = base.resolve("modules");
    new ModuleBuilder(tb, "m1").exports("pkg1").classes("package pkg1; public class E { }").build(modules);
    final Path upgradeModules = base.resolve("upgradeModules");
    new ModuleBuilder(tb, "m1").exports("pkg2").classes("package pkg2; public class E { }").build(upgradeModules);
    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("-modulepath", modules.toString(), "-upgrademodulepath", upgradeModules.toString()).files(findJavaFiles(src)).run().writeAll();
}

65. UpgradeModulePathTest#onlyUpgradeModulePath()

Project: openjdk
Source File: UpgradeModulePathTest.java
View license
@Test
public void onlyUpgradeModulePath(Path base) throws Exception {
    final Path module = base.resolve("modules");
    new ModuleBuilder(tb, "m1").exports("pkg1").classes("package pkg1; public class E { }").build(module);
    final Path upgradeModule = base.resolve("upgradeModule");
    new ModuleBuilder(tb, "m1").exports("pkg2").classes("package pkg2; public class E { }").build(upgradeModule);
    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("-upgrademodulepath", upgradeModule + File.pathSeparator + module).files(findJavaFiles(src)).run().writeAll();
}

66. UpgradeModulePathTest#sameUpgradeAndModulePath()

Project: openjdk
Source File: UpgradeModulePathTest.java
View license
@Test
public void sameUpgradeAndModulePath(Path base) throws Exception {
    final Path module = base.resolve("modules");
    new ModuleBuilder(tb, "m1").exports("pkg1").classes("package pkg1; public class E { }").build(module);
    final Path upgradeModule = base.resolve("upgradeModule");
    new ModuleBuilder(tb, "m1").exports("pkg2").classes("package pkg2; public class E { }").build(upgradeModule);
    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("-modulepath", upgradeModule + File.pathSeparator + module, "-upgrademodulepath", upgradeModule.toString()).files(findJavaFiles(src)).run().writeAll();
}

67. HiddenFiles#main()

Project: openjdk
Source File: HiddenFiles.java
View license
public static void main(String[] ignore) throws Exception {
    Path BIN = Paths.get("bin");
    Path STATE_DIR = Paths.get("state-dir");
    Path SRC = Paths.get("src");
    Files.createDirectories(BIN);
    Files.createDirectories(STATE_DIR);
    toolbox.writeJavaFiles(SRC, "package pkg; class A { B b; }");
    toolbox.writeJavaFiles(SRC, "package pkg; class B { }");
    // This compilation should fail (return RC_FATAL) since A.java refers to B.java and B.java
    // is excluded.
    int rc = compile("-x", "pkg/B.java", SRC.toString(), "-d", BIN.toString(), "--state-dir=" + STATE_DIR);
    Assert.check(rc == Result.ERROR.exitCode, "Compilation succeeded unexpectedly.");
}

68. PackagePathMismatch#main()

Project: openjdk
Source File: PackagePathMismatch.java
View license
public static void main(String... args) throws Exception {
    Path root = Paths.get(PackagePathMismatch.class.getSimpleName() + "Test");
    Path src = root.resolve("src");
    Path classes = root.resolve("classes");
    toolbox.writeFile(src.resolve("a/x/c/Test.java"), "package a.b.c; class Test { }");
    // Compile should fail since package a.b.c does not match path a/x/c.
    int rc1 = compile("-d", classes, "--state-dir=" + classes, src);
    if (rc1 == 0)
        throw new AssertionError("Compilation succeeded unexpectedly");
}

69. MockFileSystemTestCase#implTestURI()

View license
private void implTestURI(String fileName) throws IOException {
    assumeFalse("broken on J9: see https://issues.apache.org/jira/browse/LUCENE-6517", Constants.JAVA_VENDOR.startsWith("IBM"));
    Path dir = wrap(createTempDir());
    try {
        dir.resolve(fileName);
    } catch (InvalidPathException ipe) {
        assumeNoException("couldn't resolve '" + fileName + "'", ipe);
    }
    Path f1 = dir.resolve(fileName);
    URI uri = f1.toUri();
    Path f2 = dir.getFileSystem().provider().getPath(uri);
    assertEquals(f1, f2);
    dir.getFileSystem().close();
}

70. SolrCLIZkUtilsTest#testDownconfig()

Project: lucene-solr
Source File: SolrCLIZkUtilsTest.java
View license
@Test
public void testDownconfig() throws Exception {
    Path tmp = createTempDir("downConfigNewPlace");
    // First we need a configset on ZK to bring down. 
    Path configSet = TEST_PATH().resolve("configsets");
    Path srcPathCheck = configSet.resolve("cloud-subdirs").resolve("conf");
    copyConfigUp(configSet, "cloud-subdirs", "downconfig1");
    // Now do we have that config up on ZK?
    verifyZkLocalPathsMatch(srcPathCheck, "/configs/downconfig1");
    String[] args = new String[] { "-confname", "downconfig1", "-confdir", tmp.toAbsolutePath().toString(), "-zkHost", zkAddr };
    SolrCLI.ConfigSetDownloadTool downTool = new SolrCLI.ConfigSetDownloadTool();
    int res = downTool.runTool(SolrCLI.processCommandLineArgs(SolrCLI.joinCommonAndToolOptions(downTool.getOptions()), args));
    assertEquals("Download should have succeeded.", 0, res);
    verifyZkLocalPathsMatch(Paths.get(tmp.toAbsolutePath().toString(), "conf"), "/configs/downconfig1");
}

71. SingularityExecutorTaskLogManager#writeS3MetadataFileForRotatedFiles()

View license
@SuppressFBWarnings
private boolean writeS3MetadataFileForRotatedFiles(boolean finished) {
    final Path serviceLogOutPath = taskDefinition.getServiceLogOutPath();
    final Path serviceLogParent = serviceLogOutPath.getParent();
    final Path logrotateDirectory = serviceLogParent.resolve(configuration.getLogrotateToDirectory());
    boolean result = writeS3MetadataFile("default", logrotateDirectory, String.format("%s*.gz*", taskDefinition.getServiceLogOutPath().getFileName()), Optional.<String>absent(), Optional.<String>absent(), finished);
    int index = 1;
    for (SingularityExecutorS3UploaderAdditionalFile additionalFile : configuration.getS3UploaderAdditionalFiles()) {
        result = result && writeS3MetadataFile(additionalFile.getS3UploaderFilenameHint().or(String.format("extra%d", index)), logrotateDirectory, String.format("%s*.gz*", additionalFile.getFilename()), additionalFile.getS3UploaderBucket(), additionalFile.getS3UploaderKeyPattern(), finished);
        index++;
    }
    return result;
}

72. SingularityExecutorCleanup#getUncompressedLogrotatedFileIterator()

View license
private Iterator<Path> getUncompressedLogrotatedFileIterator(SingularityExecutorTaskDefinition taskDefinition) {
    final Path serviceLogOutPath = taskDefinition.getServiceLogOutPath();
    final Path parent = serviceLogOutPath.getParent();
    if (parent == null) {
        throw new IllegalStateException("Service log path " + serviceLogOutPath + " has no parent");
    }
    final Path logrotateToPath = parent.resolve(executorConfiguration.getLogrotateToDirectory());
    if (!logrotateToPath.toFile().exists() || !logrotateToPath.toFile().isDirectory()) {
        LOG.warn("Skipping uncompressed logrotated file cleanup for {} -- {} does not exist or is not a directory (task sandbox was probably garbage collected by Mesos)", taskDefinition.getTaskId(), logrotateToPath);
        return Collections.emptyIterator();
    }
    try {
        DirectoryStream<Path> dirStream = Files.newDirectoryStream(logrotateToPath, String.format("%s-*", serviceLogOutPath.getFileName()));
        return dirStream.iterator();
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}

73. FileUtilsTest#deleteQuietly_deletes_symbolicLink()

Project: sonarqube
Source File: FileUtilsTest.java
View license
@Test
public void deleteQuietly_deletes_symbolicLink() throws IOException {
    Path folder = temporaryFolder.newFolder().toPath();
    Path file1 = Files.createFile(folder.resolve("file1.txt"));
    Path symLink = Files.createSymbolicLink(folder.resolve("link1"), file1);
    assertThat(file1).isRegularFile();
    assertThat(symLink).isSymbolicLink();
    FileUtils.deleteQuietly(symLink.toFile());
    assertThat(symLink).doesNotExist();
    assertThat(file1).isRegularFile();
}

74. FileUtilsTest#deleteDirectory_throws_IOE_if_file_is_symbolicLink()

Project: sonarqube
Source File: FileUtilsTest.java
View license
@Test
public void deleteDirectory_throws_IOE_if_file_is_symbolicLink() throws IOException {
    Path folder = temporaryFolder.newFolder().toPath();
    Path file1 = Files.createFile(folder.resolve("file1.txt"));
    Path symLink = Files.createSymbolicLink(folder.resolve("link1"), file1);
    assertThat(file1).isRegularFile();
    assertThat(symLink).isSymbolicLink();
    expectedException.expect(IOException.class);
    expectedException.expectMessage("Directory '" + symLink.toFile().getAbsolutePath() + "' is a symbolic link");
    FileUtils.deleteDirectory(symLink.toFile());
}

75. FileUtilsTest#deleteQuietly_deletes_symbolicLink()

Project: sonarqube
Source File: FileUtilsTest.java
View license
@Test
public void deleteQuietly_deletes_symbolicLink() throws IOException {
    Path folder = temporaryFolder.newFolder().toPath();
    Path file1 = Files.createFile(folder.resolve("file1.txt"));
    Path symLink = Files.createSymbolicLink(folder.resolve("link1"), file1);
    assertThat(file1).isRegularFile();
    assertThat(symLink).isSymbolicLink();
    FileUtils.deleteQuietly(symLink.toFile());
    assertThat(symLink).doesNotExist();
    assertThat(file1).isRegularFile();
}

76. FileUtilsTest#deleteDirectory_throws_IOE_if_file_is_symbolicLink()

Project: sonarqube
Source File: FileUtilsTest.java
View license
@Test
public void deleteDirectory_throws_IOE_if_file_is_symbolicLink() throws IOException {
    Path folder = temporaryFolder.newFolder().toPath();
    Path file1 = Files.createFile(folder.resolve("file1.txt"));
    Path symLink = Files.createSymbolicLink(folder.resolve("link1"), file1);
    assertThat(file1).isRegularFile();
    assertThat(symLink).isSymbolicLink();
    expectedException.expect(IOException.class);
    expectedException.expectMessage("Directory '" + symLink.toFile().getAbsolutePath() + "' is a symbolic link");
    FileUtils.deleteDirectory(symLink.toFile());
}

77. AsciidocConverterTest#testSwagger2AsciiDocConversion()

View license
@Test
public void testSwagger2AsciiDocConversion() throws IOException, URISyntaxException {
    //Given
    Path file = Paths.get(AsciidocConverterTest.class.getResource("/yaml/swagger_petstore.yaml").toURI());
    Path outputDirectory = Paths.get("build/test/asciidoc/default");
    FileUtils.deleteQuietly(outputDirectory.toFile());
    //When
    Swagger2MarkupConverter.from(file).build().toFolder(outputDirectory);
    //Then
    String[] files = outputDirectory.toFile().list();
    assertThat(files).hasSize(4).containsAll(expectedFiles);
    Path expectedFilesDirectory = Paths.get(AsciidocConverterTest.class.getResource("/expected/asciidoc/default").toURI());
    DiffUtils.assertThatAllFilesAreEqual(expectedFilesDirectory, outputDirectory, "testSwagger2AsciiDocConversion.html");
}

78. AsciidocConverterTest#testSwagger2AsciiDocConversionInstagram()

View license
@Test
public void testSwagger2AsciiDocConversionInstagram() throws IOException, URISyntaxException {
    //Given
    Path file = Paths.get(AsciidocConverterTest.class.getResource("/yaml/swagger_instagram.yaml").toURI());
    Path outputDirectory = Paths.get("build/test/asciidoc/instagram");
    FileUtils.deleteQuietly(outputDirectory.toFile());
    //When
    Swagger2MarkupConverter.from(file).build().toFolder(outputDirectory);
    //Then
    String[] files = outputDirectory.toFile().list();
    assertThat(files).hasSize(4).containsAll(expectedFiles);
    Path expectedFilesDirectory = Paths.get(AsciidocConverterTest.class.getResource("/expected/asciidoc/instagram").toURI());
    DiffUtils.assertThatAllFilesAreEqual(expectedFilesDirectory, outputDirectory, "testSwagger2AsciiDocConversionInstagram.html");
}

79. AsciidocConverterTest#testSwagger2AsciiDocConversionWithInterDocumentCrossReferences()

View license
@Test
public void testSwagger2AsciiDocConversionWithInterDocumentCrossReferences() throws IOException, URISyntaxException {
    //Given
    Path file = Paths.get(AsciidocConverterTest.class.getResource("/yaml/swagger_petstore.yaml").toURI());
    Path outputDirectory = Paths.get("build/test/asciidoc/idxref");
    FileUtils.deleteQuietly(outputDirectory.toFile());
    //When
    Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder().withInterDocumentCrossReferences().build();
    Swagger2MarkupConverter.from(file).withConfig(config).build().toFolder(outputDirectory);
    //Then
    String[] files = outputDirectory.toFile().list();
    assertThat(files).hasSize(4).containsAll(expectedFiles);
    Path expectedFilesDirectory = Paths.get(AsciidocConverterTest.class.getResource("/expected/asciidoc/idxref").toURI());
    DiffUtils.assertThatAllFilesAreEqual(expectedFilesDirectory, outputDirectory, "testSwagger2AsciiDocConversionWithInterDocumentCrossReferences.html");
}

80. AsciidocConverterTest#testSwagger2AsciiDocWithInlineSchema()

View license
@Test
public void testSwagger2AsciiDocWithInlineSchema() throws IOException, URISyntaxException {
    //Given
    Path file = Paths.get(AsciidocConverterTest.class.getResource("/yaml/swagger_inlineSchema.yaml").toURI());
    Path outputDirectory = Paths.get("build/test/asciidoc/inline_schema");
    FileUtils.deleteQuietly(outputDirectory.toFile());
    //When
    Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder().build();
    Swagger2MarkupConverter.from(file).withConfig(config).build().toFolder(outputDirectory);
    //Then
    String[] files = outputDirectory.toFile().list();
    assertThat(files).hasSize(4).containsAll(expectedFiles);
    Path expectedFilesDirectory = Paths.get(AsciidocConverterTest.class.getResource("/expected/asciidoc/inline_schema").toURI());
    DiffUtils.assertThatAllFilesAreEqual(expectedFilesDirectory, outputDirectory, "testSwagger2AsciiDocWithInlineSchema.html");
}

81. AsciidocConverterTest#testSwagger2AsciiDocWithInlineSchemaAndFlatBody()

View license
@Test
public void testSwagger2AsciiDocWithInlineSchemaAndFlatBody() throws IOException, URISyntaxException {
    //Given
    Path file = Paths.get(AsciidocConverterTest.class.getResource("/yaml/swagger_inlineSchema.yaml").toURI());
    Path outputDirectory = Paths.get("build/test/asciidoc/inline_schema_flat_body");
    FileUtils.deleteQuietly(outputDirectory.toFile());
    //When
    Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder().withFlatBody().build();
    Swagger2MarkupConverter.from(file).withConfig(config).build().toFolder(outputDirectory);
    //Then
    String[] files = outputDirectory.toFile().list();
    assertThat(files).hasSize(4).containsAll(expectedFiles);
    Path expectedFilesDirectory = Paths.get(AsciidocConverterTest.class.getResource("/expected/asciidoc/inline_schema_flat_body").toURI());
    DiffUtils.assertThatAllFilesAreEqual(expectedFilesDirectory, outputDirectory, "testSwagger2AsciiDocWithInlineSchemaAndFlatBody.html");
}

82. AsciidocConverterTest#testSwagger2AsciiDocGroupedByTags()

View license
@Test
public void testSwagger2AsciiDocGroupedByTags() throws IOException, URISyntaxException {
    //Given
    Path file = Paths.get(AsciidocConverterTest.class.getResource("/yaml/swagger_petstore.yaml").toURI());
    Path outputDirectory = Paths.get("build/test/asciidoc/group_by_tags");
    FileUtils.deleteQuietly(outputDirectory.toFile());
    //When
    Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder().withPathsGroupedBy(GroupBy.TAGS).build();
    Swagger2MarkupConverter.from(file).withConfig(config).build().toFolder(outputDirectory);
    //Then
    String[] files = outputDirectory.toFile().list();
    assertThat(files).hasSize(4).containsAll(expectedFiles);
    Path expectedFilesDirectory = Paths.get(AsciidocConverterTest.class.getResource("/expected/asciidoc/group_by_tags").toURI());
    DiffUtils.assertThatAllFilesAreEqual(expectedFilesDirectory, outputDirectory, "testSwagger2AsciiDocGroupedByTags.html");
}

83. AsciidocConverterTest#testSwagger2AsciiDocConversionWithSeparatedDefinitions()

View license
@Test
public void testSwagger2AsciiDocConversionWithSeparatedDefinitions() throws IOException, URISyntaxException {
    //Given
    Path file = Paths.get(AsciidocConverterTest.class.getResource("/yaml/swagger_petstore.yaml").toURI());
    Path outputDirectory = Paths.get("build/test/asciidoc/generated");
    FileUtils.deleteQuietly(outputDirectory.toFile());
    //When
    Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder().withSeparatedDefinitions().build();
    Swagger2MarkupConverter.from(file).withConfig(config).build().toFolder(outputDirectory);
    //Then
    String[] files = outputDirectory.toFile().list();
    expectedFiles.add("definitions");
    assertThat(files).hasSize(5).containsAll(expectedFiles);
    Path definitionsDirectory = outputDirectory.resolve("definitions");
    String[] definitions = definitionsDirectory.toFile().list();
    assertThat(definitions).hasSize(5).containsAll(asList("Category.adoc", "Order.adoc", "Pet.adoc", "Tag.adoc", "User.adoc"));
}

84. AsciidocConverterTest#testSwagger2AsciiDocConversionWithSeparatedOperations()

View license
@Test
public void testSwagger2AsciiDocConversionWithSeparatedOperations() throws IOException, URISyntaxException {
    //Given
    Path file = Paths.get(AsciidocConverterTest.class.getResource("/yaml/swagger_petstore.yaml").toURI());
    Path outputDirectory = Paths.get("build/test/asciidoc/generated");
    FileUtils.deleteQuietly(outputDirectory.toFile());
    //When
    Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder().withSeparatedOperations().build();
    Swagger2MarkupConverter.from(file).withConfig(config).build().toFolder(outputDirectory);
    //Then
    String[] files = outputDirectory.toFile().list();
    expectedFiles.add("operations");
    assertThat(files).hasSize(5).containsAll(expectedFiles);
    Path pathsDirectory = outputDirectory.resolve("operations");
    String[] paths = pathsDirectory.toFile().list();
    assertThat(paths).hasSize(18);
}

85. AsciidocConverterTest#testSwagger2AsciiDocConversionWithMaps()

View license
@Test
public void testSwagger2AsciiDocConversionWithMaps() throws IOException, URISyntaxException {
    //Given
    Path file = Paths.get(AsciidocConverterTest.class.getResource("/json/swagger_maps.json").toURI());
    Path outputDirectory = Paths.get("build/test/asciidoc/maps");
    FileUtils.deleteQuietly(outputDirectory.toFile());
    //When
    Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder().build();
    Swagger2MarkupConverter.from(file).withConfig(config).build().toFolder(outputDirectory);
    //Then
    String[] files = outputDirectory.toFile().list();
    assertThat(files).hasSize(4).containsAll(expectedFiles);
    Path expectedFilesDirectory = Paths.get(AsciidocConverterTest.class.getResource("/expected/asciidoc/maps").toURI());
    DiffUtils.assertThatAllFilesAreEqual(expectedFilesDirectory, outputDirectory, "testSwagger2AsciiDocConversionWithMaps.html");
}

86. AsciidocConverterTest#testSwagger2AsciiDocConversionWithEnums()

View license
@Test
public void testSwagger2AsciiDocConversionWithEnums() throws IOException, URISyntaxException {
    //Given
    Path file = Paths.get(AsciidocConverterTest.class.getResource("/json/swagger_enums.json").toURI());
    Path outputDirectory = Paths.get("build/test/asciidoc/enums");
    FileUtils.deleteQuietly(outputDirectory.toFile());
    //When
    Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder().build();
    Swagger2MarkupConverter.from(file).withConfig(config).build().toFolder(outputDirectory);
    //Then
    String[] files = outputDirectory.toFile().list();
    assertThat(files).hasSize(4).containsAll(expectedFiles);
    Path expectedFilesDirectory = Paths.get(AsciidocConverterTest.class.getResource("/expected/asciidoc/enums").toURI());
    DiffUtils.assertThatAllFilesAreEqual(expectedFilesDirectory, outputDirectory, "testSwagger2AsciiDocConversionWithEnums.html");
}

87. AsciidocConverterTest#testSwagger2AsciiDocConversionWithValidators()

View license
@Test
public void testSwagger2AsciiDocConversionWithValidators() throws IOException, URISyntaxException {
    //Given
    Path file = Paths.get(AsciidocConverterTest.class.getResource("/json/swagger_validators.json").toURI());
    Path outputDirectory = Paths.get("build/test/asciidoc/validators");
    FileUtils.deleteQuietly(outputDirectory.toFile());
    //When
    Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder().build();
    Swagger2MarkupConverter.from(file).withConfig(config).build().toFolder(outputDirectory);
    //Then
    String[] files = outputDirectory.toFile().list();
    assertThat(files).hasSize(4).containsAll(expectedFiles);
    Path expectedFilesDirectory = Paths.get(AsciidocConverterTest.class.getResource("/expected/asciidoc/validators").toURI());
    DiffUtils.assertThatAllFilesAreEqual(expectedFilesDirectory, outputDirectory, "testSwagger2AsciiDocConversionWithValidators.html");
}

88. AsciidocConverterTest#testSwagger2AsciiDocConversionWithPolymorphism()

View license
@Test
public void testSwagger2AsciiDocConversionWithPolymorphism() throws IOException, URISyntaxException {
    //Given
    Path file = Paths.get(AsciidocConverterTest.class.getResource("/json/swagger_polymorphism.json").toURI());
    Path outputDirectory = Paths.get("build/test/asciidoc/polymorphism");
    FileUtils.deleteQuietly(outputDirectory.toFile());
    //When
    Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder().build();
    Swagger2MarkupConverter.from(file).withConfig(config).build().toFolder(outputDirectory);
    //Then
    String[] files = outputDirectory.toFile().list();
    assertThat(files).hasSize(4).containsAll(expectedFiles);
    Path expectedFilesDirectory = Paths.get(AsciidocConverterTest.class.getResource("/expected/asciidoc/polymorphism").toURI());
    DiffUtils.assertThatAllFilesAreEqual(expectedFilesDirectory, outputDirectory, "testSwagger2AsciiDocConversionWithPolymorphism.html");
}

89. AsciidocConverterTest#testSwagger2AsciiDocConversionWithPolymorphismAsIsOrdering()

View license
@Test
public void testSwagger2AsciiDocConversionWithPolymorphismAsIsOrdering() throws IOException, URISyntaxException {
    //Given
    Path file = Paths.get(AsciidocConverterTest.class.getResource("/json/swagger_polymorphism.json").toURI());
    Path outputDirectory = Paths.get("build/test/asciidoc/polymorphismAsIsOrdering");
    FileUtils.deleteQuietly(outputDirectory.toFile());
    //When
    Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder().withPropertyOrdering(OrderBy.AS_IS).build();
    Swagger2MarkupConverter.from(file).withConfig(config).build().toFolder(outputDirectory);
    //Then
    String[] files = outputDirectory.toFile().list();
    assertThat(files).hasSize(4).containsAll(expectedFiles);
    Path expectedFilesDirectory = Paths.get(AsciidocConverterTest.class.getResource("/expected/asciidoc/polymorphismAsIsOrdering").toURI());
    DiffUtils.assertThatAllFilesAreEqual(expectedFilesDirectory, outputDirectory, "testSwagger2AsciiDocConversionWithPolymorphismAsIsOrdering.html");
}

90. AsciidocConverterTest#testSwagger2AsciiDocConversionWithResponseHeaders()

View license
@Test
public void testSwagger2AsciiDocConversionWithResponseHeaders() throws IOException, URISyntaxException {
    //Given
    Path file = Paths.get(AsciidocConverterTest.class.getResource("/yaml/swagger_response_headers.yaml").toURI());
    Path outputDirectory = Paths.get("build/test/asciidoc/response_headers");
    FileUtils.deleteQuietly(outputDirectory.toFile());
    //When
    Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder().build();
    Swagger2MarkupConverter.from(file).withConfig(config).build().toFolder(outputDirectory);
    //Then
    String[] files = outputDirectory.toFile().list();
    assertThat(files).hasSize(4).containsAll(expectedFiles);
    Path expectedFilesDirectory = Paths.get(AsciidocConverterTest.class.getResource("/expected/asciidoc/response_headers").toURI());
    DiffUtils.assertThatAllFilesAreEqual(expectedFilesDirectory, outputDirectory, "testSwagger2AsciiDocConversionWithResponseHeaders.html");
}

91. MarkdownConverterTest#testSwagger2MarkdownConversion()

View license
@Test
public void testSwagger2MarkdownConversion() throws IOException, URISyntaxException {
    //Given
    Path file = Paths.get(MarkdownConverterTest.class.getResource("/yaml/swagger_petstore.yaml").toURI());
    Path outputDirectory = Paths.get("build/test/markdown/default");
    FileUtils.deleteQuietly(outputDirectory.toFile());
    //When
    Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder().withMarkupLanguage(MarkupLanguage.MARKDOWN).build();
    Swagger2MarkupConverter.from(file).withConfig(config).build().toFolder(outputDirectory);
    //Then
    String[] files = outputDirectory.toFile().list();
    assertThat(files).hasSize(4).containsAll(expectedFiles);
    Path expectedFilesDirectory = Paths.get(AsciidocConverterTest.class.getResource("/expected/markdown/default").toURI());
    DiffUtils.assertThatAllFilesAreEqual(expectedFilesDirectory, outputDirectory, "testSwagger2MarkdownConversion.html");
}

92. MarkdownConverterTest#testSwagger2MarkdownConversionWithInterDocumentCrossReferences()

View license
@Test
public void testSwagger2MarkdownConversionWithInterDocumentCrossReferences() throws IOException, URISyntaxException {
    //Given
    Path file = Paths.get(AsciidocConverterTest.class.getResource("/yaml/swagger_petstore.yaml").toURI());
    Path outputDirectory = Paths.get("build/test/markdown/idxref");
    FileUtils.deleteQuietly(outputDirectory.toFile());
    //When
    Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder().withMarkupLanguage(MarkupLanguage.MARKDOWN).withInterDocumentCrossReferences().build();
    Swagger2MarkupConverter.from(file).withConfig(config).build().toFolder(outputDirectory);
    //Then
    String[] files = outputDirectory.toFile().list();
    assertThat(files).hasSize(4).containsAll(expectedFiles);
    Path expectedFilesDirectory = Paths.get(AsciidocConverterTest.class.getResource("/expected/markdown/idxref").toURI());
    DiffUtils.assertThatAllFilesAreEqual(expectedFilesDirectory, outputDirectory, "testSwagger2MarkdownConversionWithInterDocumentCrossReferences.html");
}

93. DiagnosticTest#oneFileParseErrorReplace()

View license
@Test
public void oneFileParseErrorReplace() throws Exception {
    String one = "class One {}}\n";
    String two = "class Two {\n}\n";
    StringWriter stdout = new StringWriter();
    StringWriter stderr = new StringWriter();
    Main main = new Main(new PrintWriter(stdout, true), new PrintWriter(stderr, true), System.in);
    Path tmpdir = testFolder.newFolder().toPath();
    Path pathOne = tmpdir.resolve("One.java");
    Files.write(pathOne, one.getBytes(UTF_8));
    Path pathTwo = tmpdir.resolve("Two.java");
    Files.write(pathTwo, two.getBytes(UTF_8));
    int result = main.format("-i", pathOne.toString(), pathTwo.toString());
    assertThat(stdout.toString()).isEmpty();
    assertThat(stderr.toString()).contains("One.java:1:13: error: Syntax error on token \"}\"");
    assertThat(result).isEqualTo(1);
    // don't edit files with parse errors
    assertThat(Files.readAllLines(pathOne, UTF_8)).containsExactly("class One {}}");
    assertThat(Files.readAllLines(pathTwo, UTF_8)).containsExactly("class Two {}");
}

94. EvilSecurityTests#testSymlinkPermissions()

View license
/** When a configured dir is a symlink, test that permissions work on link target */
public void testSymlinkPermissions() throws IOException {
    // see https://github.com/elastic/elasticsearch/issues/12170
    assumeFalse("windows does not automatically grant permission to the target of symlinks", Constants.WINDOWS);
    Path dir = createTempDir();
    Path target = dir.resolve("target");
    Files.createDirectory(target);
    // symlink
    Path link = dir.resolve("link");
    try {
        Files.createSymbolicLink(link, target);
    } catch (UnsupportedOperationExceptionIOException |  e) {
        assumeNoException("test requires filesystem that supports symbolic links", e);
    } catch (SecurityException e) {
        assumeNoException("test cannot create symbolic links with security manager enabled", e);
    }
    Permissions permissions = new Permissions();
    Security.addPath(permissions, "testing", link, "read");
    assertExactPermissions(new FilePermission(link.toString(), "read"), permissions);
    assertExactPermissions(new FilePermission(link.resolve("foo").toString(), "read"), permissions);
    assertExactPermissions(new FilePermission(target.toString(), "read"), permissions);
    assertExactPermissions(new FilePermission(target.resolve("foo").toString(), "read"), permissions);
}

95. EvilSecurityTests#testEnsureSymlink()

View license
public void testEnsureSymlink() throws IOException {
    Path p = createTempDir();
    Path exists = p.resolve("exists");
    Files.createDirectory(exists);
    // symlink
    Path linkExists = p.resolve("linkExists");
    try {
        Files.createSymbolicLink(linkExists, exists);
    } catch (UnsupportedOperationExceptionIOException |  e) {
        assumeNoException("test requires filesystem that supports symbolic links", e);
    } catch (SecurityException e) {
        assumeNoException("test cannot create symbolic links with security manager enabled", e);
    }
    Security.ensureDirectoryExists(linkExists);
    Files.createTempFile(linkExists, null, null);
}

96. FileScriptTests#makeScriptService()

Project: elasticsearch
Source File: FileScriptTests.java
View license
ScriptService makeScriptService(Settings settings) throws Exception {
    Path homeDir = createTempDir();
    Path scriptsDir = homeDir.resolve("config").resolve("scripts");
    Files.createDirectories(scriptsDir);
    Path mockscript = scriptsDir.resolve("script1.mockscript");
    Files.write(mockscript, "1".getBytes("UTF-8"));
    settings = Settings.builder().put(Environment.PATH_HOME_SETTING.getKey(), homeDir).put(// no file watching, so we don't need a ResourceWatcherService
    ScriptService.SCRIPT_AUTO_RELOAD_ENABLED_SETTING.getKey(), false).put(settings).build();
    ScriptEngineRegistry scriptEngineRegistry = new ScriptEngineRegistry(Collections.singleton(new MockScriptEngine()));
    ScriptContextRegistry scriptContextRegistry = new ScriptContextRegistry(Collections.emptyList());
    ScriptSettings scriptSettings = new ScriptSettings(scriptEngineRegistry, scriptContextRegistry);
    return new ScriptService(settings, new Environment(settings), null, scriptEngineRegistry, scriptContextRegistry, scriptSettings);
}

97. CloudStorageFileSystemProviderTest#testCopy_overwriteAttributes()

View license
@Test
public void testCopy_overwriteAttributes() throws IOException {
    Path source = Paths.get(URI.create("gs://military/fashion.show"));
    Path target1 = Paths.get(URI.create("gs://greenbean/adipose"));
    Path target2 = Paths.get(URI.create("gs://greenbean/round"));
    Files.write(source, "(?? ?? )?".getBytes(UTF_8), CloudStorageOptions.withMimeType("text/lolcat"), CloudStorageOptions.withCacheControl("public; max-age=666"));
    Files.copy(source, target1, COPY_ATTRIBUTES);
    Files.copy(source, target2, COPY_ATTRIBUTES, CloudStorageOptions.withMimeType("text/palfun"));
    CloudStorageFileAttributes attributes = Files.readAttributes(target1, CloudStorageFileAttributes.class);
    assertThat(attributes.mimeType()).hasValue("text/lolcat");
    assertThat(attributes.cacheControl()).hasValue("public; max-age=666");
    attributes = Files.readAttributes(target2, CloudStorageFileAttributes.class);
    assertThat(attributes.mimeType()).hasValue("text/palfun");
    assertThat(attributes.cacheControl()).hasValue("public; max-age=666");
}

98. ClasspathEntriesParserTests#toURLsWithMultiplePathsInSingleEntry()

View license
@Test
public void toURLsWithMultiplePathsInSingleEntry() throws Exception {
    Path root = getFileSystemRoot();
    Path path1 = root.resolve("foo");
    Path path2 = root.resolve("bar");
    URL[] urls = new ClasspathEntriesParser().toURLs(singletonList(join(File.pathSeparator, path1.toString(), path2.toString())));
    assertEquals(2, urls.length);
    assertEquals(path1.toUri().toURL(), urls[0]);
    assertEquals(path2.toUri().toURL(), urls[1]);
}

99. InstallPluginCommandTests#testExistingConfig()

View license
public void testExistingConfig() throws Exception {
    Tuple<Path, Environment> env = createEnv(fs, temp);
    Path envConfigDir = env.v2().configFile().resolve("fake");
    Files.createDirectories(envConfigDir);
    Files.write(envConfigDir.resolve("custom.yaml"), "existing config".getBytes(StandardCharsets.UTF_8));
    Path pluginDir = createPluginDir(temp);
    Path configDir = pluginDir.resolve("config");
    Files.createDirectory(configDir);
    Files.write(configDir.resolve("custom.yaml"), "new config".getBytes(StandardCharsets.UTF_8));
    Files.createFile(configDir.resolve("other.yaml"));
    String pluginZip = createPlugin("fake", pluginDir);
    installPlugin(pluginZip, env.v1());
    assertPlugin("fake", pluginDir, env.v2());
    List<String> configLines = Files.readAllLines(envConfigDir.resolve("custom.yaml"), StandardCharsets.UTF_8);
    assertEquals(1, configLines.size());
    assertEquals("existing config", configLines.get(0));
    assertTrue(Files.exists(envConfigDir.resolve("other.yaml")));
}

100. DiagnosticTest#oneFileParseError()

View license
@Test
public void oneFileParseError() throws Exception {
    String one = "class One {\n";
    String two = "class Two {}\n";
    StringWriter stdout = new StringWriter();
    StringWriter stderr = new StringWriter();
    Main main = new Main(new PrintWriter(stdout, true), new PrintWriter(stderr, true), System.in);
    Path tmpdir = testFolder.newFolder().toPath();
    Path pathOne = tmpdir.resolve("One.java");
    Files.write(pathOne, one.getBytes(UTF_8));
    Path pathTwo = tmpdir.resolve("Two.java");
    Files.write(pathTwo, two.getBytes(UTF_8));
    int result = main.format(pathOne.toString(), pathTwo.toString());
    assertThat(stdout.toString()).isEqualTo(two);
    assertThat(stderr.toString()).contains("One.java:1:11: error: Syntax error, insert \"}\"");
    assertThat(result).isEqualTo(1);
}