下面列出了java.nio.file.Path#getNameCount ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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;
}
}
/**
* Appends a new component to the FolderComposite. Inexistent folders are added on the
* fly. Existing items are replaced. Triggers updates of content and name hashes.
*/
public synchronized void putComponent(Path remainingPath, FileComponent component) {
remainingPath = stripOffPrefix(remainingPath, getPath());
Path nextLevelPath = remainingPath.getName(0);
// if we are at the last recursion, perform the add, else recursively continue
if (remainingPath.getNameCount() == 1) {
deleteComponent(nextLevelPath);
addComponentToChildren(nextLevelPath, component);
} else {
FileComponent nextLevel = children.get(nextLevelPath);
if (nextLevel == null) {
// next level does not exist yet, create it
Path childPath = constructFullPath(nextLevelPath);
nextLevel = new FolderComposite(childPath, updateContentHash);
nextLevel.getAction().setFileEventManager(getAction().getFileEventManager());
addComponentToChildren(nextLevelPath, nextLevel);
}
Path newRemainingPath = remainingPath.subpath(1, remainingPath.getNameCount());
((FolderComposite) nextLevel).putComponent(newRemainingPath, component);
}
}
private static MCRFile getMCRFile(SecureDirectoryStream ds, Path relativePath) throws IOException {
MCRStoredNode storedNode = ds.resolve(relativePath);
if (storedNode != null) {
throw new FileAlreadyExistsException(ds.dirPath.resolve(relativePath).toString());
}
//does not exist, have to create
MCRStoredNode parent = ds.dir;
if (relativePath.getNameCount() > 1) {
parent = (MCRStoredNode) parent.getNodeByPath(relativePath.getParent().toString());
if (parent == null) {
throw new NoSuchFileException(ds.dirPath.resolve(relativePath.getParent()).toString());
}
if (!(parent instanceof MCRDirectory)) {
throw new NotDirectoryException(ds.dirPath.resolve(relativePath.getParent()).toString());
}
}
return ((MCRDirectory) parent).createFile(relativePath.getFileName().toString());
}
private static File normalize(File filename) {
final Path path1 = toFile(SARLConfig.FOLDER_SOURCE_SARL).toPath();
final Path path2 = toFile(SARLConfig.FOLDER_SOURCE_JAVA).toPath();
final Path path3 = toFile(SARLConfig.FOLDER_TEST_SOURCE_SARL).toPath();
final Path path = filename.toPath();
Path toRemove = null;
if (path.endsWith(path1)) {
toRemove = path1;
} else if (path.endsWith(path2)) {
toRemove = path2;
} else if (path.endsWith(path3)) {
toRemove = path3;
}
if (toRemove != null) {
final int nb = toRemove.getNameCount();
File res = filename;
for (int i = 0; i < nb; ++i) {
res = res.getParentFile();
}
return res;
}
return filename;
}
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);
}
}
private void removeIncompleteContent(final String containerName, final Path containerPath, final Path fileToRemove) {
if (Files.isDirectory(fileToRemove)) {
final Path lastPathName = fileToRemove.subpath(1, fileToRemove.getNameCount());
final String fileName = lastPathName.toFile().getName();
if (fileName.equals(ARCHIVE_DIR_NAME)) {
return;
}
final File[] children = fileToRemove.toFile().listFiles();
if (children != null) {
for (final File child : children) {
removeIncompleteContent(containerName, containerPath, child.toPath());
}
}
return;
}
final Path relativePath = containerPath.relativize(fileToRemove);
final Path sectionPath = relativePath.subpath(0, 1);
if (relativePath.getNameCount() < 2) {
return;
}
final Path idPath = relativePath.subpath(1, relativePath.getNameCount());
final String id = idPath.toFile().getName();
final String sectionName = sectionPath.toFile().getName();
final ResourceClaim resourceClaim = resourceClaimManager.newResourceClaim(containerName, sectionName, id, false, false);
if (resourceClaimManager.getClaimantCount(resourceClaim) == 0) {
removeIncompleteContent(fileToRemove);
}
}
private TreeNodeBuilder getMutableParentDirectory(Path pathFragment) {
int segments = pathFragment.getNameCount();
if (segments == getPathSegments() + 1) {
return this;
}
return getMutableDirectory(pathFragment).getMutableParentDirectory(pathFragment);
}
private void removeIncompleteContent(final String containerName, final Path containerPath, final Path fileToRemove) {
if (Files.isDirectory(fileToRemove)) {
final Path lastPathName = fileToRemove.subpath(1, fileToRemove.getNameCount());
final String fileName = lastPathName.toFile().getName();
if (fileName.equals(ARCHIVE_DIR_NAME)) {
return;
}
final File[] children = fileToRemove.toFile().listFiles();
if (children != null) {
for (final File child : children) {
removeIncompleteContent(containerName, containerPath, child.toPath());
}
}
return;
}
final Path relativePath = containerPath.relativize(fileToRemove);
final Path sectionPath = relativePath.subpath(0, 1);
if (relativePath.getNameCount() < 2) {
return;
}
final Path idPath = relativePath.subpath(1, relativePath.getNameCount());
final String id = idPath.toFile().getName();
final String sectionName = sectionPath.toFile().getName();
final ResourceClaim resourceClaim = resourceClaimManager.newResourceClaim(containerName, sectionName, id, false, false);
if (resourceClaimManager.getClaimantCount(resourceClaim) == 0) {
removeIncompleteContent(fileToRemove);
}
}
/**
* Returns true is some element of path inside base path is a symlink.
*/
private SymlinkResult getSymlinkBase(final String base, final Path file) throws IOException {
int nameCount = file.getNameCount();
Path root = Paths.get(base);
int rootCount = root.getNameCount();
Path f = file;
for (int i = nameCount - 1; i>=0; i--) {
if (Files.isSymbolicLink(f)) {
return new SymlinkResult(i+1 > rootCount, f);
}
f = f.getParent();
}
return null;
}
private static boolean canMergeWithKeepingPackage(
Path currentPath, Path parentPackage, IjFolder child, PackagePathCache packagePathCache) {
Optional<Path> childPackageOptional = packagePathCache.lookup(child);
if (!childPackageOptional.isPresent()) {
return false;
}
Path childPackage = childPackageOptional.get();
int pathDifference = child.getPath().getNameCount() - currentPath.getNameCount();
Preconditions.checkState(pathDifference == 1);
if (childPackage.getNameCount() == 0) {
return false;
}
return MorePaths.getParentOrEmpty(childPackage).equals(parentPackage);
}
public static int commonSuffixLength(Path a, Path b) {
int count = 0;
while (count < a.getNameCount() && count < b.getNameCount()) {
if (!a.getName(a.getNameCount() - count - 1)
.equals(b.getName(b.getNameCount() - count - 1))) {
break;
}
count++;
}
return count;
}
@Override
protected Path validateRelativePath(Path path) throws ValidationException {
if(path.getNameCount() != 1) {
throw createException(Severity.ERROR, ValidationMessages.Path_NotAbsoluteNorSingle(path));
}
return path;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (file.getNameCount() > 2 && file.toString().endsWith(".class")) {
// /modules/jdk.rmic/sun/tools/tree/CaseStatement.class
String moduleName = file.getName(1).toString(); // jdk.rmic
Path moduleRootPath = file.subpath(0, 2); // /modules/jdk.rmic
if (!modules.containsKey(moduleName)) {
modules.put(moduleName, moduleRootPath);
}
}
return FileVisitResult.CONTINUE;
}
@Test
public void testPutFileInSubfolder() throws IOException {
Path fileSub = Paths.get("1", "2", "3", "file.txt");
Path file = rootPath.resolve(fileSub);
FileComponent f = createFile(file);
rootFolder.putComponent(file, f);
// check file
FileComponent parent = rootFolder.getComponent(fileSub.getParent());
assertEquals(parent, f.getParent());
assertEquals(f.getPath(), file);
// check ancestors -- for each element of the path:
FileComponent previous = rootFolder;
FileComponent current = null;
for (int i = 1; i < fileSub.getNameCount(); ++i) {
Path sub = rootPath.resolve(fileSub.subpath(0, i));
// check parent
current = rootFolder.getComponent(sub);
assertNotNull(current);
assertEquals(previous, current.getParent());
assertEquals(sub, current.getPath());
// check children
assertTrue(previous.isFolder());
FolderComposite folder = (FolderComposite) previous;
assertTrue(folder.getChildren().size() == 1);
assertTrue(folder.getChildren().containsKey(sub.getFileName()));
assertEquals(folder.getChildren().get(sub.getFileName()), current);
// check content hash -- parent includes hash of child
String contentHash = computeHashOfString(current.getContentHash());
assertEquals(previous.getContentHash(), contentHash);
// check name hash
String structureHash = computeHashOfString(current.getPath().getFileName().toString());
assertEquals(((FolderComposite)previous).getStructureHash(), structureHash);
previous = current;
}
}
/**
* In-thread code.
* @return path to the downloaded data.
*/
@Override
public DownloadResult call() throws Exception
{
Path out_file_path;
if (tempDir != null)
{
out_file_path = Files.createTempFile(tempDir, null, TMP_FILE_SUFFIX);
}
else
{
out_file_path = Files.createTempFile(null, TMP_FILE_SUFFIX);
}
try (FileChannel output = FileChannel.open(out_file_path, StandardOpenOption.WRITE))
{
// Computes the data's md5 sum on the fly
MessageDigest md = MessageDigest.getInstance("MD5");
DigestIWC decorator = new DigestIWC(md, output);
long delta = System.currentTimeMillis();
HttpResponse response = http_client.interruptibleGet(this.urlToDownload, decorator);
LOGGER.debug(String.format("Downloaded '%s' in %d ms",
this.urlToDownload, System.currentTimeMillis() - delta));
// If the response's status code is not 200, something wrong happened
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
{
Formatter ff = new Formatter();
ff.format("Cannot download from %s,"
+ " remote host returned message '%s' (HTTP%d)",
this.urlToDownload,
response.getStatusLine().getReasonPhrase(),
response.getStatusLine().getStatusCode());
throw new IOException(ff.out().toString());
}
// Gets the filename from the HTTP header field `Content-Disposition'
String contdis = response.getFirstHeader("Content-Disposition").getValue();
if (contdis != null && !contdis.isEmpty())
{
Matcher m = pattern.matcher(contdis);
if (m.find())
{
String filename = m.group(1);
if (filename != null && !filename.isEmpty())
{
decorator.close();
// Renames the downloaded file
Path rpath = Paths.get(filename);
if (rpath.isAbsolute() || rpath.getNameCount() != 1)
{
String msg = String.format("invalid filename '%s' from %s",
filename, this.urlToDownload);
throw new IllegalStateException(msg);
}
Path dest = out_file_path.resolveSibling(rpath);
Files.move(out_file_path, dest, StandardCopyOption.ATOMIC_MOVE);
out_file_path = dest;
}
}
}
DownloadResult res = new DownloadResult(
out_file_path,
response.getEntity().getContentType().getValue(),
response.getEntity().getContentLength(),
md.digest());
return res;
}
catch (Exception e)
{
// cleanup if an error occured
if (Files.exists(out_file_path))
{
Files.delete(out_file_path);
}
throw e;
}
}
private static void rmdirs(Path path) throws IOException {
while (path != null && path.getNameCount() != 0) {
Files.delete(path);
path = path.getParent();
}
}
public static Pair<Path, Path> stripCommonSuffix(Path a, Path b) {
int count = commonSuffixLength(a, b);
return new Pair<>(
count == a.getNameCount() ? emptyOf(a) : a.subpath(0, a.getNameCount() - count),
count == b.getNameCount() ? emptyOf(b) : b.subpath(0, b.getNameCount() - count));
}
public static Path getWildcardPath(Path path) {
int nameCount = path.getNameCount();
int wildcardIdx = 0;
for (; wildcardIdx < nameCount && !hasGlobWildcard(path.getName(wildcardIdx).toString()); wildcardIdx++);
return getSubPath(path, wildcardIdx, nameCount, false);
}
/**
* Returns a child path relative to a base path. This is similar to `Path.relativize`, but
* supports base paths that start with "..", even in Java 11. JCL implementations of
* `Path.relativize` support base paths like this in Java 8, but not in Java 11.
*
* @param basePath the path against which childPath will be relativized
* @param childPath the path to relativize against {@code basePath}
* @return {@code childPath} relativized against {@code basePath}
*/
public static Path relativizeWithDotDotSupport(Path basePath, Path childPath) {
if (basePath instanceof BuckUnixPath) {
// Call our more efficient implementation if using Buck's own filesystem provider.
return basePath.relativize(childPath);
}
if (basePath.equals(childPath)) {
return basePath.getFileSystem().getPath("");
}
if (basePath.isAbsolute() != childPath.isAbsolute()) {
throw new IllegalArgumentException("Expected paths to be of the same type");
}
// Skip past equal prefixes.
int idx = 0;
while (idx < basePath.getNameCount()
&& idx < childPath.getNameCount()
&& basePath.getName(idx).equals(childPath.getName(idx))) {
idx++;
}
// Add ".."s to get to the root of the remainder of the base path.
StringBuilder result = new StringBuilder();
for (int i = idx; i < basePath.getNameCount(); i++) {
if (!basePath.getName(i).toString().isEmpty()) {
result.append("..");
result.append(File.separatorChar);
}
}
// Now add the remainder of the child path.
if (idx < childPath.getNameCount()) {
result.append(childPath.getName(idx).toString());
}
for (int i = idx + 1; i < childPath.getNameCount(); i++) {
result.append(File.separatorChar);
result.append(childPath.getName(i).toString());
}
return basePath.getFileSystem().getPath(result.toString());
}
private static boolean isEmpty(Path test) {
return test instanceof MCRPath && ((MCRPath) test).isEmpty()
|| (test.getNameCount() == 1 && test.getName(0).toString().isEmpty());
}