Java Code Examples for java.nio.file.FileSystem#getPath()

The following examples show how to use java.nio.file.FileSystem#getPath() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Basic.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test(dataProvider = "packagesLinkedDirs")
public void dirStreamPackagesDirTest(String dirName) throws IOException {
    FileSystem fs = FileSystems.getFileSystem(URI.create("jrt:/"));
    Path path = fs.getPath(dirName);

    int childCount = 0, dirPrefixOkayCount = 0;
    try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(path)) {
        for (Path child : dirStream) {
            childCount++;
            if (child.toString().startsWith(dirName)) {
                dirPrefixOkayCount++;
            }
        }
    }

    assertTrue(childCount != 0);
    assertEquals(dirPrefixOkayCount, childCount);
}
 
Example 2
Source File: TransformWorkTest.java    From copybara with Apache License 2.0 6 votes vote down vote up
@Test
public void testRunDynamicTransforms() throws IOException, ValidationException, RepoException {
  FileSystem fileSystem = Jimfs.newFileSystem();
  Path base = fileSystem.getPath("testRunDynamicTransforms");
  touchFile(base, "folder/file1.txt");
  touchFile(base, "folder/file2.txt");
  touchFile(base, "folder/file3.txt");

  Files.createDirectories(workdir.resolve("folder"));
  origin.addChange(0, base, "message", /*matchesGlob=*/true);

  runWorkflow("test", ""
      + "def test(ctx):\n"
      + "    message = ''\n"
      + "    for f in ctx.run(glob(['**.txt'])):\n"
      + "        ctx.run(core.move(f.path, 'other/folder/prefix_' + f.name))");

  assertThat(destination.processed.get(0).getWorkdir().keySet()).containsExactly(
      "other/folder/prefix_file1.txt",
      "other/folder/prefix_file2.txt",
      "other/folder/prefix_file3.txt");
}
 
Example 3
Source File: TransformWorkTest.java    From copybara with Apache License 2.0 6 votes vote down vote up
@Test
public void testTreeStateRestored() throws IOException, ValidationException, RepoException {
  FileSystem fileSystem = Jimfs.newFileSystem();
  Path base = fileSystem.getPath("testTreeStateRestored");
  writeFile(base, "folder/file1.txt", "aaa");
  writeFile(base, "folder/file2.txt", "aaa");
  writeFile(base, "folder/file3.txt", "aaa");

  Files.createDirectories(workdir.resolve("folder"));
  origin.addChange(0, base, "message", /*matchesGlob=*/true);

  runWorkflow("test", ""
      + "def test(ctx):\n"
      + "    message = ''\n"
      + "    for f in ctx.run(glob(['**.txt'])):\n"
      + "        ctx.run(core.move(f.path, 'prefix_' + f.name))\n"
      + "        ctx.run(core.replace("
      + "before ='aaa', after = 'bbb', paths = glob(['prefix_' + f.name])))");

  assertThat(destination.processed.get(0).getWorkdir())
      .containsExactlyEntriesIn(ImmutableMap.of(
          "prefix_file1.txt", "bbb",
          "prefix_file2.txt", "bbb",
          "prefix_file3.txt", "bbb"));
}
 
Example 4
Source File: ResolvePaths.java    From java-1-class-demos with MIT License 6 votes vote down vote up
public static void main(String[] args) {

		FileSystem fs = FileSystems.getDefault();
		
		String linuxPath = "/home/ard/Documents/tmp-pdf.txt";			// this is a linux filesytem path.
		String windowsPath = "C:\\Users\\aaron.decker\\Documents"; 		// in java you must escape backslashes
		
		Path testPath = fs.getPath(linuxPath);
		System.out.println(testPath);
		
		Path testPath2 = fs.getPath(windowsPath, "tmp.txt");
		System.out.println(testPath2);
		
		try {
			// null char is not allowed on linux "\0"
			// on windows ? is not allowed.
			Path testPath3 = fs.getPath("\0");  // special NULL char.
			System.out.println(testPath3);
		} catch (InvalidPathException e ) {
			System.out.println(e);
		}
		
	}
 
Example 5
Source File: TestIOUtils.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
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));
}
 
Example 6
Source File: Basic.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Test the URI of every file in the jrt file system
 */
