Java Code Examples for java.nio.file.Path#getRoot()
The following examples show how to use
java.nio.file.Path#getRoot() .
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: PathTester.java From jimfs with Apache License 2.0 | 6 votes |
private void testEndsWith(Path path) { // empty path doesn't start with any path if (root != null || !names.isEmpty()) { Path other = path; while (other != null) { assertTrue(path + ".endsWith(" + other + ") should be true", path.endsWith(other)); assertTrue( path + ".endsWith(" + other + ") should be true", path.endsWith(other.toString())); if (other.getRoot() != null && other.getNameCount() > 0) { other = other.subpath(0, other.getNameCount()); } else if (other.getNameCount() > 1) { other = other.subpath(1, other.getNameCount()); } else { other = null; } } } }
Example 2
Source File: JimfsPathTest.java From jimfs with Apache License 2.0 | 6 votes |
private void assertResolvedPathEquals( String expected, Path path, String firstResolvePath, String... moreResolvePaths) { Path resolved = path.resolve(firstResolvePath); for (String additionalPath : moreResolvePaths) { resolved = resolved.resolve(additionalPath); } assertPathEquals(expected, resolved); Path relative = pathService.parsePath(firstResolvePath, moreResolvePaths); resolved = path.resolve(relative); assertPathEquals(expected, resolved); // assert the invariant that p.relativize(p.resolve(q)).equals(q) when q does not have a root // p = path, q = relative, p.resolve(q) = resolved if (relative.getRoot() == null) { assertEquals(relative, path.relativize(resolved)); } }
Example 3
Source File: Paths.java From js-dossier with Apache License 2.0 | 6 votes |
/** * Returns the {@link Path} that represents the longest common prefix for the provided {@code * paths}. All paths will be resolved and normalized relative to the given {@code root} directory * before computing a common prefix. * * <p>If all of the provided {@code paths} do not designate */ static Path getCommonPrefix(Path root, Collection<Path> paths) { if (paths.isEmpty()) { return root; } root = root.toAbsolutePath(); paths = paths.stream().map(normalizeRelativeTo(root)).collect(toList()); Path prefix = root.getRoot(); Path shortest = Ordering.from(length()).min(paths); for (Path part : shortest) { Path possiblePrefix = prefix.resolve(part); if (paths.stream().allMatch(startsWith(possiblePrefix))) { prefix = possiblePrefix; } else { break; } } return prefix; }
Example 4
Source File: ParserService.java From AsciidocFX with Apache License 2.0 | 6 votes |
private void applyForEachInPath(List<Path> pathList, Consumer<Path> consumer, Path root) { Path workDirRoot = root.getRoot(); for (Path path : pathList) { Path includePath = null; if (workDirRoot.equals(path.getRoot())) { includePath = root.relativize(path); } else { includePath = path.toAbsolutePath(); } if (Objects.nonNull(includePath)) { consumer.accept(includePath); } } }
Example 5
Source File: AbstractFullDistribZkTestBase.java From lucene-solr with Apache License 2.0 | 6 votes |
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(); }
Example 6
Source File: PropertyConfigHandlerTest.java From docker-maven-plugin with Apache License 2.0 | 6 votes |
@Test public void testBuildFromDockerFileMerged() { imageConfiguration = new ImageConfiguration.Builder() .name("myimage") .externalConfig(externalConfigMode(PropertyMode.Override)) .buildConfig(new BuildImageConfiguration.Builder() .dockerFile("/some/path") .cacheFrom((Arrays.asList("foo/bar:latest"))) .build() ) .build(); List<ImageConfiguration> configs = resolveImage( imageConfiguration, props() ); assertEquals(1, configs.size()); BuildImageConfiguration buildConfiguration = configs.get(0).getBuildConfiguration(); assertNotNull(buildConfiguration); buildConfiguration.initAndValidate(null); Path absolutePath = Paths.get(".").toAbsolutePath(); String expectedPath = absolutePath.getRoot() + "some" + File.separator + "path"; assertEquals(expectedPath, buildConfiguration.getDockerFile().getAbsolutePath()); }
Example 7
Source File: PathOps.java From yajsync with GNU General Public License v3.0 | 6 votes |
public static Path subtractPathOrNull(Path parent, Path sub) { if (!parent.endsWith(sub)) { throw new IllegalArgumentException(String.format( "%s is not a parent path of %s", parent, sub)); } if (parent.getNameCount() == sub.getNameCount()) { return parent.getRoot(); // NOTE: return null if parent has no root } Path res = parent.subpath(0, parent.getNameCount() - sub.getNameCount()); if (parent.isAbsolute()) { return parent.getRoot().resolve(res); } else { return res; } }
Example 8
Source File: FileHandlerSymlinksTestCase.java From quarkus-http with Apache License 2.0 | 6 votes |
@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)); }
Example 9
Source File: PathOps.java From yajsync with GNU General Public License v3.0 | 5 votes |
private static Path joinPaths(Path path, List<Path> paths) { Path empty = path.getFileSystem().getPath(Text.EMPTY); Path result = path.isAbsolute() ? path.getRoot() : empty; for (Path p : paths) { result = result.resolve(p); } return result; }
Example 10
Source File: PathTester.java From jimfs with Apache License 2.0 | 5 votes |
private void testSubpaths(Path path) { if (path.getRoot() == null) { assertEquals(path, path.subpath(0, path.getNameCount())); } if (path.getNameCount() > 1) { String stringWithoutRoot = root == null ? string : string.substring(root.length()); // test start + 1 to end and start to end - 1 subpaths... this recursively tests all subpaths // actually tests most possible subpaths multiple times but... eh Path startSubpath = path.subpath(1, path.getNameCount()); List<String> startNames = ImmutableList.copyOf(Splitter.on('/').split(stringWithoutRoot)) .subList(1, path.getNameCount()); new PathTester(pathService, Joiner.on('/').join(startNames)) .names(startNames) .test(startSubpath); Path endSubpath = path.subpath(0, path.getNameCount() - 1); List<String> endNames = ImmutableList.copyOf(Splitter.on('/').split(stringWithoutRoot)) .subList(0, path.getNameCount() - 1); new PathTester(pathService, Joiner.on('/').join(endNames)).names(endNames).test(endSubpath); } }
Example 11
Source File: BuckUnixPathTest.java From buck with Apache License 2.0 | 5 votes |
@Test @Parameters({",null", "/,/", "a,null", "/a,/", "a/b/c,null", "/a/b/c,/"}) public void getRootMethod(String data, String expected) { Path path = BuckUnixPathUtils.createPath(data); Path root = path.getRoot(); if (expected.equals("null")) { assertNull(root); } else { assertEquals(expected, root.toString()); } }
Example 12
Source File: IgniteKernal.java From ignite with Apache License 2.0 | 5 votes |
/** * @param clsPathEntry Classpath string to process. * @param clsPathContent StringBuilder to attach path to. */ private void ackClassPathWildCard(String clsPathEntry, SB clsPathContent) { final int lastSeparatorIdx = clsPathEntry.lastIndexOf(File.separator); final int asteriskIdx = clsPathEntry.indexOf('*'); //just to log possibly incorrent entries to err if (asteriskIdx >= 0 && asteriskIdx < lastSeparatorIdx) throw new RuntimeException("Could not parse classpath entry"); final int fileMaskFirstIdx = lastSeparatorIdx + 1; final String fileMask = (fileMaskFirstIdx >= clsPathEntry.length()) ? "*.jar" : clsPathEntry.substring(fileMaskFirstIdx); Path path = Paths.get(lastSeparatorIdx > 0 ? clsPathEntry.substring(0, lastSeparatorIdx) : ".") .toAbsolutePath() .normalize(); if (lastSeparatorIdx == 0) path = path.getRoot(); try { DirectoryStream<Path> files = Files.newDirectoryStream(path, fileMask); for (Path f : files) { String s = f.toString(); if (s.toLowerCase().endsWith(".jar")) clsPathContent.a(f.toString()).a(";"); } } catch (IOException e) { throw new UncheckedIOException(e); } }
Example 13
Source File: Resources.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
/** * Map a resource name to a "safe" file path. Returns {@code null} if * the resource name cannot be converted into a "safe" file path. * * Resource names with empty elements, or elements that are "." or ".." * are rejected, as are resource names that translates to a file path * with a root component. */ private static Path toSafeFilePath(FileSystem fs, String name) { // scan elements of resource name int next; int off = 0; while ((next = name.indexOf('/', off)) != -1) { int len = next - off; if (!mayTranslate(name, off, len)) { return null; } off = next + 1; } int rem = name.length() - off; if (!mayTranslate(name, off, rem)) { return null; } // convert to file path Path path; if (File.separatorChar == '/') { path = fs.getPath(name); } else { // not allowed to embed file separators if (name.contains(File.separator)) return null; path = fs.getPath(name.replace('/', File.separatorChar)); } // file path not allowed to have root component return (path.getRoot() == null) ? path : null; }
Example 14
Source File: Resources.java From Bytecoder with Apache License 2.0 | 5 votes |
/** * Map a resource name to a "safe" file path. Returns {@code null} if * the resource name cannot be converted into a "safe" file path. * * Resource names with empty elements, or elements that are "." or ".." * are rejected, as are resource names that translates to a file path * with a root component. */ private static Path toSafeFilePath(FileSystem fs, String name) { // scan elements of resource name int next; int off = 0; while ((next = name.indexOf('/', off)) != -1) { int len = next - off; if (!mayTranslate(name, off, len)) { return null; } off = next + 1; } int rem = name.length() - off; if (!mayTranslate(name, off, rem)) { return null; } // convert to file path Path path; if (File.separatorChar == '/') { path = fs.getPath(name); } else { // not allowed to embed file separators if (name.contains(File.separator)) return null; path = fs.getPath(name.replace('/', File.separatorChar)); } // file path not allowed to have root component return (path.getRoot() == null) ? path : null; }
Example 15
Source File: TlsToolkitStandaloneCommandLine.java From localization_nifi with Apache License 2.0 | 5 votes |
protected static String calculateDefaultOutputDirectory(Path currentPath) { Path currentAbsolutePath = currentPath.toAbsolutePath(); Path parent = currentAbsolutePath.getParent(); if (parent == currentAbsolutePath.getRoot()) { return parent.toString(); } else { Path currentNormalizedPath = currentAbsolutePath.normalize(); return "../" + currentNormalizedPath.getFileName().toString(); } }
Example 16
Source File: ConfigChannelSaltManager.java From uyuni with GNU General Public License v2.0 | 5 votes |
/** * Gets the salt URI for given file. * * @param file the file * @return the salt uri for the file (starting with salt://) */ public String getSaltUriForConfigFile(ConfigFile file) { Path filePath = Paths.get(file.getConfigFileName().getPath()); if (filePath.getRoot() != null) { filePath = filePath.getRoot().relativize(filePath); } return SALT_FS_PREFIX + getChannelRelativePath(file.getConfigChannel()) .resolve(filePath); }
Example 17
Source File: ConfigChannelSaltManager.java From uyuni with GNU General Public License v2.0 | 5 votes |
/** * Get the file params list for salt * @param file file * @return List of params map */ private List<Map<String, Object>> getFileStateParams(ConfigFile file) { Path filePath = Paths.get(file.getConfigFileName().getPath()); if (filePath.getRoot() != null) { filePath = filePath.getRoot().relativize(filePath); } List<Map<String, Object>> fileParams = new LinkedList<>(); fileParams.add(singletonMap("name", file.getConfigFileName().getPath())); fileParams.add(singletonMap("source", getSaltUriForConfigFile(file))); fileParams.add(singletonMap("makedirs", true)); fileParams.addAll(getModeParams(file.getLatestConfigRevision().getConfigInfo())); return fileParams; }
Example 18
Source File: FileUtil.java From tesb-studio-se with Apache License 2.0 | 4 votes |
public static String getPathPrefixInArchive(String zip) throws IOException { try (ZipInputStream zipStream = new ZipInputStream(new FileInputStream(zip), Charset.forName("UTF-8"))) { ZipEntry zentry = zipStream.getNextEntry(); if (zentry == null) { return null; } String name = zentry.getName(); Path path = Paths.get(name); String prefix = path.getRoot() == null ? path.toString() : path.getRoot().toString(); boolean isRuntime = false; boolean isESB = false; Set<Path> toLookFor = new HashSet<>(); for (String contF : CONTAINER_FILES) { toLookFor.add(Paths.get(contF)); } while (zentry != null && !toLookFor.isEmpty()) { Path zpath = Paths.get(zentry.getName()); if (zpath.getNameCount() < 2) { zentry = zipStream.getNextEntry(); continue; } if (toLookFor.remove(zpath.subpath(1, zpath.getNameCount()))) { isRuntime = true; } else if ("container".equals(zpath.getName(1).toString()) && zpath.getNameCount() > 2 && toLookFor.remove(zpath.subpath(2, zpath.getNameCount()))) { isESB = true; } zentry = zipStream.getNextEntry(); } if (!toLookFor.isEmpty()) { System.out.println("Some elements were not found: " + toLookFor); return null; } if (isESB == isRuntime) { System.out.println("ESB and Runtime is the same: " + isESB); return null; } return isESB ? Paths.get(prefix, "container").toString().replace('\\', '/') : prefix; } }
Example 19
Source File: TreeTables.java From sis with Apache License 2.0 | 4 votes |
/** * Finds the node for the given path, or creates a new node if none exists. * First, this method searches in the node {@linkplain TreeTable.Node#getChildren() * children collection} for the root element of the given path. If no such node is found, * a {@linkplain TreeTable.Node#newChild() new child} is created. Then this method * repeats the process (searching in the children of the child for the second path * element), until the last path element is reached. * * <p>For example if the given path is {@code "users/alice/data"}, then this method * finds or creates the nodes for the following tree, where {@code "from"} is the * node given in argument to this method:</p> * * {@preformat text * from * └─users * └─alice * └─data * } * * @param from the root node from which to start the search. * @param column the column containing the file name. * @param path the path for which to find or create a node. * @return the node for the given path, either as an existing node or a new node. */ public static TreeTable.Node nodeForPath(TreeTable.Node from, final TableColumn<? super String> column, final Path path) { final Path parent = path.getParent(); if (parent != null) { from = nodeForPath(from, column, parent); } Path filename = path.getFileName(); if (filename == null) { filename = path.getRoot(); } final String name = filename.toString(); for (final TreeTable.Node child : from.getChildren()) { if (name.equals(child.getValue(column))) { return child; } } from = from.newChild(); from.setValue(column, name); return from; }
Example 20
Source File: FileHandler.java From Bytecoder with Apache License 2.0 | 4 votes |
static File generate(String pat, int count, int generation, int unique) throws IOException { Path path = Paths.get(pat); Path result = null; boolean sawg = false; boolean sawu = false; StringBuilder word = new StringBuilder(); Path prev = null; for (Path elem : path) { if (prev != null) { prev = prev.resolveSibling(word.toString()); result = result == null ? prev : result.resolve(prev); } String pattern = elem.toString(); int ix = 0; word.setLength(0); while (ix < pattern.length()) { char ch = pattern.charAt(ix); ix++; char ch2 = 0; if (ix < pattern.length()) { ch2 = Character.toLowerCase(pattern.charAt(ix)); } if (ch == '%') { if (ch2 == 't') { String tmpDir = System.getProperty("java.io.tmpdir"); if (tmpDir == null) { tmpDir = System.getProperty("user.home"); } result = Paths.get(tmpDir); ix++; word.setLength(0); continue; } else if (ch2 == 'h') { result = Paths.get(System.getProperty("user.home")); if (jdk.internal.misc.VM.isSetUID()) { // Ok, we are in a set UID program. For safety's sake // we disallow attempts to open files relative to %h. throw new IOException("can't use %h in set UID program"); } ix++; word.setLength(0); continue; } else if (ch2 == 'g') { word = word.append(generation); sawg = true; ix++; continue; } else if (ch2 == 'u') { word = word.append(unique); sawu = true; ix++; continue; } else if (ch2 == '%') { word = word.append('%'); ix++; continue; } } word = word.append(ch); } prev = elem; } if (count > 1 && !sawg) { word = word.append('.').append(generation); } if (unique > 0 && !sawu) { word = word.append('.').append(unique); } if (word.length() > 0) { String n = word.toString(); Path p = prev == null ? Paths.get(n) : prev.resolveSibling(n); result = result == null ? p : result.resolve(p); } else if (result == null) { result = Paths.get(""); } if (path.getRoot() == null) { return result.toFile(); } else { return path.getRoot().resolve(result).toFile(); } }