Here are the examples of the java api class java.nio.file.Path taken from open source projects.
1. NodeEnvironmentEvilTests#testMissingWritePermissionOnShard()
Project: elasticsearch
File: NodeEnvironmentEvilTests.java
File: NodeEnvironmentEvilTests.java
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()
Project: undertow
File: FileHandlerSymlinksTestCase.java
File: FileHandlerSymlinksTestCase.java
@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
File: AppleBundle.java
File: AppleBundle.java
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()
Project: undertow
File: FileHandlerSymlinksTestCase.java
File: FileHandlerSymlinksTestCase.java
@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. MoreFilesTest#testSortFilesByAccessTime()
Project: buck
File: MoreFilesTest.java
File: MoreFilesTest.java
@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)); }
6. ExecutableFinderTest#testSearchPathsSymlinkToExecutableOutsideSearchPathReturnsPath()
Project: buck
File: ExecutableFinderTest.java
File: ExecutableFinderTest.java
@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())); }
7. HgCmdLineInterfaceIntegrationTest#explodeReposZip()
Project: buck
File: HgCmdLineInterfaceIntegrationTest.java
File: HgCmdLineInterfaceIntegrationTest.java
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; }
8. ProjectWorkspaceTest#testCopyRecursively()
Project: buck
File: ProjectWorkspaceTest.java
File: ProjectWorkspaceTest.java
@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. FilesystemBackedBuildFileTreeTest#respectsIgnorePaths()
Project: buck
File: FilesystemBackedBuildFileTreeTest.java
File: FilesystemBackedBuildFileTreeTest.java
@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); }
10. JimfsUnixLikeFileSystemTest#testDelete_pathPermutations()
Project: jimfs
File: JimfsUnixLikeFileSystemTest.java
File: JimfsUnixLikeFileSystemTest.java
@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. ModuleInfoTest#testRequiresPublicLoop()
Project: openjdk
File: ModuleInfoTest.java
File: ModuleInfoTest.java
/** * 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"); }
12. ModuleInfoTest#testRequiresLoop()
Project: openjdk
File: ModuleInfoTest.java
File: ModuleInfoTest.java
/** * 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"); }
13. FileUtilsTest#deleteDirectory_deletes_directory_and_content()
Project: sonarqube
File: FileUtilsTest.java
File: FileUtilsTest.java
@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(); }
14. FileUtilsTest#deleteQuietly_deletes_directory_and_content()
Project: sonarqube
File: FileUtilsTest.java
File: FileUtilsTest.java
@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(); }
15. FileUtilsTest#deleteDirectory_deletes_directory_and_content()
Project: sonarqube
File: FileUtilsTest.java
File: FileUtilsTest.java
@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(); }
16. FileUtilsTest#deleteQuietly_deletes_directory_and_content()
Project: sonarqube
File: FileUtilsTest.java
File: FileUtilsTest.java
@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(); }
17. JLinkNegativeTest#testDuplicateModule2()
Project: openjdk
File: JLinkNegativeTest.java
File: JLinkNegativeTest.java
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. ContentHandlersTest#step1_ContentHandlerFactory()
Project: openjdk
File: ContentHandlersTest.java
File: ContentHandlersTest.java
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); } }
19. AccessSystemLogger#main()
Project: openjdk
File: AccessSystemLogger.java
File: AccessSystemLogger.java
// 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); }
20. AccessSystemLogger#main()
Project: openjdk
File: AccessSystemLogger.java
File: AccessSystemLogger.java
// 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); }
21. AccessSystemLogger#main()
Project: openjdk
File: AccessSystemLogger.java
File: AccessSystemLogger.java
// 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); }
22. AccessSystemLogger#main()
Project: openjdk
File: AccessSystemLogger.java
File: AccessSystemLogger.java
// 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); }
23. ModuleFinderTest#testOfManyJarFiles()
Project: openjdk
File: ModuleFinderTest.java
File: ModuleFinderTest.java
/** * 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"); }
24. XModuleTest#testWithUpgradeModulePath()
Project: openjdk
File: XModuleTest.java
File: XModuleTest.java
@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(); }
25. OldIndexBackwardsCompatibilityIT#getNodeDir()
Project: elasticsearch
File: OldIndexBackwardsCompatibilityIT.java
File: OldIndexBackwardsCompatibilityIT.java
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/"); }
26. JimfsWindowsLikeFileSystemTest#testPaths_areSortedCaseInsensitive()
Project: jimfs
File: JimfsWindowsLikeFileSystemTest.java
File: JimfsWindowsLikeFileSystemTest.java
@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 }
27. JimfsUnixLikeFileSystemTest#testPaths_areSortedCaseSensitive()
Project: jimfs
File: JimfsUnixLikeFileSystemTest.java
File: JimfsUnixLikeFileSystemTest.java
@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 }
28. JLinkNegativeTest#testDuplicateModule3()
Project: openjdk
File: JLinkNegativeTest.java
File: JLinkNegativeTest.java
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); } }
29. Basic#setupMRJARModuleInfo()
Project: openjdk
File: Basic.java
File: Basic.java
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); } }
30. Basic#servicesCreateWithoutFailureMRMJAR()
Project: openjdk
File: Basic.java
File: Basic.java
@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(); }
31. Basic#partialUpdateMRMJarFooNotAllFiles()
Project: openjdk
File: Basic.java
File: Basic.java
@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)); }
32. Basic#updateMRMJarFoo()
Project: openjdk
File: Basic.java
File: Basic.java
@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)); }
33. Basic#createMRMJarFoo()
Project: openjdk
File: Basic.java
File: Basic.java
/** 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)); }
34. ContentHandlersTest#step4_BuiltIn()
Project: openjdk
File: ContentHandlersTest.java
File: ContentHandlersTest.java
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); }
35. AbstractFullDistribZkTestBase#getRelativeSolrHomePath()
Project: lucene-solr
File: AbstractFullDistribZkTestBase.java
File: AbstractFullDistribZkTestBase.java
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(); }
36. MockFileSystemTestCase#testHashCodeEquals()
Project: lucene-solr
File: MockFileSystemTestCase.java
File: MockFileSystemTestCase.java
/** 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(); }
37. TestIOUtils#testManyPartitions()
Project: lucene-solr
File: TestIOUtils.java
File: TestIOUtils.java
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)); }
38. TestIOUtils#testRotatingPlatters()
Project: lucene-solr
File: TestIOUtils.java
File: TestIOUtils.java
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)); }
39. TestIOUtils#testSSD()
Project: lucene-solr
File: TestIOUtils.java
File: TestIOUtils.java
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)); }
40. AppPropertiesTest#constructorShouldUseHomeDirIfPropertiesNotInWorkingDir()
Project: SAGU
File: AppPropertiesTest.java
File: AppPropertiesTest.java
@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")); }
41. RemovedJDKInternals#compileAll()
Project: openjdk
File: RemovedJDKInternals.java
File: RemovedJDKInternals.java
/** * 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())); }
42. ReportNonExistentPackageTest#testPackageWithMemberWOPackageDeclaration()
Project: openjdk
File: ReportNonExistentPackageTest.java
File: ReportNonExistentPackageTest.java
@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"); }
43. NPECompilingModuleInfoTest#testCompileNoError()
Project: openjdk
File: NPECompilingModuleInfoTest.java
File: NPECompilingModuleInfoTest.java
@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); }
44. MultiModuleModeTest#testCantFindModule()
Project: openjdk
File: MultiModuleModeTest.java
File: MultiModuleModeTest.java
@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"); }
45. MultiModuleModeTest#testDuplicateModules()
Project: openjdk
File: MultiModuleModeTest.java
File: MultiModuleModeTest.java
@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"); }
46. ModulePathTest#oneModuleHidesAnother()
Project: openjdk
File: ModulePathTest.java
File: ModulePathTest.java
@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(); }
47. ModuleInfoTest#testDuplicateExports_modules()
Project: openjdk
File: ModuleInfoTest.java
File: ModuleInfoTest.java
/** * 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"); }
48. ModuleInfoTest#testDuplicateRequires()
Project: openjdk
File: ModuleInfoTest.java
File: ModuleInfoTest.java
/** * 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"); }
49. DoclintOtherModules#testSimple()
Project: openjdk
File: DoclintOtherModules.java
File: DoclintOtherModules.java
@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); }
50. AddReadsTest#testAddReadsUnnamedModule()
Project: openjdk
File: AddReadsTest.java
File: AddReadsTest.java
@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(); }
51. TestSynchronousFileFinder#testFindDirectoriesAndRegularFiles()
Project: datacollector
File: TestSynchronousFileFinder.java
File: TestSynchronousFileFinder.java
@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))); }
52. DirArtifactCacheTest#testDeleteNothingAbsentLimit()
Project: buck
File: DirArtifactCacheTest.java
File: DirArtifactCacheTest.java
@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); }
53. DirArtifactCacheTest#testDeleteNothing()
Project: buck
File: DirArtifactCacheTest.java
File: DirArtifactCacheTest.java
@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); }
54. StringifyAlterRuleKeyTest#findAbsolutePathsInMapOfPaths()
Project: buck
File: StringifyAlterRuleKeyTest.java
File: StringifyAlterRuleKeyTest.java
@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))); }
55. CellTest#shouldResolveFallbackCell()
Project: buck
File: CellTest.java
File: CellTest.java
@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); }
56. ResolverIntegrationTest#shouldDetectNewestJar()
Project: buck
File: ResolverIntegrationTest.java
File: ResolverIntegrationTest.java
@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)); }
57. ExecutableFinderTest#testSearchPathsMultipleFileFoundReturnsFirstPath()
Project: buck
File: ExecutableFinderTest.java
File: ExecutableFinderTest.java
@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())); }
58. ExecutableFinderTest#testSearchPathsNonExecutableFileIsIgnored()
Project: buck
File: ExecutableFinderTest.java
File: ExecutableFinderTest.java
@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())); }
59. ExecutableFinderTest#testSearchPathsFileFoundReturnsPath()
Project: buck
File: ExecutableFinderTest.java
File: ExecutableFinderTest.java
@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())); }
60. AsynchronousDirectoryContentsCleanerTest#contentsOfTrashDirectoryCleanedAsynchronously()
Project: buck
File: AsynchronousDirectoryContentsCleanerTest.java
File: AsynchronousDirectoryContentsCleanerTest.java
@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)); }
61. BackupRestoreSecurityPrincipalsTest#deleteDatabaseFiles()
Project: exist
File: BackupRestoreSecurityPrincipalsTest.java
File: BackupRestoreSecurityPrincipalsTest.java
private void deleteDatabaseFiles() throws DatabaseConfigurationException, IOException { final Path confFile = ConfigurationHelper.lookup("conf.xml"); final Configuration config = new Configuration(confFile.toAbsolutePath().toString()); final Path dataDir = Paths.get(config.getProperty(BrokerPool.PROPERTY_DATA_DIR).toString()); if (Files.exists(dataDir)) { deleteAllDataFiles(dataDir); } final Path journalDir = Paths.get(config.getProperty(Journal.PROPERTY_RECOVERY_JOURNAL_DIR).toString()); if (Files.exists(journalDir)) { deleteAllDataFiles(journalDir); } }
62. DotFileTest#initProfiles()
Project: error-prone-javac
File: DotFileTest.java
File: DotFileTest.java
private static boolean initProfiles() { // check if ct.sym exists; if not use the profiles.properties file Path home = Paths.get(System.getProperty("java.home")); if (home.endsWith("jre")) { home = home.getParent(); } Path ctsym = home.resolve("lib").resolve("ct.sym"); boolean symbolExists = ctsym.toFile().exists(); if (!symbolExists) { Path testSrcProfiles = Paths.get(System.getProperty("test.src", "."), "profiles.properties"); if (!testSrcProfiles.toFile().exists()) throw new Error(testSrcProfiles + " does not exist"); System.out.format("%s doesn't exist.%nUse %s to initialize profiles info%n", ctsym, testSrcProfiles); System.setProperty("jdeps.profiles", testSrcProfiles.toString()); } return symbolExists; }
63. Basic#initProfiles()
Project: error-prone-javac
File: Basic.java
File: Basic.java
private static boolean initProfiles() { // check if ct.sym exists; if not use the profiles.properties file Path home = Paths.get(System.getProperty("java.home")); if (home.endsWith("jre")) { home = home.getParent(); } Path ctsym = home.resolve("lib").resolve("ct.sym"); boolean symbolExists = ctsym.toFile().exists(); if (!symbolExists) { Path testSrcProfiles = Paths.get(System.getProperty("test.src", "."), "profiles.properties"); if (!testSrcProfiles.toFile().exists()) throw new Error(testSrcProfiles + " does not exist"); System.out.format("%s doesn't exist.%nUse %s to initialize profiles info%n", ctsym, testSrcProfiles); System.setProperty("jdeps.profiles", testSrcProfiles.toString()); } return symbolExists; }
64. APIDeps#initProfiles()
Project: error-prone-javac
File: APIDeps.java
File: APIDeps.java
private static boolean initProfiles() { // check if ct.sym exists; if not use the profiles.properties file Path home = Paths.get(System.getProperty("java.home")); if (home.endsWith("jre")) { home = home.getParent(); } Path ctsym = home.resolve("lib").resolve("ct.sym"); boolean symbolExists = ctsym.toFile().exists(); if (!symbolExists) { Path testSrcProfiles = Paths.get(System.getProperty("test.src", "."), "profiles.properties"); if (!testSrcProfiles.toFile().exists()) throw new Error(testSrcProfiles + " does not exist"); System.out.format("%s doesn't exist.%nUse %s to initialize profiles info%n", ctsym, testSrcProfiles); System.setProperty("jdeps.profiles", testSrcProfiles.toString()); } return symbolExists; }
65. CheckAptIsRemovedTest#main()
Project: error-prone-javac
File: CheckAptIsRemovedTest.java
File: CheckAptIsRemovedTest.java
public static void main(String[] args) throws Exception { String testJDK = System.getProperty("test.jdk"); Path aptLin = Paths.get(testJDK, "bin", "apt"); Path aptWin = Paths.get(testJDK, "bin", "apt.exe"); if (Files.exists(aptLin) || Files.exists(aptWin)) { throw new AssertionError("apt executable should not exist"); } Path classpath = Paths.get(testJDK, "lib", "tools.jar"); ToolBox tb = new ToolBox(); tb.new JavacTask().classpath(// TODO: add overload classpath.toString()).sourcepath(".").sources(NullAPFSrc).run(ToolBox.Expect.FAIL).writeAll(); }
66. AutomaticModulesTest#testBadServicesConfiguration()
Project: openjdk
File: AutomaticModulesTest.java
File: AutomaticModulesTest.java
/** * Test JAR file with META-INF/services configuration file with bad * values or names. */ @Test(dataProvider = "badproviders", expectedExceptions = FindException.class) public void testBadServicesConfiguration(String service, String provider) throws IOException { Path tmpdir = Files.createTempDirectory(USER_DIR, "tmp"); Path services = tmpdir.resolve("META-INF").resolve("services"); Files.createDirectories(services); Files.write(services.resolve(service), Set.of(provider)); Path dir = Files.createTempDirectory(USER_DIR, "mods"); JarUtils.createJarFile(dir.resolve("m1.jar"), tmpdir); // should throw FindException ModuleFinder.of(dir).findAll(); }
67. AutomaticModulesTest#testServicesConfiguration()
Project: openjdk
File: AutomaticModulesTest.java
File: AutomaticModulesTest.java
/** * Test JAR file with META-INF/services configuration file */ public void testServicesConfiguration() throws IOException { String service = "p.S"; String provider = "p.S1"; Path tmpdir = Files.createTempDirectory(USER_DIR, "tmp"); Path services = tmpdir.resolve("META-INF").resolve("services"); Files.createDirectories(services); Files.write(services.resolve(service), Set.of(provider)); Path dir = Files.createTempDirectory(USER_DIR, "mods"); JarUtils.createJarFile(dir.resolve("m1.jar"), tmpdir); ModuleFinder finder = ModuleFinder.of(dir); Optional<ModuleReference> mref = finder.find("m1"); assertTrue(mref.isPresent(), "m1 not found"); ModuleDescriptor descriptor = mref.get().descriptor(); assertTrue(descriptor.provides().size() == 1); assertTrue(descriptor.provides().containsKey(service)); ModuleDescriptor.Provides provides = descriptor.provides().get(service); assertTrue(provides.providers().size() == 1); assertTrue(provides.providers().contains((provider))); }
68. InstallPluginCommandTests#testExistingConfig()
Project: elasticsearch
File: InstallPluginCommandTests.java
File: InstallPluginCommandTests.java
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"))); }
69. EvilSecurityTests#testSymlinkPermissions()
Project: elasticsearch
File: EvilSecurityTests.java
File: EvilSecurityTests.java
/** 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); }
70. EvilSecurityTests#testEnsureSymlink()
Project: elasticsearch
File: EvilSecurityTests.java
File: EvilSecurityTests.java
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); }
71. FileScriptTests#makeScriptService()
Project: elasticsearch
File: FileScriptTests.java
File: FileScriptTests.java
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); }
72. DiagnosticTest#oneFileParseErrorReplace()
Project: google-java-format
File: DiagnosticTest.java
File: DiagnosticTest.java
@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 {}"); }
73. DiagnosticTest#oneFileParseError()
Project: google-java-format
File: DiagnosticTest.java
File: DiagnosticTest.java
@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); }
74. CloudStorageFileSystemProviderTest#testCopy_overwriteAttributes()
Project: gcloud-java
File: CloudStorageFileSystemProviderTest.java
File: CloudStorageFileSystemProviderTest.java
@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"); }
75. ClasspathEntriesParserTests#toURLsWithMultiplePathsInSingleEntry()
Project: junit5
File: ClasspathEntriesParserTests.java
File: ClasspathEntriesParserTests.java
@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]); }
76. ClasspathEntriesParserTests#toURLsWithMultiplePathsInMultipleEntries()
Project: junit5
File: ClasspathEntriesParserTests.java
File: ClasspathEntriesParserTests.java
@Test public void toURLsWithMultiplePathsInMultipleEntries() throws Exception { Path root = getFileSystemRoot(); Path path1 = root.resolve("foo"); Path path2 = root.resolve("bar"); URL[] urls = new ClasspathEntriesParser().toURLs(asList(path1.toString(), path2.toString())); assertEquals(2, urls.length); assertEquals(path1.toUri().toURL(), urls[0]); assertEquals(path2.toUri().toURL(), urls[1]); }
77. JimfsPathTest#testEqualityBasedOnStringNotName()
Project: jimfs
File: JimfsPathTest.java
File: JimfsPathTest.java
@Test public void testEqualityBasedOnStringNotName() { Name a1 = Name.create("a", "a"); Name a2 = Name.create("A", "a"); Name a3 = Name.create("a", "A"); Path path1 = pathService.createFileName(a1); Path path2 = pathService.createFileName(a2); Path path3 = pathService.createFileName(a3); new EqualsTester().addEqualityGroup(path1, path3).addEqualityGroup(path2).testEquals(); }
78. FileWritingTest#filerNestedClasses()
Project: javapoet
File: FileWritingTest.java
File: FileWritingTest.java
@Test public void filerNestedClasses() throws IOException { TypeSpec type = TypeSpec.classBuilder("Test").build(); JavaFile.builder("foo", type).build().writeTo(filer); JavaFile.builder("foo.bar", type).build().writeTo(filer); JavaFile.builder("foo.bar.baz", type).build().writeTo(filer); Path fooPath = fsRoot.resolve(fs.getPath("foo", "Test.java")); Path barPath = fsRoot.resolve(fs.getPath("foo", "bar", "Test.java")); Path bazPath = fsRoot.resolve(fs.getPath("foo", "bar", "baz", "Test.java")); assertThat(Files.exists(fooPath)).isTrue(); assertThat(Files.exists(barPath)).isTrue(); assertThat(Files.exists(bazPath)).isTrue(); }
79. FileWritingTest#pathNestedClasses()
Project: javapoet
File: FileWritingTest.java
File: FileWritingTest.java
@Test public void pathNestedClasses() throws IOException { TypeSpec type = TypeSpec.classBuilder("Test").build(); JavaFile.builder("foo", type).build().writeTo(fsRoot); JavaFile.builder("foo.bar", type).build().writeTo(fsRoot); JavaFile.builder("foo.bar.baz", type).build().writeTo(fsRoot); Path fooPath = fsRoot.resolve(fs.getPath("foo", "Test.java")); Path barPath = fsRoot.resolve(fs.getPath("foo", "bar", "Test.java")); Path bazPath = fsRoot.resolve(fs.getPath("foo", "bar", "baz", "Test.java")); assertThat(Files.exists(fooPath)).isTrue(); assertThat(Files.exists(barPath)).isTrue(); assertThat(Files.exists(bazPath)).isTrue(); }
80. TestDownloadManagerImpl#downloadLocalFile()
Project: incubator-taverna-osgi
File: TestDownloadManagerImpl.java
File: TestDownloadManagerImpl.java
/** * Test downloading a file:/// to a File, checking md5 hashsum. * * This might seem silly, but avoids spinning up a Jetty instance * just for this unit test. * */ @Test public void downloadLocalFile() throws Exception { Path example = Files.createTempFile("test", ".txt"); // No newline Files.write(example, "Hello world".getBytes(US_ASCII)); Path exampleMd5 = example.resolveSibling(example.getFileName() + ".md5"); // stain@biggie:~$ echo -n "Hello world"|md5sum // 3e25960a79dbc69b674cd4ec67a72c62 - // no newline Files.write(exampleMd5, "3e25960a79dbc69b674cd4ec67a72c62".getBytes(US_ASCII)); DownloadManagerImpl dl = new DownloadManagerImpl(); Path toFile = Files.createTempFile("downloaded", ".txt"); dl.download(example.toUri(), toFile, "MD5"); String hello = Files.readAllLines(toFile, US_ASCII).get(0); assertEquals("Hello world", hello); }
81. IndexFolderUpgraderTests#writeShard()
Project: elasticsearch
File: IndexFolderUpgraderTests.java
File: IndexFolderUpgraderTests.java
private void writeShard(ShardId shardId, Path indexLocation, final int numIdxFiles, final int numTranslogFiles) throws IOException { Path oldShardDataPath = indexLocation.resolve(String.valueOf(shardId.getId())); final Path translogPath = oldShardDataPath.resolve(ShardPath.TRANSLOG_FOLDER_NAME); final Path idxPath = oldShardDataPath.resolve(ShardPath.INDEX_FOLDER_NAME); Files.createDirectories(translogPath); Files.createDirectories(idxPath); for (int i = 0; i < numIdxFiles; i++) { String filename = Integer.toString(i); try (BufferedWriter w = Files.newBufferedWriter(idxPath.resolve(filename + ".tst"), StandardCharsets.UTF_8)) { w.write(filename); } } for (int i = 0; i < numTranslogFiles; i++) { String filename = Integer.toString(i); try (BufferedWriter w = Files.newBufferedWriter(translogPath.resolve(filename + ".translog"), StandardCharsets.UTF_8)) { w.write(filename); } } }
82. LoggingConfigurationTests#testResolveYamlLoggingConfig()
Project: elasticsearch
File: LoggingConfigurationTests.java
File: LoggingConfigurationTests.java
public void testResolveYamlLoggingConfig() throws Exception { Path tmpDir = createTempDir(); Path loggingConf1 = tmpDir.resolve(loggingConfiguration("yml")); Path loggingConf2 = tmpDir.resolve(loggingConfiguration("yaml")); Files.write(loggingConf1, "yml: bar".getBytes(StandardCharsets.UTF_8)); Files.write(loggingConf2, "yaml: bar".getBytes(StandardCharsets.UTF_8)); Environment environment = new Environment(Settings.builder().put(Environment.PATH_CONF_SETTING.getKey(), tmpDir.toAbsolutePath()).put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString()).build()); Settings.Builder builder = Settings.builder(); LogConfigurator.resolveConfig(environment, builder); Settings logSettings = builder.build(); assertThat(logSettings.get("yml"), is("bar")); assertThat(logSettings.get("yaml"), is("bar")); }
83. TestIOUtils#testFsyncFile()
Project: lucene-solr
File: TestIOUtils.java
File: TestIOUtils.java
public void testFsyncFile() throws Exception { Path dir = createTempDir(); dir = FilterPath.unwrap(dir).toRealPath(); Path devdir = dir.resolve("dev"); Files.createDirectories(devdir); Path somefile = devdir.resolve("somefile"); try (OutputStream o = Files.newOutputStream(somefile)) { o.write("0\n".getBytes(StandardCharsets.US_ASCII)); } IOUtils.fsync(somefile, false); // no exception }
84. TestIOUtils#testSpinsBasics()
Project: lucene-solr
File: TestIOUtils.java
File: TestIOUtils.java
public void testSpinsBasics() throws Exception { Path dir = createTempDir(); // no exception, directory exists IOUtils.spins(dir); Path file = dir.resolve("exists"); Files.createFile(file); // no exception, file exists IOUtils.spins(file); // exception: file doesn't exist Path fake = dir.resolve("nonexistent"); expectThrows(IOException.class, () -> { IOUtils.spins(fake); }); }
85. TestCompile#testCompileMulti()
Project: lucene-solr
File: TestCompile.java
File: TestCompile.java
public void testCompileMulti() throws Exception { Path dir = createTempDir("testCompile"); Path output = dir.resolve("testRules.txt"); try (InputStream input = getClass().getResourceAsStream("testRules.txt")) { Files.copy(input, output); } String path = output.toAbsolutePath().toString(); Compile.main(new String[] { "Mtest", path }); Path compiled = dir.resolve("testRules.txt.out"); Trie trie = loadTrie(compiled); assertTrie(trie, output, true, true); assertTrie(trie, output, false, true); }
86. TestCompile#testCompileBackwards()
Project: lucene-solr
File: TestCompile.java
File: TestCompile.java
public void testCompileBackwards() throws Exception { Path dir = createTempDir("testCompile"); Path output = dir.resolve("testRules.txt"); try (InputStream input = getClass().getResourceAsStream("testRules.txt")) { Files.copy(input, output); } String path = output.toAbsolutePath().toString(); Compile.main(new String[] { "-test", path }); Path compiled = dir.resolve("testRules.txt.out"); Trie trie = loadTrie(compiled); assertTrie(trie, output, true, true); assertTrie(trie, output, false, true); }
87. TestCompile#testCompile()
Project: lucene-solr
File: TestCompile.java
File: TestCompile.java
public void testCompile() throws Exception { Path dir = createTempDir("testCompile"); Path output = dir.resolve("testRules.txt"); try (InputStream input = getClass().getResourceAsStream("testRules.txt")) { Files.copy(input, output); } String path = output.toAbsolutePath().toString(); Compile.main(new String[] { "test", path }); Path compiled = dir.resolve("testRules.txt.out"); Trie trie = loadTrie(compiled); assertTrie(trie, output, true, true); assertTrie(trie, output, false, true); }
88. StringsResourceTranslator#main()
Project: zxing
File: StringsResourceTranslator.java
File: StringsResourceTranslator.java
public static void main(String[] args) throws IOException { Path resDir = Paths.get(args[0]); Path valueDir = resDir.resolve("values"); Path stringsFile = valueDir.resolve("strings.xml"); Collection<String> forceRetranslation = Arrays.asList(args).subList(1, args.length); DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() { @Override public boolean accept(Path entry) { return Files.isDirectory(entry) && !Files.isSymbolicLink(entry) && VALUES_DIR_PATTERN.matcher(entry.getFileName().toString()).matches(); } }; try (DirectoryStream<Path> dirs = Files.newDirectoryStream(resDir, filter)) { for (Path dir : dirs) { translate(stringsFile, dir.resolve("strings.xml"), forceRetranslation); } } }
89. MwDumpFileProcessingTest#setLocalDumpFile()
Project: Wikidata-Toolkit
File: MwDumpFileProcessingTest.java
File: MwDumpFileProcessingTest.java
private void setLocalDumpFile(String dateStamp, DumpContentType dumpContentType, MockDirectoryManager dm) throws IOException { URL resourceUrl = MwDumpFileProcessingTest.class.getResource("/mock-dump-for-testing.xml"); Path dmPath = Paths.get(System.getProperty("user.dir")); Path dumpFilePath = dmPath.resolve("dumpfiles").resolve("wikidatawiki"); Path thisDumpPath = dumpFilePath.resolve(dumpContentType.toString().toLowerCase() + "-" + dateStamp); dm.setFileContents(thisDumpPath.resolve("wikidatawiki-" + dateStamp + WmfDumpFile.getDumpFilePostfix(dumpContentType)), MockStringContentFactory.getStringFromUrl(resourceUrl), WmfDumpFile.getDumpFileCompressionType(dumpContentType)); }
90. JsonDumpFileProcessingTest#setLocalJsonDumpFile()
Project: Wikidata-Toolkit
File: JsonDumpFileProcessingTest.java
File: JsonDumpFileProcessingTest.java
private void setLocalJsonDumpFile(String fileName, String dateStamp, MockDirectoryManager dm) throws IOException { DumpContentType dumpContentType = DumpContentType.JSON; URL resourceUrl = MwDumpFileProcessingTest.class.getResource("/" + fileName); Path dmPath = Paths.get(System.getProperty("user.dir")); Path dumpFilePath = dmPath.resolve("dumpfiles").resolve("wikidatawiki"); Path thisDumpPath = dumpFilePath.resolve(dumpContentType.toString().toLowerCase() + "-" + dateStamp); dm.setFileContents(thisDumpPath.resolve(dateStamp + WmfDumpFile.getDumpFilePostfix(dumpContentType)), MockStringContentFactory.getStringFromUrl(resourceUrl), WmfDumpFile.getDumpFileCompressionType(dumpContentType)); }
91. SwiftGeneratorTest#thriftProvider()
Project: swift
File: SwiftGeneratorTest.java
File: SwiftGeneratorTest.java
@DataProvider public Iterator<Object[]> thriftProvider() throws Exception { Path inputBase; List<GenerationPaths> testFiles = Lists.newArrayList(); inputBase = getResourcePath("").resolve("basic"); for (Path input : listMatchingFiles(inputBase, "**/*.thrift")) { testFiles.add(new GenerationPaths(input.toUri(), inputBase.toUri(), new URI[] {})); } inputBase = getResourcePath("").resolve("include_path_tests"); for (Path input : listMatchingFiles(inputBase, "**/*.thrift")) { testFiles.add(new GenerationPaths(input.toUri(), inputBase.toUri(), new URI[] { // Generate an absolute URI include path getResourcePath("").resolve("include_path_1").toUri(), // as well as a relative URI include path URI.create("../include_path_2/") })); } return listDataProvider(testFiles); }
92. MarkdownConverterTest#testSwagger2MarkdownConversionWithResponseHeaders()
Project: swagger2markup
File: MarkdownConverterTest.java
File: MarkdownConverterTest.java
@Test public void testSwagger2MarkdownConversionWithResponseHeaders() throws IOException, URISyntaxException { //Given Path file = Paths.get(AsciidocConverterTest.class.getResource("/yaml/swagger_response_headers.yaml").toURI()); Path outputDirectory = Paths.get("build/test/markdown/response_headers"); 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/response_headers").toURI()); DiffUtils.assertThatAllFilesAreEqual(expectedFilesDirectory, outputDirectory, "testSwagger2MarkdownConversionWithResponseHeaders.html"); }
93. MarkdownConverterTest#testSwagger2MarkdownConversionWithInterDocumentCrossReferences()
Project: swagger2markup
File: MarkdownConverterTest.java
File: MarkdownConverterTest.java
@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"); }
94. MarkdownConverterTest#testSwagger2MarkdownConversion()
Project: swagger2markup
File: MarkdownConverterTest.java
File: MarkdownConverterTest.java
@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"); }
95. AsciidocConverterTest#testSwagger2AsciiDocConversionWithResponseHeaders()
Project: swagger2markup
File: AsciidocConverterTest.java
File: AsciidocConverterTest.java
@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"); }
96. AsciidocConverterTest#testSwagger2AsciiDocConversionWithPolymorphismAsIsOrdering()
Project: swagger2markup
File: AsciidocConverterTest.java
File: AsciidocConverterTest.java
@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"); }
97. AsciidocConverterTest#testSwagger2AsciiDocConversionWithPolymorphism()
Project: swagger2markup
File: AsciidocConverterTest.java
File: AsciidocConverterTest.java
@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"); }
98. AsciidocConverterTest#testSwagger2AsciiDocConversionWithValidators()
Project: swagger2markup
File: AsciidocConverterTest.java
File: AsciidocConverterTest.java
@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"); }
99. AsciidocConverterTest#testSwagger2AsciiDocConversionWithEnums()
Project: swagger2markup
File: AsciidocConverterTest.java
File: AsciidocConverterTest.java
@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"); }
100. AsciidocConverterTest#testSwagger2AsciiDocConversionWithMaps()
Project: swagger2markup
File: AsciidocConverterTest.java
File: AsciidocConverterTest.java
@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"); }