@Test
public void testToAndFromUri() throws Exception {
    FileSystem fs = FileSystems.getFileSystem(URI.create("jrt:/"));
    Path top = fs.getPath("/");
    try (Stream<Path> stream = Files.walk(top)) {
        stream.forEach(path -> {
            URI u = path.toUri();
            assertTrue(u.getScheme().equalsIgnoreCase("jrt"));
            assertFalse(u.isOpaque());
            assertTrue(u.getAuthority() == null);
            assertEquals(u.getPath(), path.toAbsolutePath().toString());
            Path p = Paths.get(u);
            assertEquals(p, path);
        });
    }
}
 
Example 7
Source File: SequenceTest.java    From copybara with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws IOException {
  FileSystem fs = Jimfs.newFileSystem();
  checkoutDir = fs.getPath("/test-checkoutDir");
  Files.createDirectories(checkoutDir);
  OptionsBuilder options = new OptionsBuilder();
  console = new TestingConsole();
  options.setConsole(console);
  sequence = new Sequence(options.general.profiler(), /*joinTransformations*/true,
                          ImmutableList.of(t1, t2));
}
 
Example 8
Source File: ConfigurationFolderMonitor.java    From JVoiceXML with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Resolves this path against the config folder.
 * @param path the observed path
 * @return a file object relative to the config folder.
 * @throws IOException error resolving the path
 */
private File resolve(final Path path) throws IOException {
    final FileSystem filesystem = FileSystems.getDefault();
    final String canonicalPath = configFolder.getCanonicalPath();
    final Path configFolderPath = filesystem.getPath(canonicalPath);
    final Path resolvedPath = configFolderPath.resolve(path);
    return resolvedPath.toFile();
}
 
Example 9
Source File: CustomLauncherTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static String[] getLauncher() throws IOException {
    String platform = getPlatform();
    if (platform == null) {
        return null;
    }

    String launcher = TEST_SRC + File.separator + platform + "-" + ARCH +
                      File.separator + "launcher";

    final FileSystem FS = FileSystems.getDefault();
    Path launcherPath = FS.getPath(launcher);

    final boolean hasLauncher = Files.isRegularFile(launcherPath, LinkOption.NOFOLLOW_LINKS)&&
                                Files.isReadable(launcherPath);
    if (!hasLauncher) {
        System.out.println("Launcher [" + launcher + "] does not exist. Skipping the test.");
        return null;
    }

    // It is impossible to store an executable file in the source control
    // We need to copy the launcher to the working directory
    // and set the executable flag
    Path localLauncherPath = FS.getPath(WORK_DIR, "launcher");
    Files.copy(launcherPath, localLauncherPath,
               StandardCopyOption.REPLACE_EXISTING);
    if (!Files.isExecutable(localLauncherPath)) {
        Set<PosixFilePermission> perms = new HashSet<>(
            Files.getPosixFilePermissions(
                localLauncherPath,
                LinkOption.NOFOLLOW_LINKS
            )
        );
        perms.add(PosixFilePermission.OWNER_EXECUTE);
        Files.setPosixFilePermissions(localLauncherPath, perms);
    }
    return new String[] {launcher, localLauncherPath.toAbsolutePath().toString()};
}
 
Example 10
Source File: ManifestMergerActionTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a runfile's path.
 *
 * <p>The `path` must specify a valid runfile, meaning on Windows (where $RUNFILES_MANIFEST_ONLY
 * is 1) the `path` must exactly match a runfiles manifest entry, and on Linux/MacOS `path` must
 * point to a valid file in the runfiles directory.
 */
@Nullable
private static Path rlocation(String path) throws IOException {
  FileSystem fs = FileSystems.getDefault();
  if (fs.getPath(path).isAbsolute()) {
    return fs.getPath(path);
  }
  if ("1".equals(System.getenv("RUNFILES_MANIFEST_ONLY"))) {
    String manifest = System.getenv("RUNFILES_MANIFEST_FILE");
    assertThat(manifest).isNotNull();
    try (BufferedReader r =
        Files.newBufferedReader(Paths.get(manifest), Charset.defaultCharset())) {
      Splitter splitter = Splitter.on(' ').limit(2);
      String line = null;
      while ((line = r.readLine()) != null) {
        List<String> tokens = splitter.splitToList(line);
        if (tokens.size() == 2) {
          if (tokens.get(0).equals(path)) {
            return fs.getPath(tokens.get(1));
          }
        }
      }
    }
    return null;
  } else {
    String runfiles = System.getenv("RUNFILES_DIR");
    if (runfiles == null) {
      runfiles = System.getenv("JAVA_RUNFILES");
      assertThat(runfiles).isNotNull();
    }
    Path result = fs.getPath(runfiles).resolve(path);
    assertThat(result.toFile().exists()).isTrue(); // comply with function's contract
    return result;
  }
}
 
Example 11
Source File: Packager.java    From IDES-Data-Preparation-Java with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
public boolean renameZipEntries(String zipFile, String[] entryNames, String[] newEntryNames) throws Exception {
	if (logger.isDebugEnabled()) {
		StringBuilder sb = new StringBuilder("--> renameZipEntries()");
		sb.append(", zipFile=");
		sb.append(zipFile);
		sb.append(", entryNames=[");
		for (int i = 0; i < entryNames.length; i++) {
			if (i > 0) sb.append(",");
			sb.append(entryNames[i]);
		}
		sb.append("], newEntryNames=[");
		for (int i = 0; i < newEntryNames.length; i++) {
			if (i > 0) sb.append(",");
			sb.append(newEntryNames[i]);
		}
		sb.append("]");
		logger.debug(sb.toString());
	}
	boolean ret = false;
	if (entryNames.length != newEntryNames.length)
		throw new Exception("renameZipEntries entryNames and newEntryNames length should be same");
       HashMap<String, String> props = new HashMap<String, String>(); 
       props.put("create", "false"); 
       URI zipDisk = URI.create("jar:" + new File(zipFile).toURI());
   	FileSystem zipfs = FileSystems.newFileSystem(zipDisk, props);
   	Path pathInZipfile, renamedZipEntry;
   	for (int i = 0; i < entryNames.length; i++) {
           pathInZipfile = zipfs.getPath(entryNames[i]);
           renamedZipEntry = zipfs.getPath(newEntryNames[i]);
           Files.move(pathInZipfile, renamedZipEntry, StandardCopyOption.ATOMIC_MOVE);
   	}
       zipfs.close();
       ret = true;
	logger.debug("<-- renameZipEntries()");
	return ret;
}
 
Example 12
Source File: TestFinder.java    From jdk8u_nashorn with GNU General Public License v2.0 5 votes vote down vote up
private static Path[] getExcludeDirs() {
    final String excludeDirs[] = System.getProperty(TEST_JS_EXCLUDE_DIR, "test/script/currently-failing").split(" ");
    final Path[] excludePaths = new Path[excludeDirs.length];
    final FileSystem fileSystem = FileSystems.getDefault();
    int i = 0;
    for (final String excludeDir : excludeDirs) {
        excludePaths[i++] = fileSystem.getPath(excludeDir);
    }
    return excludePaths;
}
 
Example 13
Source File: NotificationInfoTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static Set<String> findStandardMBeansFromRuntime() throws Exception {
    FileSystem fs = FileSystems.getFileSystem(URI.create("jrt:/"));
    Path modules = fs.getPath("/modules");
    return Files.walk(modules)
            .filter(path -> path.toString().endsWith(".class"))
            .map(path -> path.subpath(2, path.getNameCount()))
            .map(Path::toString)
            .map(s -> s.substring(0, s.length() - 6))  // drop .class
            .filter(s -> !s.equals("module-info"))
            .map(s -> s.replace('/', '.'))
            .collect(Collectors.toSet());
}
 
Example 14
Source File: TestFinder.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static Path[] getExcludeDirs() {
    final String excludeDirs[] = System.getProperty(TEST_JS_EXCLUDE_DIR, "test/script/currently-failing").split(" ");
    final Path[] excludePaths = new Path[excludeDirs.length];
    final FileSystem fileSystem = FileSystems.getDefault();
    int i = 0;
    for (final String excludeDir : excludeDirs) {
        excludePaths[i++] = fileSystem.getPath(excludeDir);
    }
    return excludePaths;
}
 
Example 15
Source File: MavenProducerBase.java    From galleon with Apache License 2.0 4 votes vote down vote up
protected static Path getProducerDir(FileSystem zipfs, String producerName) {
    return zipfs.getPath(GALLEON, UNIVERSE, PRODUCER, producerName);
}
 
Example 16
Source File: LocalComputationConfig.java    From powsybl-core with Mozilla Public License 2.0 4 votes vote down vote up
private static Path getDefaultLocalDir(FileSystem fileSystem) {
    return fileSystem.getPath(DEFAULT_LOCAL_DIR);
}
 
Example 17
Source File: JavacPathFileManager.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
private static Path getPath(FileSystem fs, String relativePath) {
    return fs.getPath(relativePath.replace("/", fs.getSeparator()));
}
 
Example 18
Source File: TestFinder.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
static <T> void findAllTests(final List<T> tests, final Set<String> orphans, final TestFactory<T> testFactory) throws Exception {
    final String framework = System.getProperty(TEST_JS_FRAMEWORK);
    final String testList = System.getProperty(TEST_JS_LIST);
    final String failedTestFileName = System.getProperty(TEST_FAILED_LIST_FILE);
    if (failedTestFileName != null) {
        final File failedTestFile = new File(failedTestFileName);
        if (failedTestFile.exists() && failedTestFile.length() > 0L) {
            try (final BufferedReader r = new BufferedReader(new FileReader(failedTestFile))) {
                for (;;) {
                    final String testFileName = r.readLine();
                    if (testFileName == null) {
                        break;
                    }
                    handleOneTest(framework, new File(testFileName).toPath(), tests, orphans, testFactory);
                }
            }
            return;
        }
    }
    if (testList == null || testList.length() == 0) {
        // Run the tests under the test roots dir, selected by the
        // TEST_JS_INCLUDES patterns
        final String testRootsString = System.getProperty(TEST_JS_ROOTS, "test/script");
        if (testRootsString == null || testRootsString.length() == 0) {
            throw new Exception("Error: " + TEST_JS_ROOTS + " must be set");
        }
        final String testRoots[] = testRootsString.split(" ");
        final FileSystem fileSystem = FileSystems.getDefault();
        final Set<String> testExcludeSet = getExcludeSet();
        final Path[] excludePaths = getExcludeDirs();
        for (final String root : testRoots) {
            final Path dir = fileSystem.getPath(root);
            findTests(framework, dir, tests, orphans, excludePaths, testExcludeSet, testFactory);
        }
    } else {
        // TEST_JS_LIST contains a blank speparated list of test file names.
        final String strArray[] = testList.split(" ");
        for (final String ss : strArray) {
            handleOneTest(framework, new File(ss).toPath(), tests, orphans, testFactory);
        }
    }
}
 
Example 19
Source File: ClassWriterTest.java    From turbine with Apache License 2.0 4 votes vote down vote up
@Test
public void roundTrip() throws Exception {
  FileSystem fs = Jimfs.newFileSystem(Configuration.unix());
  Path path = fs.getPath("test/Test.java");
  Files.createDirectories(path.getParent());
  Files.write(
      path,
      ImmutableList.of(
          "package test;",
          "import java.util.List;",
          "class Test<T extends String> implements Runnable {", //
          "  public void run() {}",
          "  public <T extends Exception> void f() throws T {}",
          "  public static int X;",
          "  class Inner {}",
          "}"),
      UTF_8);
  Path out = fs.getPath("out");
  Files.createDirectories(out);

  JavacFileManager fileManager = new JavacFileManager(new Context(), false, UTF_8);
  fileManager.setLocationFromPaths(StandardLocation.CLASS_OUTPUT, ImmutableList.of(out));
  DiagnosticCollector<JavaFileObject> collector = new DiagnosticCollector<>();
  JavacTask task =
      JavacTool.create()
          .getTask(
              new PrintWriter(
                  new BufferedWriter(new OutputStreamWriter(System.err, UTF_8)), true),
              fileManager,
              collector,
              ImmutableList.of("-source", "8", "-target", "8"),
              /* classes= */ null,
              fileManager.getJavaFileObjects(path));

  assertWithMessage(collector.getDiagnostics().toString()).that(task.call()).isTrue();

  byte[] original = Files.readAllBytes(out.resolve("test/Test.class"));
  byte[] actual = ClassWriter.writeClass(ClassReader.read(null, original));

  assertThat(AsmUtils.textify(original, /* skipDebug= */ true))
      .isEqualTo(AsmUtils.textify(actual, /* skipDebug= */ true));
}
 
Example 20
Source File: JavacPathFileManager.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
private static Path resolve(Path base, String relativePath) {
    FileSystem fs = base.getFileSystem();
    Path rp = fs.getPath(relativePath.replace("/", fs.getSeparator()));
    return base.resolve(rp);
}