diff --git a/platform/core.startup/test/unit/src/org/netbeans/core/startup/layers/BinaryFSBehindMultiFSTest.java b/platform/core.startup/test/unit/src/org/netbeans/core/startup/layers/BinaryFSBehindMultiFSTest.java index 59daa51a3dcf..4164453fcd2e 100644 --- a/platform/core.startup/test/unit/src/org/netbeans/core/startup/layers/BinaryFSBehindMultiFSTest.java +++ b/platform/core.startup/test/unit/src/org/netbeans/core/startup/layers/BinaryFSBehindMultiFSTest.java @@ -27,6 +27,7 @@ import org.netbeans.junit.NbTestSuite; import org.openide.filesystems.AttributesTestHidden; import org.openide.filesystems.FileObjectTestHid; +import org.openide.filesystems.PathTestHid; import org.openide.filesystems.FileSystem; import org.openide.filesystems.FileSystemFactoryHid; import org.openide.filesystems.FileSystemTestHid; @@ -49,6 +50,7 @@ public static Test suite() { NbTestSuite suite = new NbTestSuite(); suite.addTestSuite(FileSystemTestHid.class); suite.addTestSuite(FileObjectTestHid.class); + suite.addTestSuite(PathTestHid.class); suite.addTestSuite(AttributesTestHidden.class); suite.addTestSuite(XMLFileSystemTestHid.class); diff --git a/platform/core.startup/test/unit/src/org/netbeans/core/startup/layers/BinaryFSTest.java b/platform/core.startup/test/unit/src/org/netbeans/core/startup/layers/BinaryFSTest.java index ea84ff91dc72..b25b3efb0482 100644 --- a/platform/core.startup/test/unit/src/org/netbeans/core/startup/layers/BinaryFSTest.java +++ b/platform/core.startup/test/unit/src/org/netbeans/core/startup/layers/BinaryFSTest.java @@ -26,6 +26,7 @@ import org.netbeans.junit.NbTestSuite; import org.openide.filesystems.AttributesTestHidden; import org.openide.filesystems.FileObjectTestHid; +import org.openide.filesystems.PathTestHid; import org.openide.filesystems.FileSystem; import org.openide.filesystems.FileSystemFactoryHid; import org.openide.filesystems.FileSystemTestHid; @@ -47,6 +48,7 @@ public static Test suite() { NbTestSuite suite = new NbTestSuite(); suite.addTestSuite(FileSystemTestHid.class); suite.addTestSuite(FileObjectTestHid.class); + suite.addTestSuite(PathTestHid.class); suite.addTestSuite(AttributesTestHidden.class); suite.addTestSuite(XMLFileSystemTestHid.class); diff --git a/platform/masterfs/test/unit/src/org/netbeans/modules/masterfs/filebasedfs/FileBasedFileSystemTest.java b/platform/masterfs/test/unit/src/org/netbeans/modules/masterfs/filebasedfs/FileBasedFileSystemTest.java index aa6427dc0d60..abbd13cc2747 100644 --- a/platform/masterfs/test/unit/src/org/netbeans/modules/masterfs/filebasedfs/FileBasedFileSystemTest.java +++ b/platform/masterfs/test/unit/src/org/netbeans/modules/masterfs/filebasedfs/FileBasedFileSystemTest.java @@ -54,6 +54,7 @@ static NbTestSuite suite(boolean created) { NbTestSuite suite = new NbTestSuite(); suite.addTestSuite(FileSystemTestHid.class); suite.addTestSuite(FileObjectTestHid.class); + suite.addTestSuite(PathTestHid.class); suite.addTestSuite(URLMapperTestHidden.class); suite.addTestSuite(FileUtilTestHidden.class); suite.addTestSuite(FileUtilJavaIOFileHidden.class); diff --git a/platform/openide.filesystems/apichanges.xml b/platform/openide.filesystems/apichanges.xml index 8872f3e0fb66..0d7b2aee7a89 100644 --- a/platform/openide.filesystems/apichanges.xml +++ b/platform/openide.filesystems/apichanges.xml @@ -19,12 +19,26 @@ under the License. --> - + Filesystems API + + + FileUtil.toPath works for every file object + + + + + + FileUtil.toPath + now returns a non-null Path instance + for all file objects, even for virtual ones. + + + FileObject copy preserves source posix permissions. diff --git a/platform/openide.filesystems/manifest.mf b/platform/openide.filesystems/manifest.mf index 8ac6f2fa4277..b27c2de73c58 100644 --- a/platform/openide.filesystems/manifest.mf +++ b/platform/openide.filesystems/manifest.mf @@ -2,6 +2,6 @@ Manifest-Version: 1.0 OpenIDE-Module: org.openide.filesystems OpenIDE-Module-Localizing-Bundle: org/openide/filesystems/Bundle.properties OpenIDE-Module-Layer: org/openide/filesystems/resources/layer.xml -OpenIDE-Module-Specification-Version: 9.48 +OpenIDE-Module-Specification-Version: 9.50 diff --git a/platform/openide.filesystems/src/org/netbeans/modules/openide/filesystems/declmime/NioFileTypeDetector.java b/platform/openide.filesystems/src/org/netbeans/modules/openide/filesystems/declmime/NioFileTypeDetector.java new file mode 100644 index 000000000000..ec09be57ea18 --- /dev/null +++ b/platform/openide.filesystems/src/org/netbeans/modules/openide/filesystems/declmime/NioFileTypeDetector.java @@ -0,0 +1,35 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.netbeans.modules.openide.filesystems.declmime; + +import java.nio.file.Path; +import java.nio.file.spi.FileTypeDetector; + +import org.openide.filesystems.FileObject; +import org.openide.filesystems.FileUtil; +import org.openide.util.lookup.ServiceProvider; + +@ServiceProvider(service = FileTypeDetector.class, position = 100) +public final class NioFileTypeDetector extends FileTypeDetector { + @Override + public String probeContentType(Path path) { + FileObject fileObject = FileUtil.toFileObject(path); + return fileObject == null ? null : fileObject.getMIMEType(); + } +} diff --git a/platform/openide.filesystems/src/org/openide/filesystems/FileSystem.java b/platform/openide.filesystems/src/org/openide/filesystems/FileSystem.java index cf298713c856..11a4952318d9 100644 --- a/platform/openide.filesystems/src/org/openide/filesystems/FileSystem.java +++ b/platform/openide.filesystems/src/org/openide/filesystems/FileSystem.java @@ -170,6 +170,7 @@ public String annotateNameHtml(String name, Set files) { private transient ListenerList fileStatusList; private transient ListenerList vetoableChangeList; private transient PropertyChangeSupport changeSupport; + private transient NioFsForFileSystem nioFs; /** Default constructor. */ public FileSystem() { @@ -737,6 +738,13 @@ public final void removeFileChangeListener(FileChangeListener fcl) { void waitRefreshed() { } + final synchronized NioFsForFileSystem getNioFs() { + if (nioFs == null) { + nioFs = new NioFsForFileSystem(this); + } + return nioFs; + } + /** An action that it is to be called atomically with respect to filesystem event notification. * During its execution (via {@link FileSystem#runAtomicAction runAtomicAction}) * no events about changes in filesystems are fired. diff --git a/platform/openide.filesystems/src/org/openide/filesystems/FileUtil.java b/platform/openide.filesystems/src/org/openide/filesystems/FileUtil.java index e2ebc7aa6200..f98d4d0f1d41 100644 --- a/platform/openide.filesystems/src/org/openide/filesystems/FileUtil.java +++ b/platform/openide.filesystems/src/org/openide/filesystems/FileUtil.java @@ -833,16 +833,30 @@ public static File toFile(FileObject fo) { return retVal; } - /** Finds appropriate java.nio.file.Path to FileObject if possible. - * If not possible then null is returned. - * This is the inverse operation of {@link #toFileObject}. - * @param fo FileObject whose corresponding Path will be looked for - * @return java.nio.file.Path or null if no corresponding File exists. + /** Finds appropriate {@link Path} for given {@code FileObject}. + * Since version 9.50 it is guaranteed that the return value + * will never be {@code null} for an object with valid {@link FileObject#getFileSystem()}. + * A fully functional {@link Path} + * instance is created even for fully virtual {@code FileObject}s. + * + * This is the inverse operation of {@link #toFileObject(java.nio.file.Path) }. + * @param fo object to find corresponding Path for + * @return {@link Path} for the {@code FileObject} never {@code null} + * * @since 9.32 */ public static Path toPath(FileObject fo) { + Parameters.notNull("fo", fo); File f = toFile(fo); - return f != null ? f.toPath() : null; + if (f != null) { + return f.toPath(); + } + try { + var nioFs = fo.getFileSystem().getNioFs(); + return NioPathForFileObject.create(fo, nioFs); + } catch (FileStateInvalidException ex) { + throw new IllegalStateException("FileObject has no valid filesystem", ex); + } } /** @@ -917,8 +931,12 @@ public static FileObject toFileObject(File file) { * @param path the {@link Path} to be converted * @return the {@link FileObject} representing the {@code path} or {@code null} * @since 9.32 + * @see #toPath */ public static FileObject toFileObject(Path path) { + if (path instanceof NioPathForFileObject nioPath) { + return nioPath.getFileObject(); + } try { return toFileObject(path.toFile()); } catch (UnsupportedOperationException ex) { diff --git a/platform/openide.filesystems/src/org/openide/filesystems/NioFsForFileSystem.java b/platform/openide.filesystems/src/org/openide/filesystems/NioFsForFileSystem.java new file mode 100644 index 000000000000..7def244d3b40 --- /dev/null +++ b/platform/openide.filesystems/src/org/openide/filesystems/NioFsForFileSystem.java @@ -0,0 +1,135 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.openide.filesystems; + +import java.io.IOException; +import java.nio.file.FileStore; +import java.nio.file.FileSystem; +import java.nio.file.Path; +import java.nio.file.PathMatcher; +import java.nio.file.WatchService; +import java.nio.file.attribute.UserPrincipalLookupService; +import java.nio.file.spi.FileSystemProvider; +import java.util.Collections; +import java.util.Set; + +final class NioFsForFileSystem extends FileSystem { + private final org.openide.filesystems.FileSystem fileSystem; + private final NioPathProvider provider; + + NioFsForFileSystem(org.openide.filesystems.FileSystem fileSystem) { + this.fileSystem = fileSystem; + this.provider = new NioPathProvider(this); + } + + org.openide.filesystems.FileSystem getFileSystem() { + return fileSystem; + } + + @Override + public FileSystemProvider provider() { + return provider; + } + + @Override + public void close() { + } + + @Override + public boolean isOpen() { + return true; + } + + @Override + public boolean isReadOnly() { + return fileSystem.isReadOnly(); + } + + @Override + public String getSeparator() { + return "/"; + } + + @Override + public Iterable getRootDirectories() { + return Collections.singletonList(NioPathForFileObject.create(fileSystem.getRoot(), this)); + } + + @Override + public Iterable getFileStores() { + return Collections.emptyList(); + } + + @Override + public Set supportedFileAttributeViews() { + return Collections.singleton("basic"); + } + + @Override + public Path getPath(String first, String... more) { + StringBuilder value = new StringBuilder(first); + for (String part : more) { + if (!value.isEmpty() && value.charAt(value.length() - 1) != '/') { + value.append('/'); + } + value.append(part); + } + String normalized = normalizedPath(value.toString()); + FileObject fo = fileSystem.findResource(normalized); + String name = normalizeName(value.toString()); + if (!value.toString().startsWith("/")) { + return NioPathForFileObject.relative(fo, this, name); + } + return NioPathForFileObject.create(fo, this, name); + } + + private String normalizedPath(String value) { + if (value.isEmpty()) { + return ""; + } + String result = value.replace('\\', '/'); + while (result.startsWith("/")) { + result = result.substring(1); + } + return result; + } + + private String normalizeName(String value) { + String result = value.replace('\\', '/'); + while (result.startsWith("/")) { + result = result.substring(1); + } + return result; + } + + @Override + public PathMatcher getPathMatcher(String syntaxAndPattern) { + throw new UnsupportedOperationException("PathMatcher is not supported"); + } + + @Override + public UserPrincipalLookupService getUserPrincipalLookupService() { + throw new UnsupportedOperationException("User lookup is not supported"); + } + + @Override + public WatchService newWatchService() throws IOException { + return new NioWatchService(); + } +} diff --git a/platform/openide.filesystems/src/org/openide/filesystems/NioPathForFileObject.java b/platform/openide.filesystems/src/org/openide/filesystems/NioPathForFileObject.java new file mode 100644 index 000000000000..c1a8e2ed7d7a --- /dev/null +++ b/platform/openide.filesystems/src/org/openide/filesystems/NioPathForFileObject.java @@ -0,0 +1,373 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.openide.filesystems; + +import java.io.File; +import java.io.IOException; +import java.net.URI; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.WatchEvent; +import java.nio.file.WatchKey; +import java.nio.file.WatchService; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Objects; + +final class NioPathForFileObject implements Path { + private final FileObject fileObject; + private final NioFsForFileSystem fileSystem; + private final String name; + private final boolean absolute; + + private NioPathForFileObject(FileObject fileObject, NioFsForFileSystem fileSystem, String name) { + this(fileObject, fileSystem, name, true); + } + + private NioPathForFileObject(FileObject fileObject, NioFsForFileSystem fileSystem, String name, boolean absolute) { + this.fileObject = fileObject; + this.fileSystem = fileSystem; + this.name = normalize(name); + this.absolute = absolute; + } + + static NioPathForFileObject create(FileObject fileObject, NioFsForFileSystem fileSystem) { + return new NioPathForFileObject(fileObject, fileSystem, fullName(fileObject)); + } + + static NioPathForFileObject create(FileObject fileObject, NioFsForFileSystem fileSystem, String name) { + return new NioPathForFileObject(fileObject, fileSystem, name); + } + + static NioPathForFileObject relative(FileObject fileObject, NioFsForFileSystem fileSystem, String name) { + return new NioPathForFileObject(fileObject, fileSystem, name, false); + } + + FileObject getFileObject() { + if (!name.isEmpty()) { + FileObject resolved = fileSystem.getFileSystem().findResource(name); + if (resolved != null) { + return resolved; + } + } + return fileObject; + } + + @Override + public java.nio.file.FileSystem getFileSystem() { + return fileSystem; + } + + @Override + public boolean isAbsolute() { + return absolute; + } + + @Override + public Path getRoot() { + return create(fileSystem.getFileSystem().getRoot(), fileSystem); + } + + @Override + public Path getFileName() { + if (name.isEmpty()) { + return null; + } + int separator = name.lastIndexOf('/'); + String fileName = separator == -1 ? name : name.substring(separator + 1); + return fileName.isEmpty() ? null : relative(fileObject, fileSystem, fileName); + } + + @Override + public Path getParent() { + if (name.isEmpty()) { + return null; + } + int separator = name.lastIndexOf('/'); + if (separator == -1) { + return getRoot(); + } + String parentName = name.substring(0, separator); + FileObject parent = fileSystem.getFileSystem().findResource(parentName); + if (parent == null && fileObject != null) { + parent = fileObject.getParent(); + } + return create(parent, fileSystem, parentName); + } + + @Override + public int getNameCount() { + if (name.isEmpty()) { + return 1; + } + int count = 0; + for (String part : name.split("/")) { + if (!part.isEmpty()) { + count++; + } + } + return count; + } + + @Override + public Path getName(int index) { + if (index < 0 || index >= getNameCount()) { + throw new IllegalArgumentException("Illegal name index: " + index); + } + List names = names(); + return relative(null, fileSystem, names.get(index)); + } + + @Override + public Path subpath(int beginIndex, int endIndex) { + if (beginIndex < 0 || endIndex > getNameCount() || beginIndex >= endIndex) { + throw new IllegalArgumentException(); + } + List names = names(); + return relative(null, fileSystem, String.join("/", names.subList(beginIndex, endIndex))); + } + + @Override + public boolean startsWith(Path other) { + if (!(other instanceof NioPathForFileObject nio) || nio.fileSystem != fileSystem) { + return false; + } + if (nio.name.isEmpty()) { + return absolute; + } + return name.equals(nio.name) || name.startsWith(nio.name + "/"); + } + + @Override + public boolean startsWith(String other) { + return startsWith(fileSystem.getPath(other)); + } + + @Override + public boolean endsWith(Path other) { + if (!(other instanceof NioPathForFileObject nio) || nio.fileSystem != fileSystem) { + return false; + } + if (nio.absolute || nio.name.isEmpty()) { + return absolute == nio.absolute && name.equals(nio.name); + } + return name.equals(nio.name) || name.endsWith("/" + nio.name); + } + + @Override + public boolean endsWith(String other) { + return endsWith(fileSystem.getPath(other)); + } + + @Override + public Path normalize() { + List normalized = new ArrayList<>(); + for (String part : names()) { + if (part.isEmpty() || part.equals(".")) { + continue; + } + if (part.equals("..")) { + if (!normalized.isEmpty()) { + normalized.remove(normalized.size() - 1); + } + } else { + normalized.add(part); + } + } + String normalizedName = String.join("/", normalized); + FileObject fo = fileSystem.getFileSystem().findResource(normalizedName); + return create(fo, fileSystem, normalizedName); + } + + @Override + public Path resolve(Path other) { + if (other.isAbsolute()) { + return other; + } + if (!(other instanceof NioPathForFileObject nio)) { + return resolve(other.toString()); + } + return resolve(nio.name); + } + + @Override + public Path resolve(String other) { + if (other.isEmpty()) { + return this; + } + String result = name.isEmpty() ? normalize(other) : normalize(name + "/" + other); + FileObject fo = fileSystem.getFileSystem().findResource(result); + return create(fo, fileSystem, result); + } + + @Override + public Path resolveSibling(Path other) { + if (other.isAbsolute()) { + return other; + } + Path parent = getParent(); + return parent == null ? other : parent.resolve(other); + } + + @Override + public Path resolveSibling(String other) { + return resolveSibling(fileSystem.getPath(other)); + } + + @Override + public Path relativize(Path other) { + if (!(other instanceof NioPathForFileObject nio) || nio.fileSystem != fileSystem) { + throw new IllegalArgumentException("Cannot relativize different file systems"); + } + List base = names(); + List target = nio.names(); + int common = 0; + while (common < base.size() && common < target.size() && base.get(common).equals(target.get(common))) { + common++; + } + List result = new ArrayList<>(); + for (int i = common; i < base.size(); i++) { + result.add(".."); + } + result.addAll(target.subList(common, target.size())); + String relative = String.join("/", result); + return relative(null, fileSystem, relative.isEmpty() ? "" : relative); + } + + @Override + public URI toUri() { + return fileObject.toURI(); + } + + @Override + public Path toAbsolutePath() { + return this; + } + + @Override + public Path toRealPath(LinkOption... options) throws IOException { + if (fileObject == null) { + throw new IOException("No FileObject for " + name); + } + return normalize(); + } + + @Override + public File toFile() { + if (fileObject != null) { + File disk = FileUtil.toFile(fileObject); + if (disk != null) { + return disk; + } + } + throw new UnsupportedOperationException("Virtual FileObject has no java.io.File"); + } + + @Override + public WatchKey register(WatchService watcher, WatchEvent.Kind[] events, WatchEvent.Modifier... modifiers) throws IOException { + if (!(watcher instanceof NioWatchService nioWatcher)) { + throw new IllegalArgumentException("Unsupported WatchService"); + } + return nioWatcher.register(this, events); + } + + @Override + public WatchKey register(WatchService watcher, WatchEvent.Kind... events) throws IOException { + return register(watcher, events, new WatchEvent.Modifier[0]); + } + + @Override + public Iterator iterator() { + List paths = new ArrayList<>(); + for (String part : names()) { + paths.add(relative(null, fileSystem, part)); + } + return paths.iterator(); + } + + @Override + public int compareTo(Path other) { + return toString().compareTo(other.toString()); + } + + @Override + public String toString() { + return absolute ? (name.isEmpty() ? "/" : "/" + name) : name; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (!(obj instanceof NioPathForFileObject other)) { + return false; + } + return fileSystem == other.fileSystem && absolute == other.absolute && name.equals(other.name); + } + + @Override + public int hashCode() { + return Objects.hash(fileSystem, name, absolute); + } + + private List names() { + List names = new ArrayList<>(); + if (!name.isEmpty()) { + for (String part : name.split("/")) { + if (!part.isEmpty()) { + names.add(part); + } + } + } + return names; + } + + private static String normalize(String name) { + if (name == null) { + return ""; + } + String result = name.replace('\\', '/'); + while (result.startsWith("/")) { + result = result.substring(1); + } + return result; + } + + private static String fullName(FileObject fileObject) { + if (fileObject == null) { + return ""; + } + List names = new ArrayList<>(); + FileObject current = fileObject; + while (current != null) { + String name = current.getNameExt(); + if (!name.isEmpty()) { + names.add(0, name); + } + current = current.getParent(); + } + return String.join("/", names); + } + + static NioPathForFileObject fromInvalidPath(String name, NioFsForFileSystem fileSystem) { + return new NioPathForFileObject(null, fileSystem, name); + } +} diff --git a/platform/openide.filesystems/src/org/openide/filesystems/NioPathProvider.java b/platform/openide.filesystems/src/org/openide/filesystems/NioPathProvider.java new file mode 100644 index 000000000000..0325e8a94c1a --- /dev/null +++ b/platform/openide.filesystems/src/org/openide/filesystems/NioPathProvider.java @@ -0,0 +1,574 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.openide.filesystems; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.ByteArrayOutputStream; +import java.net.URI; +import java.nio.channels.SeekableByteChannel; +import java.nio.ByteBuffer; +import java.nio.file.AccessDeniedException; +import java.nio.file.AccessMode; +import java.nio.file.CopyOption; +import java.nio.file.DirectoryNotEmptyException; +import java.nio.file.DirectoryStream; +import java.nio.file.FileAlreadyExistsException; +import java.nio.file.FileStore; +import java.nio.file.FileSystem; +import java.nio.file.LinkOption; +import java.nio.file.NoSuchFileException; +import java.nio.file.NotDirectoryException; +import java.nio.file.OpenOption; +import java.nio.file.Path; +import java.nio.file.ProviderMismatchException; +import java.nio.file.StandardCopyOption; +import java.nio.file.attribute.BasicFileAttributes; +import java.nio.file.attribute.FileAttribute; +import java.nio.file.attribute.FileTime; +import java.nio.file.spi.FileSystemProvider; +import java.util.Iterator; +import java.util.Map; +import java.util.Objects; +import java.util.Set; + +final class NioPathProvider extends FileSystemProvider { + private final NioFsForFileSystem fileSystem; + + NioPathProvider(NioFsForFileSystem fileSystem) { + this.fileSystem = fileSystem; + } + + @Override + public String getScheme() { + return fileSystem.getFileSystem().getRoot().toURI().getScheme(); + } + + @Override + public FileSystem newFileSystem(URI uri, Map env) { + throw new UnsupportedOperationException(); + } + + @Override + public FileSystem getFileSystem(URI uri) { + return fileSystem; + } + + @Override + public Path getPath(URI uri) { + String path = uri.getPath(); + return fileSystem.getPath(path); + } + + @Override + public SeekableByteChannel newByteChannel( + Path path, Set options, FileAttribute... attrs) throws IOException { + if (options.stream().anyMatch(option -> + option == java.nio.file.StandardOpenOption.WRITE + || option == java.nio.file.StandardOpenOption.APPEND + || option == java.nio.file.StandardOpenOption.CREATE + || option == java.nio.file.StandardOpenOption.CREATE_NEW)) { + FileObject fo = fromPath(path).getFileObject(); + if (fo == null || !fo.isValid()) { + if (fromPath(path).getFileObject() == null && path.getParent() != null) { + FileObject parent = fromPath(path.getParent()).getFileObject(); + if (parent == null) { + throw new NoSuchFileException(path.toString()); + } + fo = parent.createData(path.getFileName().toString()); + } else { + throw new NoSuchFileException(path.toString()); + } + } + return new WritableFileObjectByteChannel(fo); + } + FileObject fo = fromPath(path).getFileObject(); + if (fo == null || !fo.isValid()) { + throw new NoSuchFileException(path.toString()); + } + return new FileObjectByteChannel(fo); + } + + @Override + public DirectoryStream newDirectoryStream(Path dir, DirectoryStream.Filter filter) + throws IOException { + NioPathForFileObject nio = fromPath(dir); + FileObject folder = nio.getFileObject(); + if (folder == null || !folder.isFolder()) { + throw new NoSuchFileException(dir.toString()); + } + FileObject[] children = folder.getChildren(); + java.util.List paths = new java.util.ArrayList<>(); + for (FileObject child : children) { + Path childPath = NioPathForFileObject.create(child, fileSystem); + if (filter.accept(childPath)) { + paths.add(childPath); + } + } + return new DirectoryStream() { + @Override + public Iterator iterator() { + return paths.iterator(); + } + + @Override + public void close() { + } + }; + } + + @Override + public void createDirectory(Path dir, FileAttribute... attrs) throws IOException { + NioPathForFileObject nio = fromPath(dir); + if (nio.getFileObject() != null) { + throw new java.nio.file.FileAlreadyExistsException(dir.toString()); + } + Path parent = dir.getParent(); + NioPathForFileObject nioParent = parent instanceof NioPathForFileObject ? fromPath(parent) : null; + if (nioParent == null || nioParent.getFileObject() == null) { + throw new NoSuchFileException(dir.toString()); + } + nioParent.getFileObject().createFolder(dir.getFileName().toString()); + } + + @Override + public void delete(Path path) throws IOException { + FileObject fo = fromPath(path).getFileObject(); + if (fo == null || !fo.isValid()) { + throw new NoSuchFileException(path.toString()); + } + fo.delete(); + } + + @Override + public void copy(Path source, Path target, CopyOption... options) throws IOException { + boolean replaceExisting = false; + boolean copyAttributes = false; + for (CopyOption option : options) { + Objects.requireNonNull(option, "option"); + if (option == StandardCopyOption.REPLACE_EXISTING) { + replaceExisting = true; + } else if (option == StandardCopyOption.COPY_ATTRIBUTES) { + copyAttributes = true; + } else if (option != LinkOption.NOFOLLOW_LINKS) { + throw new UnsupportedOperationException("Unsupported copy option: " + option); + } + } + + NioPathForFileObject sourcePath = fromPath(source); + NioPathForFileObject targetPath = fromPath(target); + if (sourcePath.getFileSystem() != fileSystem || targetPath.getFileSystem() != fileSystem) { + throw new ProviderMismatchException(); + } + FileObject sourceFile = sourcePath.getFileObject(); + if (sourceFile == null || !sourceFile.isValid()) { + throw new NoSuchFileException(source.toString()); + } + FileObject targetFile = targetPath.getFileObject(); + if (targetFile != null && targetFile.isValid()) { + if (sourceFile.equals(targetFile)) { + return; + } + if (!replaceExisting) { + throw new FileAlreadyExistsException(target.toString()); + } + if (targetFile.isFolder() && targetFile.getChildren().length != 0) { + throw new DirectoryNotEmptyException(target.toString()); + } + } + + Path targetParentPath = target.getParent(); + if (targetParentPath == null) { + throw new NoSuchFileException(target.toString()); + } + FileObject targetParent = fromPath(targetParentPath).getFileObject(); + if (targetParent == null || !targetParent.isValid()) { + throw new NoSuchFileException(targetParentPath.toString()); + } + if (!targetParent.isFolder()) { + throw new NotDirectoryException(targetParentPath.toString()); + } + if (targetFile != null && targetFile.isValid()) { + targetFile.delete(); + } + String targetName = target.getFileName().toString(); + FileObject copied; + if (sourceFile.isFolder()) { + copied = targetParent.createFolder(targetName); + } else { + copied = targetParent.createData(targetName); + try (InputStream input = sourceFile.getInputStream(); + OutputStream output = copied.getOutputStream()) { + input.transferTo(output); + } + } + if (copyAttributes) { + FileUtil.copyAttributes(sourceFile, copied); + } + } + + @Override + public void move(Path source, Path target, CopyOption... options) throws IOException { + FileObject fo = fromPath(source).getFileObject(); + FileObject targetParent = fromPath(target.getParent()).getFileObject(); + if (fo == null || targetParent == null) { + throw new NoSuchFileException(source.toString()); + } + Path targetName = target.getFileName(); + if (targetName == null) { + throw new NoSuchFileException(target.toString()); + } + String targetFileName = targetName.toString(); + int dot = targetFileName.lastIndexOf('.'); + String name = dot == -1 ? targetFileName : targetFileName.substring(0, dot); + String ext = dot == -1 ? null : targetFileName.substring(dot + 1); + FileLock lock = fo.lock(); + try { + fo.move(lock, targetParent, name, ext); + } finally { + lock.releaseLock(); + } + } + + @Override + public boolean isSameFile(Path path, Path path2) throws IOException { + NioPathForFileObject first = fromPath(path); + NioPathForFileObject second = fromPath(path2); + if (first.getFileObject() != null && second.getFileObject() != null) { + return first.getFileObject().equals(second.getFileObject()); + } + return path.equals(path2); + } + + @Override + public boolean isHidden(Path path) { + FileObject fo = fromPath(path).getFileObject(); + return fo != null && fo.getNameExt().startsWith("."); + } + + @Override + public FileStore getFileStore(Path path) { + throw new UnsupportedOperationException("FileStore is not supported"); + } + + @Override + public void checkAccess(Path path, AccessMode... modes) throws IOException { + FileObject fo = fromPath(path).getFileObject(); + if (fo == null || !fo.isValid()) { + throw new NoSuchFileException(path.toString()); + } + for (AccessMode mode : modes) { + if (mode == AccessMode.WRITE && fo.isReadOnly()) { + throw new AccessDeniedException(path.toString()); + } + if (mode == AccessMode.EXECUTE) { + throw new AccessDeniedException(path.toString()); + } + } + } + + @Override + public V getFileAttributeView( + Path path, Class type, LinkOption... options) { + return null; + } + + @Override + public A readAttributes( + Path path, Class type, LinkOption... options) throws IOException { + if (!type.equals(BasicFileAttributes.class)) { + throw new UnsupportedOperationException("Unsupported attributes type"); + } + final FileObject fo = fromPath(path).getFileObject(); + if (fo == null || !fo.isValid()) { + throw new NoSuchFileException(path.toString()); + } + final FileTime modified = FileTime.fromMillis(fo.lastModified().getTime()); + final BasicFileAttributes attrs = new BasicFileAttributes() { + @Override + public FileTime lastModifiedTime() { + return modified; + } + + @Override + public FileTime lastAccessTime() { + return modified; + } + + @Override + public FileTime creationTime() { + return modified; + } + + @Override + public boolean isRegularFile() { + return fo.isData(); + } + + @Override + public boolean isDirectory() { + return fo.isFolder(); + } + + @Override + public boolean isSymbolicLink() { + return false; + } + + @Override + public boolean isOther() { + return !fo.isData() && !fo.isFolder(); + } + + @Override + public long size() { + return fo.getSize(); + } + + @Override + public Object fileKey() { + return fo; + } + }; + @SuppressWarnings("unchecked") + A result = (A) attrs; + return result; + } + + @Override + public Map readAttributes( + Path path, String attributes, LinkOption... options) throws IOException { + BasicFileAttributes attrs = readAttributes(path, BasicFileAttributes.class, options); + if ("*".equals(attributes) || "basic:*".equals(attributes)) { + java.util.Map result = new java.util.HashMap<>(); + result.put("lastModifiedTime", attrs.lastModifiedTime()); + result.put("lastAccessTime", attrs.lastAccessTime()); + result.put("creationTime", attrs.creationTime()); + result.put("size", attrs.size()); + result.put("isRegularFile", attrs.isRegularFile()); + result.put("isDirectory", attrs.isDirectory()); + result.put("isSymbolicLink", attrs.isSymbolicLink()); + result.put("isOther", attrs.isOther()); + result.put("fileKey", attrs.fileKey()); + return result; + } + if ("basic:lastModifiedTime".equals(attributes)) { + return Map.of("lastModifiedTime", attrs.lastModifiedTime()); + } + throw new UnsupportedOperationException("Unsupported attributes"); + } + + @Override + public void setAttribute(Path path, String attribute, Object value, LinkOption... options) + throws IOException { + FileObject fo = fromPath(path).getFileObject(); + if (fo == null || !fo.isValid()) { + throw new NoSuchFileException(path.toString()); + } + throw new UnsupportedOperationException("Unsupported attribute: " + attribute); + } + + @Override + public InputStream newInputStream(Path path, OpenOption... options) throws IOException { + FileObject fo = fromPath(path).getFileObject(); + if (fo == null || !fo.isValid()) { + throw new NoSuchFileException(path.toString()); + } + return fo.getInputStream(); + } + + @Override + public OutputStream newOutputStream(Path path, OpenOption... options) throws IOException { + FileObject fo = fromPath(path).getFileObject(); + if (fo == null || !fo.isValid()) { + Path parent = path.getParent(); + if (parent != null) { + FileObject parentFo = fromPath(parent).getFileObject(); + if (parentFo != null) { + fo = parentFo.getFileObject(path.getFileName().toString()); + if (fo == null) { + fo = parentFo.createData(path.getFileName().toString()); + } + } + } + if (fo == null) { + throw new NoSuchFileException(path.toString()); + } + } + if (fo.isReadOnly()) { + throw new AccessDeniedException(path.toString()); + } + return fo.getOutputStream(); + } + + private NioPathForFileObject fromPath(Path path) { + if (!(path instanceof NioPathForFileObject nio)) { + throw new IllegalArgumentException("Not a NetBeans FileObject path"); + } + return nio; + } + + private static final class FileObjectByteChannel implements SeekableByteChannel { + private final byte[] bytes; + private long position; + private boolean open = true; + + FileObjectByteChannel(FileObject fileObject) throws IOException { + try (InputStream input = fileObject.getInputStream()) { + bytes = input.readAllBytes(); + } + } + + @Override + public int read(ByteBuffer dst) throws IOException { + if (!open) { + throw new java.nio.channels.ClosedChannelException(); + } + int remaining = (int) Math.min(dst.remaining(), bytes.length - position); + if (remaining <= 0) { + return -1; + } + dst.put(bytes, (int) position, remaining); + position += remaining; + return remaining; + } + + @Override + public int write(ByteBuffer src) { + throw new UnsupportedOperationException("Read-only"); + } + + @Override + public long position() { + return position; + } + + @Override + public SeekableByteChannel position(long newPosition) { + if (newPosition < 0) { + throw new IllegalArgumentException(); + } + position = newPosition; + return this; + } + + @Override + public long size() { + return bytes.length; + } + + @Override + public SeekableByteChannel truncate(long size) { + throw new UnsupportedOperationException("Read-only"); + } + + @Override + public boolean isOpen() { + return open; + } + + @Override + public void close() { + open = false; + } + } + + private static final class WritableFileObjectByteChannel implements SeekableByteChannel { + private final FileObject fileObject; + private ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + private long position; + private boolean open = true; + + WritableFileObjectByteChannel(FileObject fileObject) throws IOException { + this.fileObject = fileObject; + try (InputStream input = fileObject.getInputStream()) { + byte[] existing = input.readAllBytes(); + bytes.write(existing); + } + } + + @Override + public int read(ByteBuffer dst) { + byte[] data = bytes.toByteArray(); + int remaining = (int) Math.min(dst.remaining(), data.length - position); + if (remaining <= 0) { + return -1; + } + dst.put(data, (int) position, remaining); + position += remaining; + return remaining; + } + + @Override + public int write(ByteBuffer src) { + byte[] data = new byte[src.remaining()]; + src.get(data); + byte[] existing = bytes.toByteArray(); + int end = (int) Math.max(existing.length, position + data.length); + byte[] updated = new byte[end]; + System.arraycopy(existing, 0, updated, 0, existing.length); + System.arraycopy(data, 0, updated, (int) position, data.length); + bytes = new ByteArrayOutputStream(); + bytes.write(updated, 0, updated.length); + position += data.length; + return data.length; + } + + @Override + public long position() { + return position; + } + + @Override + public SeekableByteChannel position(long newPosition) { + position = newPosition; + return this; + } + + @Override + public long size() { + return bytes.size(); + } + + @Override + public SeekableByteChannel truncate(long size) { + byte[] data = bytes.toByteArray(); + byte[] truncated = java.util.Arrays.copyOf(data, (int) size); + bytes = new ByteArrayOutputStream(); + bytes.write(truncated, 0, truncated.length); + return this; + } + + @Override + public boolean isOpen() { + return open; + } + + @Override + public void close() throws IOException { + if (open) { + try (OutputStream output = fileObject.getOutputStream()) { + output.write(bytes.toByteArray()); + } + open = false; + } + } + } +} diff --git a/platform/openide.filesystems/src/org/openide/filesystems/NioWatchService.java b/platform/openide.filesystems/src/org/openide/filesystems/NioWatchService.java new file mode 100644 index 000000000000..f0a455794e3e --- /dev/null +++ b/platform/openide.filesystems/src/org/openide/filesystems/NioWatchService.java @@ -0,0 +1,235 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.openide.filesystems; + +import java.nio.file.ClosedWatchServiceException; +import java.nio.file.Path; +import java.nio.file.StandardWatchEventKinds; +import java.nio.file.Watchable; +import java.nio.file.WatchEvent; +import java.nio.file.WatchKey; +import java.nio.file.WatchService; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.ConcurrentLinkedQueue; + +final class NioWatchService implements WatchService { + private final BlockingQueue keys = new LinkedBlockingQueue<>(); + private volatile boolean closed; + + WatchKey register(Path path, WatchEvent.Kind[] events) { + checkClosed(); + return new NioWatchKey(this, path, events); + } + + @Override + public WatchKey poll() throws ClosedWatchServiceException { + checkClosed(); + return dequeued(keys.poll()); + } + + @Override + public WatchKey poll(long timeout, TimeUnit unit) + throws ClosedWatchServiceException, InterruptedException { + checkClosed(); + return dequeued(keys.poll(timeout, unit)); + } + + @Override + public WatchKey take() throws ClosedWatchServiceException, InterruptedException { + checkClosed(); + return dequeued(keys.take()); + } + + private WatchKey dequeued(NioWatchKey key) { + if (key != null) { + key.dequeued(); + } + return key; + } + + @Override + public void close() { + closed = true; + } + + void checkClosed() { + if (closed) { + throw new ClosedWatchServiceException(); + } + } + + private static final class NioWatchKey implements WatchKey { + private final NioWatchService service; + private final Path path; + private final WatchEvent.Kind[] events; + private final ConcurrentLinkedQueue> queuedEvents = new ConcurrentLinkedQueue<>(); + private final FileChangeListener listener; + private final FileObject watchedObject; + private boolean valid = true; + private boolean signalled; + private boolean queued; + + NioWatchKey(NioWatchService service, Path path, WatchEvent.Kind[] events) { + this.service = service; + this.path = path; + this.events = events.clone(); + FileObject watched = null; + this.listener = new FileChangeAdapter() { + @Override + public void fileDataCreated(FileEvent event) { + offer(StandardWatchEventKinds.ENTRY_CREATE, event.getFile().getNameExt()); + } + + @Override + public void fileFolderCreated(FileEvent event) { + offer(StandardWatchEventKinds.ENTRY_CREATE, event.getFile().getNameExt()); + } + + @Override + public void fileDeleted(FileEvent event) { + offer(StandardWatchEventKinds.ENTRY_DELETE, event.getFile().getNameExt()); + } + + @Override + public void fileRenamed(FileRenameEvent event) { + String oldName = event.getName(); + if (event.getExt() != null && !event.getExt().isEmpty()) { + oldName += "." + event.getExt(); + } + offer(StandardWatchEventKinds.ENTRY_DELETE, oldName); + offer(StandardWatchEventKinds.ENTRY_CREATE, event.getFile().getNameExt()); + } + + @Override + public void fileChanged(FileEvent event) { + offer(StandardWatchEventKinds.ENTRY_MODIFY, event.getFile().getNameExt()); + } + }; + if (path instanceof NioPathForFileObject nio && nio.getFileObject() != null) { + FileObject fo = nio.getFileObject(); + fo.addFileChangeListener(listener); + watched = fo; + } + this.watchedObject = watched; + } + + private synchronized void offer(WatchEvent.Kind kind, String context) { + if (!isValid()) { + return; + } + for (WatchEvent.Kind watched : events) { + if (watched == kind) { + Path contextPath = path.getFileSystem().getPath(context); + queuedEvents.offer(new NioWatchEvent(kind, contextPath)); + if (!signalled) { + signalled = true; + enqueue(); + } + break; + } + } + } + + @Override + public synchronized boolean isValid() { + return valid && !service.closed; + } + + @Override + public synchronized List> pollEvents() { + List> result = new ArrayList<>(); + WatchEvent event; + while ((event = queuedEvents.poll()) != null) { + result.add(event); + } + return result; + } + + @Override + public synchronized boolean reset() { + if (!isValid()) { + return false; + } + if (signalled) { + if (queuedEvents.isEmpty()) { + signalled = false; + } else { + enqueue(); + } + } + return true; + } + + private void enqueue() { + if (!queued) { + queued = true; + service.keys.offer(this); + } + } + + private synchronized void dequeued() { + queued = false; + } + + @Override + public void cancel() { + synchronized (this) { + valid = false; + } + if (watchedObject != null) { + watchedObject.removeFileChangeListener(listener); + } + } + + @Override + public Watchable watchable() { + return path; + } + } + + private static final class NioWatchEvent implements WatchEvent { + private final WatchEvent.Kind kind; + private final Object context; + + @SuppressWarnings("unchecked") + NioWatchEvent(WatchEvent.Kind kind, Object context) { + this.kind = (WatchEvent.Kind) kind; + this.context = context; + } + + @Override + public Kind kind() { + return kind; + } + + @Override + public int count() { + return 1; + } + + @Override + public Object context() { + return context; + } + } +} diff --git a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/JarFileSystemTest.java b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/JarFileSystemTest.java index 8ec3bb7551d3..ed92302b0de9 100644 --- a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/JarFileSystemTest.java +++ b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/JarFileSystemTest.java @@ -42,6 +42,7 @@ public static Test suite() { suite.addTestSuite(RepositoryTestHid.class); suite.addTestSuite(FileSystemTestHid.class); suite.addTestSuite(FileObjectTestHid.class); + suite.addTestSuite(PathTestHid.class); /*failing tests*/ suite.addTestSuite(URLMapperTestHidden.class); suite.addTestSuite(URLMapperTestInternalHidden.class); diff --git a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/LocalFileSystemTest.java b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/LocalFileSystemTest.java index ff625f84eb80..a44a087b647f 100644 --- a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/LocalFileSystemTest.java +++ b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/LocalFileSystemTest.java @@ -39,6 +39,7 @@ public static Test suite() { suite.addTestSuite(URLMapperTestHidden.class); suite.addTestSuite(URLMapperTestInternalHidden.class); suite.addTestSuite(FileUtilTestHidden.class); + suite.addTestSuite(PathTestHid.class); suite.addTestSuite(FileUtilJavaIOFileHidden.class); return new LocalFileSystemTest(suite); diff --git a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/LocalFileSystemTestHid.java b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/LocalFileSystemTestHid.java index 6eab87aec319..0e3d94b41af2 100644 --- a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/LocalFileSystemTestHid.java +++ b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/LocalFileSystemTestHid.java @@ -22,6 +22,8 @@ import java.io.File; import java.io.InputStream; import java.io.SyncFailedException; +import java.nio.file.Files; +import java.nio.file.attribute.FileTime; public class LocalFileSystemTestHid extends TestBaseHid { private static String[] resources = new String [] { @@ -38,6 +40,20 @@ protected String[] getResources (String testName) { return resources; } + public void testSetPathLastModifiedUpdatesFileObject() throws Exception { + FileObject file = testedFS.findResource("A/C/A"); + assertNotNull(file); + java.nio.file.Path path = FileUtil.toPath(file); + assertNotNull(path); + + FileTime modified = FileTime.fromMillis(file.lastModified().getTime() + 10000); + Files.setAttribute(path, "basic:lastModifiedTime", modified); + file.refresh(); + + assertEquals(modified.toMillis(), file.lastModified().getTime()); + assertEquals(modified, Files.getLastModifiedTime(path)); + } + /** We delete a folder and then listen on changes fired on one of its children. */ public void testExternalRemoveChildrenEvents () throws Exception { FileObject fo = testedFS.findResource ("A/B/C.java"); diff --git a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MemoryFSTestHid.java b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MemoryFSTestHid.java index 7853f6c63daf..d8bf4099fed6 100644 --- a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MemoryFSTestHid.java +++ b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MemoryFSTestHid.java @@ -21,8 +21,12 @@ import java.io.ByteArrayOutputStream; import java.io.OutputStream; +import java.net.URI; import java.net.URL; import java.net.URLConnection; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; /** * @@ -86,4 +90,23 @@ public void testURLs() throws Exception { assertEquals(file.getParent(), URLMapper.findFileObject(file.getParent().toURI().toURL())); } + public void testURIs() throws Exception{ + FileObject file = FileUtil.createData(testedFS.getRoot(), "/folder/file.txt"); + URI uri = file.toURI(); + assertEquals("memory", uri.getScheme()); + Path path = FileUtil.toPath(file); + URI u2 = path.toUri(); + assertEquals("memory", u2.getScheme()); + assertEquals("memory", path.getFileSystem().provider().getScheme()); + } + + public void testCopyAttributesThroughPath() throws Exception { + FileObject source = testedFS.getRoot().createData("source.txt"); + source.setAttribute("custom", "value"); + Path target = FileUtil.toPath(source).resolveSibling("copy.txt"); + + Files.copy(FileUtil.toPath(source), target, StandardCopyOption.COPY_ATTRIBUTES); + assertEquals("value", FileUtil.toFileObject(target).getAttribute("custom")); + assertNotNull(testedFS.getRoot().getFileObject("source.txt")); + } } diff --git a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MemoryFileSystemTest.java b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MemoryFileSystemTest.java index 24eb3c9cfcf0..6e2af8071242 100644 --- a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MemoryFileSystemTest.java +++ b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MemoryFileSystemTest.java @@ -37,6 +37,7 @@ public static Test suite() { suite.addTestSuite(RepositoryTestHid.class); suite.addTestSuite(FileSystemTestHid.class); suite.addTestSuite(FileObjectTestHid.class); + suite.addTestSuite(PathTestHid.class); suite.addTestSuite(MemoryFSTestHid.class); return new MemoryFileSystemTest(suite); diff --git a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MultiFileSystem1Test.java b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MultiFileSystem1Test.java index d23f0596cd7f..9ed2cddb28eb 100644 --- a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MultiFileSystem1Test.java +++ b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MultiFileSystem1Test.java @@ -48,6 +48,7 @@ public static Test suite() { suite.addTestSuite(FileSystemTestHid.class); suite.addTestSuite(AttributesTestHidden.class); suite.addTestSuite(FileObjectTestHid.class); + suite.addTestSuite(PathTestHid.class); suite.addTestSuite(MultiFileObjectTestHid.class); /*failing tests*/ suite.addTestSuite(URLMapperTestHidden.class); diff --git a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MultiFileSystem2Test.java b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MultiFileSystem2Test.java index 17c5c5dcc977..46649278e2bd 100644 --- a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MultiFileSystem2Test.java +++ b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MultiFileSystem2Test.java @@ -47,6 +47,7 @@ public static Test suite() { suite.addTestSuite(AttributesTestHidden.class); suite.addTestSuite(FileSystemTestHid.class); suite.addTestSuite(FileObjectTestHid.class); + suite.addTestSuite(PathTestHid.class); suite.addTestSuite(MultiFileObjectTestHid.class); /*failing tests*/ suite.addTestSuite(URLMapperTestHidden.class); diff --git a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MultiFileSystem3Test.java b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MultiFileSystem3Test.java index e4bf55c892a7..4135f3029f95 100644 --- a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MultiFileSystem3Test.java +++ b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MultiFileSystem3Test.java @@ -47,6 +47,7 @@ public static Test suite() { suite.addTestSuite(FileSystemTestHid.class); suite.addTestSuite(AttributesTestHidden.class); suite.addTestSuite(FileObjectTestHid.class); + suite.addTestSuite(PathTestHid.class); suite.addTestSuite(MultiFileObjectTestHid.class); /*failing tests*/ suite.addTestSuite(URLMapperTestHidden.class); diff --git a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MultiFileSystemXMLTest.java b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MultiFileSystemXMLTest.java index e507d72b6c89..3411fe8ec03a 100644 --- a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MultiFileSystemXMLTest.java +++ b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MultiFileSystemXMLTest.java @@ -42,6 +42,7 @@ public static Test suite() { NbTestSuite suite = new NbTestSuite(); suite.addTestSuite(FileSystemTestHid.class); suite.addTestSuite(FileObjectTestHid.class); + suite.addTestSuite(PathTestHid.class); suite.addTestSuite(XMLFileSystemTestHid.class); return new MultiFileSystemXMLTest(suite); diff --git a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java new file mode 100644 index 000000000000..d268f8484fae --- /dev/null +++ b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java @@ -0,0 +1,864 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.openide.filesystems; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URI; +import java.nio.channels.FileChannel; +import java.nio.charset.StandardCharsets; +import java.nio.file.FileAlreadyExistsException; +import java.nio.file.Files; +import java.nio.file.NoSuchFileException; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; +import java.nio.file.StandardWatchEventKinds; +import java.nio.file.WatchEvent; +import java.nio.file.WatchKey; +import java.nio.file.WatchService; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class PathTestHid extends TestBaseHid { + + private FileObject root; + + public PathTestHid(String name) { + super(name); + } + + @Override + protected String[] getResources(String testName) { + return new String[] { + "pathtest/dir/file.txt", + "pathtest/dir/sibling.txt" + }; + } + + @Override + @SuppressWarnings("deprecation") + protected void setUp() throws Exception { + super.setUp(); + Repository.getDefault().addFileSystem(testedFS); + root = testedFS.findResource(getResourcePrefix()); + } + + @Override + @SuppressWarnings("deprecation") + protected void tearDown() throws Exception { + Repository.getDefault().removeFileSystem(testedFS); + super.tearDown(); + } + + public void testPathAccessorsAndNames() throws Exception { + Path path = getPath(); + + assertNotNull(path.getFileSystem()); + assertTrue(path.isAbsolute()); + assertNotNull(path.getRoot()); + assertEquals("file.txt", path.getFileName().toString()); + assertNotNull(path.getParent()); + assertTrue(path.getNameCount() > 0); + assertEquals(path.getFileName(), path.getName(path.getNameCount() - 1)); + assertEquals(path.getNameCount(), path.subpath(0, path.getNameCount()).getNameCount()); + assertTrue(path.startsWith(path.getRoot())); + assertTrue(path.startsWith(path.getParent())); + assertTrue(path.startsWith(path.getParent().toString())); + assertTrue(path.endsWith(path.getFileName())); + assertTrue(path.endsWith(path.getFileName().toString())); + assertEquals(path, path.normalize()); + + Iterator names = path.iterator(); + Path lastName = null; + while (names.hasNext()) { + lastName = names.next(); + } + assertEquals(path.getFileName(), lastName); + } + + public void testListChildrenThroughPath() throws Exception { + FileObject folder = getFileObject().getParent(); + FileObject[] children = folder.getChildren(); + Set fileObjectNames = new HashSet<>(); + for (FileObject child : children) { + fileObjectNames.add(child.getNameExt()); + } + + Set pathNames; + try (Stream entries = Files.list(FileUtil.toPath(folder))) { + pathNames = entries + .map(entry -> entry.getFileName().toString()) + .collect(Collectors.toSet()); + } + + assertEquals(fileObjectNames, pathNames); + assertEquals(2, children.length); + } + + public void testURLsAreTheSame() throws Exception { + FileObject folder = getFileObject().getParent(); + FileObject[] children = folder.getChildren(); + Set foUris = new HashSet<>(); + for (FileObject child : children) { + foUris.add(child.toURI()); + } + + Set pathUris; + try (Stream entries = Files.list(FileUtil.toPath(folder))) { + pathUris = entries + .map(entry -> entry.toUri()) + .collect(Collectors.toSet()); + } + + assertEquals(foUris, pathUris); + assertEquals(2, children.length); + + for (URI u : foUris) { + assertEquals("Scheme is correct", u.getScheme(), FileUtil.toPath(folder).getFileSystem().provider().getScheme()); + } + } + + public void testPathResolutionAndRelativization() throws Exception { + Path path = getPath(); + + Path parent = path.getParent(); + Path fileName = path.getFileName(); + assertEquals(path, parent.resolve(fileName)); + assertEquals(path, parent.resolve(fileName.toString())); + assertEquals(path, path.resolveSibling(path.getFileName())); + assertEquals(path, path.resolveSibling(path.getFileName().toString())); + assertEquals("sibling.txt", path.resolveSibling("sibling.txt").getFileName().toString()); + + Path relative = parent.relativize(path); + assertEquals(fileName, relative); + assertEquals(path, parent.resolve(relative)); + assertEquals(path.getFileSystem().getPath(""), path.relativize(path)); + } + + public void testEndsWithWholePathElements() throws Exception { + java.nio.file.FileSystem fs = getPath().getFileSystem(); + Path path = getPath(); + + assertTrue(path.endsWith("file.txt")); + assertTrue(path.endsWith(fs.getPath("dir/file.txt"))); + assertTrue(path.endsWith(path)); + assertFalse(path.endsWith("le.txt")); + assertFalse(path.endsWith(fs.getPath("ir/file.txt"))); + assertFalse(path.endsWith(path.getRoot().resolve("file.txt"))); + assertFalse(fs.getPath("dir/file.txt").endsWith(path)); + assertFalse(path.endsWith("")); + assertTrue(fs.getPath("").endsWith("")); + assertTrue(path.getRoot().endsWith(path.getRoot())); + assertFalse(path.getRoot().endsWith("")); + } + + public void testPathConversionAndComparison() throws Exception { + FileObject fileObject = getFileObject(); + Path path = getPath(); + + Path samePath = path.getFileSystem().getPath(path.toString()); + assertEquals(path, samePath); + assertEquals(path.hashCode(), samePath.hashCode()); + assertEquals(0, path.compareTo(samePath)); + assertEquals(fileObject, FileUtil.toFileObject(path)); + assertTrue(path.toUri().isAbsolute()); + assertEquals(path.toAbsolutePath().toUri(), path.toUri()); + assertFalse(path.toString().isEmpty()); + + if (testedFS.isReadOnly()) { + try { + path.toFile(); + fail("Read-only virtual Path unexpectedly has a java.io.File"); + } catch (UnsupportedOperationException ex) { + // Expected for virtual filesystems. + } + } else { + File file = FileUtil.toFile(fileObject); + if (file != null) { + assertEquals(file, path.toFile()); + assertEquals(file.getCanonicalFile().toPath(), path.toRealPath()); + } else { + try { + path.toFile(); + fail("Virtual FileObject unexpectedly has a java.io.File"); + } catch (UnsupportedOperationException ex) { + // Expected for virtual filesystems. + } + } + } + } + + public void testIndependentPathConversions() throws Exception { + FileObject fileObject = getFileObject(); + Path first = FileUtil.toPath(fileObject); + Path second = FileUtil.toPath(fileObject); + Path parent = FileUtil.toPath(fileObject.getParent()); + + assertEquals(first, second); + assertEquals(first.hashCode(), second.hashCode()); + assertEquals(0, first.compareTo(second)); + assertTrue(first.startsWith(parent)); + assertTrue(first.endsWith(second.getFileName())); + assertEquals(first.getFileName(), parent.relativize(first)); + assertEquals(first, parent.resolve(parent.relativize(second))); + } + + public void testFileSystemConversion() throws Exception { + FileObject fileObject = getFileObject(); + Path originalPath = getPath(); + java.nio.file.FileSystem nioFileSystem = originalPath.getFileSystem(); + Path path = nioFileSystem.getPath(originalPath.toString()); + + FileObject converted = FileUtil.toFileObject(path); + assertEquals(fileObject, converted); + assertSame(testedFS, converted.getFileSystem()); + } + + public void testCreateFileAndFolderThroughPath() throws Exception { + if (testedFS.isReadOnly()) { + return; + } + FileObject parent = getFileObject().getParent(); + Path folderPath = getPath().getParent().resolve("nio-folder"); + Path filePath = folderPath.resolve("nio-file.txt"); + + Files.createDirectory(folderPath); + Files.createFile(filePath); + Files.writeString(filePath, "created through NIO"); + + parent.refresh(); + FileObject folder = parent.getFileObject("nio-folder"); + assertNotNull(folder); + FileObject file = folder.getFileObject("nio-file.txt"); + assertNotNull(file); + assertTrue(folder.isFolder()); + assertTrue(file.isData()); + assertEquals(folder, file.getParent()); + assertEquals("created through NIO", file.asText()); + } + + public void testCopyFileThroughPath() throws Exception { + if (testedFS.isReadOnly()) { + return; + } + FileObject source = getFileObject(); + FileObject folder = source.getParent(); + Path sourcePath = FileUtil.toPath(source); + Path targetPath = sourcePath.resolveSibling("nio-copy.txt"); + Files.writeString(sourcePath, "original content"); + + assertEquals(targetPath, Files.copy(sourcePath, targetPath)); + folder.refresh(); + assertTrue("Copy must not invalidate the source", source.isValid()); + assertEquals(source, folder.getFileObject("file.txt")); + assertEquals("original content", source.asText("UTF-8")); + FileObject target = folder.getFileObject("nio-copy.txt"); + assertNotNull(target); + assertEquals("original content", target.asText("UTF-8")); + + Files.writeString(targetPath, "different content"); + try { + Files.copy(sourcePath, targetPath); + fail("Copying over an existing file must fail"); + } catch (FileAlreadyExistsException expected) { + } + assertEquals("different content", Files.readString(targetPath)); + Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING); + assertEquals("original content", Files.readString(targetPath)); + assertEquals("original content", Files.readString(sourcePath)); + Files.copy(sourcePath, sourcePath); + Files.copy(sourcePath, sourcePath, StandardCopyOption.REPLACE_EXISTING); + assertEquals("original content", Files.readString(sourcePath)); + try { + Files.copy(sourcePath, sourcePath.resolveSibling("missing-folder").resolve("copy.txt")); + fail("Copying to a missing parent directory must fail"); + } catch (NoSuchFileException expected) { + } + try { + Files.copy(sourcePath, sourcePath.resolveSibling("unsupported.txt"), StandardCopyOption.ATOMIC_MOVE); + fail("An unsupported copy option must fail"); + } catch (UnsupportedOperationException expected) { + } + } + + public void testCopyDirectoryThroughPath() throws Exception { + if (testedFS.isReadOnly()) { + return; + } + Path source = getPath().getParent(); + Path target = source.resolveSibling("nio-copy-folder"); + + Files.copy(source, target); + assertTrue(Files.isDirectory(target)); + try (Stream entries = Files.list(target)) { + assertEquals("Directory copy must not copy children", 0, entries.count()); + } + assertTrue(Files.exists(source.resolve("file.txt"))); + Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING); + Files.createFile(target.resolve("child.txt")); + try { + Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING); + fail("Replacing a nonempty directory must fail"); + } catch (IOException expected) { + } + assertTrue(Files.exists(target.resolve("child.txt"))); + try { + Files.copy(source.resolve("missing.txt"), target.resolve("missing.txt")); + fail("Copying a missing source must fail"); + } catch (NoSuchFileException expected) { + } + } + + public void testCopyFileToLocalFilesystem() throws Exception { + FileObject source = getFileObject(); + Path sourcePath = FileUtil.toPath(source); + Path targetPath = getWorkDir().toPath().resolve("nio-external-copy.txt"); + byte[] content = Files.readAllBytes(sourcePath); + + Files.copy(sourcePath, targetPath); + assertTrue(Arrays.equals(content, Files.readAllBytes(targetPath))); + assertTrue(source.isValid()); + assertEquals(source, source.getParent().getFileObject(source.getNameExt())); + } + + public void testCopyFileFromLocalFilesystem() throws Exception { + if (testedFS.isReadOnly()) { + return; + } + Path source = getWorkDir().toPath().resolve("nio-external-source.txt"); + Path target = getPath().resolveSibling("nio-imported.txt"); + Files.writeString(source, "external content"); + + Files.copy(source, target); + assertEquals("external content", Files.readString(source)); + assertEquals("external content", Files.readString(target)); + } + + public void testCopyToReadOnlyFilesystemFails() throws Exception { + if (!testedFS.isReadOnly()) { + return; + } + FileObject source = getFileObject(); + Path sourcePath = FileUtil.toPath(source); + Path targetPath = sourcePath.resolveSibling("nio-copy.txt"); + try { + Files.copy(sourcePath, targetPath); + fail("Copying to a read-only filesystem must fail"); + } catch (IOException expected) { + } + assertTrue(source.isValid()); + assertEquals(source, source.getParent().getFileObject(source.getNameExt())); + assertNull(source.getParent().getFileObject("nio-copy.txt")); + } + + public void testReadAndWriteThroughPathStreams() throws Exception { + FileObject file = getFileObject(); + Path path = getPath(); + byte[] original = Files.readAllBytes(path); + assertEquals(Files.size(path), file.getSize()); + try (InputStream input = Files.newInputStream(path)) { + assertTrue(Arrays.equals(original, input.readAllBytes())); + } + + if (testedFS.isReadOnly()) { + return; + } + String content = "Written through a Path output stream"; + while (content.getBytes(StandardCharsets.UTF_8).length == original.length) { + content += "!"; + } + byte[] contentBytes = content.getBytes(StandardCharsets.UTF_8); + CountDownLatch changed = new CountDownLatch(1); + FileChangeListener listener = new FileChangeAdapter() { + @Override + public void fileChanged(FileEvent event) { + changed.countDown(); + } + }; + file.addFileChangeListener(listener); + try (WatchService watcher = path.getFileSystem().newWatchService()) { + path.getParent().register(watcher, StandardWatchEventKinds.ENTRY_MODIFY); + try (OutputStream output = Files.newOutputStream(path)) { + output.write(contentBytes); + } + + assertWatchEventPresent( + watcher, new ExpectedWatchEvent(StandardWatchEventKinds.ENTRY_MODIFY, path.getFileName())); + file.refresh(); + if (FileUtil.toFile(file) != null) { + assertTrue("FileChangeListener was not notified", changed.await(5, TimeUnit.SECONDS)); + } + assertEquals(content, file.asText("UTF-8")); + assertEquals(contentBytes.length, Files.size(path)); + assertEquals(Files.size(path), file.getSize()); + try (InputStream input = Files.newInputStream(path)) { + assertEquals(content, new String(input.readAllBytes(), StandardCharsets.UTF_8)); + } + } finally { + file.removeFileChangeListener(listener); + } + } + + public void testPathSizeAndBasicAttributes() throws Exception { + FileObject file = getFileObject(); + Path path = getPath(); + BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class); + assertEquals(attributes.size(), Files.size(path)); + assertEquals(attributes.size(), file.getSize()); + assertEquals(attributes.lastModifiedTime().toMillis(), file.lastModified().getTime()); + } + + public void testPathFileChannelLock() throws Exception { + if (testedFS.isReadOnly()) { + return; + } + FileObject file = getFileObject(); + Path path = getPath(); + assertFalse(file.isLocked()); + + if (FileUtil.toFile(file) != null) { + try (FileChannel channel = FileChannel.open(path, StandardOpenOption.WRITE)) { + java.nio.channels.FileLock nioLock = channel.lock(); + try { + assertTrue(nioLock.isValid()); + assertFalse(file.isLocked()); + } finally { + nioLock.release(); + } + assertFalse(nioLock.isValid()); + } + } + + FileLock fileObjectLock = file.lock(); + try { + assertTrue(file.isLocked()); + } finally { + fileObjectLock.releaseLock(); + } + assertFalse(file.isLocked()); + } + + public void testMIMETypeAfterPathConversion() throws Exception { + Path path = getPath(); + if (!testedFS.isReadOnly()) { + Files.writeString(path, "Plain text content\n"); + } + FileObject file = FileUtil.toFileObject(path); + assertNotNull(file); + file.refresh(); + assertEquals(Files.probeContentType(path), file.getMIMEType()); + } + + public void testWatchServiceAndFileChangeListener() throws Exception { + if (testedFS.isReadOnly()) { + return; + } + FileObject watchedFolder = getFileObject().getParent(); + FileObject[] children = watchedFolder.getChildren(); + Path folderPath = FileUtil.toPath(watchedFolder); + Path createdPath = folderPath.resolve("nio-watched.txt"); + CountDownLatch created = new CountDownLatch(1); + AtomicReference createdFile = new AtomicReference<>(); + FileChangeListener listener = new FileChangeAdapter() { + @Override + public void fileDataCreated(FileEvent event) { + if (event.getFile().getNameExt().equals("nio-watched.txt")) { + createdFile.set(event.getFile()); + created.countDown(); + } + } + }; + watchedFolder.addFileChangeListener(listener); + try (WatchService watcher = folderPath.getFileSystem().newWatchService()) { + WatchEvent.Kind[] events = {StandardWatchEventKinds.ENTRY_CREATE}; + WatchKey key = folderPath.register(watcher, events); + assertTrue(key.isValid()); + WatchKey keyWithModifiers = folderPath.register(watcher, events, new WatchEvent.Modifier[0]); + assertTrue(keyWithModifiers.isValid()); + + Files.createFile(createdPath); + + WatchKey eventKey = watcher.poll(5, TimeUnit.SECONDS); + assertNotNull(eventKey); + List> watchEvents = eventKey.pollEvents(); + assertEquals(1, watchEvents.size()); + assertEquals(createdPath.getFileName(), watchEvents.get(0).context()); + + watchedFolder.refresh(); + assertTrue("FileChangeListener was not notified", created.await(5, TimeUnit.SECONDS)); + assertEquals(FileUtil.toFileObject(createdPath), createdFile.get()); + } finally { + watchedFolder.removeFileChangeListener(listener); + } + assertEquals(2, children.length); + } + + public void testWatchServicePollEventsAfterFileObjectChanges() throws Exception { + if (testedFS.isReadOnly()) { + return; + } + FileObject folder = getFileObject().getParent(); + FileObject[] children = folder.getChildren(); + Path folderPath = FileUtil.toPath(folder); + try (WatchService watcher = folderPath.getFileSystem().newWatchService()) { + WatchKey key = folderPath.register(watcher, StandardWatchEventKinds.ENTRY_CREATE); + assertNull("Registration must not signal a key", watcher.poll()); + assertTrue(key.pollEvents().isEmpty()); + + folder.createData("first-watch-event.txt"); + assertSame(key, watcher.poll(5, TimeUnit.SECONDS)); + List> events = key.pollEvents(); + assertEquals(1, events.size()); + assertEquals(StandardWatchEventKinds.ENTRY_CREATE, events.get(0).kind()); + assertEquals(folderPath.getFileSystem().getPath("first-watch-event.txt"), events.get(0).context()); + assertTrue(key.pollEvents().isEmpty()); + + folder.createData("second-watch-event.txt"); + assertNull("A signalled key must not be queued again before reset", + watcher.poll(200, TimeUnit.MILLISECONDS)); + assertTrue(key.reset()); + assertSame(key, watcher.poll(5, TimeUnit.SECONDS)); + events = key.pollEvents(); + assertEquals(1, events.size()); + assertEquals(StandardWatchEventKinds.ENTRY_CREATE, events.get(0).kind()); + assertEquals(folderPath.getFileSystem().getPath("second-watch-event.txt"), events.get(0).context()); + } + assertEquals(2, children.length); + } + + public void testWatchServiceFileObjectChangeSequence() throws Exception { + if (testedFS.isReadOnly()) { + return; + } + FileObject folder = getFileObject().getParent(); + FileObject[] children = folder.getChildren(); + Path folderPath = FileUtil.toPath(folder); + Path originalName = folderPath.getFileSystem().getPath("watch-sequence.txt"); + Path renamedName = folderPath.getFileSystem().getPath("watch-renamed.txt"); + try (WatchService watcher = folderPath.getFileSystem().newWatchService()) { + folderPath.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, + StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE); + + FileObject file = folder.createData(originalName.toString()); + assertWatchEvents(watcher, new ExpectedWatchEvent(StandardWatchEventKinds.ENTRY_CREATE, originalName)); + + try (OutputStream out = file.getOutputStream()) { + out.write(42); + } + assertWatchEvents(watcher, new ExpectedWatchEvent(StandardWatchEventKinds.ENTRY_MODIFY, originalName)); + + try (FileLock lock = file.lock()) { + file.rename(lock, "watch-renamed", "txt"); + } + assertWatchEvents(watcher, + new ExpectedWatchEvent(StandardWatchEventKinds.ENTRY_DELETE, originalName), + new ExpectedWatchEvent(StandardWatchEventKinds.ENTRY_CREATE, renamedName)); + + try (OutputStream out = file.getOutputStream()) { + out.write(43); + } + assertWatchEvents(watcher, new ExpectedWatchEvent(StandardWatchEventKinds.ENTRY_MODIFY, renamedName)); + + file.delete(); + assertWatchEvents(watcher, new ExpectedWatchEvent(StandardWatchEventKinds.ENTRY_DELETE, renamedName)); + } + assertEquals(2, children.length); + } + + public void testWatchServiceRoutesRenameToWatchedDirectory() throws Exception { + if (testedFS.isReadOnly()) { + return; + } + FileObject folder = getFileObject().getParent(); + FileObject[] children = folder.getChildren(); + FileObject nested = folder.createFolder("watch-nested"); + nested.createData("before.txt"); + FileObject[] nestedChildren = nested.getChildren(); + Path parentPath = FileUtil.toPath(folder); + Path nestedPath = parentPath.resolve("watch-nested"); + try (WatchService watcher = parentPath.getFileSystem().newWatchService()) { + WatchKey parentKey = parentPath.register(watcher, + StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE); + WatchKey nestedKey = nestedPath.register(watcher, + StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE); + Files.move(nestedPath.resolve("before.txt"), nestedPath.resolve("after.txt")); + + Set expected = Set.of("ENTRY_DELETE:before.txt", "ENTRY_CREATE:after.txt"); + Set remaining = new HashSet<>(expected); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (!remaining.isEmpty()) { + long timeout = deadline - System.nanoTime(); + assertTrue("Expected nested directory events " + remaining, timeout > 0); + WatchKey key = watcher.poll(timeout, TimeUnit.NANOSECONDS); + assertNotNull("Expected nested directory events " + remaining, key); + assertSame("Event delivered to the wrong directory", nestedKey, key); + for (WatchEvent event : key.pollEvents()) { + String actual = event.kind().name() + ":" + event.context(); + assertTrue("Unexpected event " + actual, expected.contains(actual)); + remaining.remove(actual); + } + assertTrue(key.reset()); + } + WatchKey extra = watcher.poll(200, TimeUnit.MILLISECONDS); + assertNotSame("Rename must not signal the parent directory", parentKey, extra); + } + assertEquals(2, children.length); + assertEquals(1, nestedChildren.length); + } + + public void testRenameFileThroughPath() throws Exception { + if (testedFS.isReadOnly()) { + return; + } + FileObject file = getFileObject(); + FileObject parent = file.getParent(); + FileObject[] children = parent.getChildren(); + Path filePath = getPath(); + Path renamedPath = filePath.resolveSibling("nio-renamed.txt"); + BlockingQueue fileChangeEvents = new LinkedBlockingQueue<>(); + FileChangeListener listener = createEventListener(fileChangeEvents); + parent.addFileChangeListener(listener); + try (WatchService watcher = filePath.getFileSystem().newWatchService()) { + filePath.getParent().register( + watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE); + + Files.move(filePath, renamedPath); + + assertWatchEvents( + watcher, + new ExpectedWatchEvent(StandardWatchEventKinds.ENTRY_DELETE, filePath.getFileName()), + new ExpectedWatchEvent(StandardWatchEventKinds.ENTRY_CREATE, renamedPath.getFileName())); + parent.refresh(); + assertRenameEvents(fileChangeEvents, "renamed:nio-renamed.txt", + "deleted:file.txt", "dataCreated:nio-renamed.txt"); + assertNotNull(parent.getFileObject("nio-renamed.txt")); + } finally { + parent.removeFileChangeListener(listener); + } + assertEquals(2, children.length); + } + + public void testRenameFolderThroughPath() throws Exception { + if (testedFS.isReadOnly()) { + return; + } + Path folderPath = getPath().getParent(); + Path parentPath = folderPath.getParent(); + Path renamedPath = parentPath.resolve("nio-renamed-folder"); + FileObject parent = getFileObject().getParent().getParent(); + FileObject[] children = parent.getChildren(); + FileObject folder = parent.getFileObject(folderPath.getFileName().toString()); + assertNotNull(folder); + BlockingQueue fileChangeEvents = new LinkedBlockingQueue<>(); + FileChangeListener listener = createEventListener(fileChangeEvents); + parent.addFileChangeListener(listener); + try (WatchService watcher = parentPath.getFileSystem().newWatchService()) { + parentPath.register( + watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE); + + Files.move(folderPath, renamedPath); + + assertWatchEvents( + watcher, + new ExpectedWatchEvent(StandardWatchEventKinds.ENTRY_DELETE, folderPath.getFileName()), + new ExpectedWatchEvent(StandardWatchEventKinds.ENTRY_CREATE, renamedPath.getFileName())); + parent.refresh(); + assertRenameEvents(fileChangeEvents, "renamed:nio-renamed-folder", + "deleted:dir", "folderCreated:nio-renamed-folder"); + assertNotNull(parent.getFileObject("nio-renamed-folder")); + } finally { + parent.removeFileChangeListener(listener); + } + assertEquals(1, children.length); + } + + public void testCreateDeleteAndRecreateThroughPath() throws Exception { + if (testedFS.isReadOnly()) { + return; + } + FileObject parent = getFileObject().getParent(); + FileObject[] children = parent.getChildren(); + Path parentPath = getPath().getParent(); + Path filePath = parentPath.resolve("nio-cycle.txt"); + BlockingQueue fileChangeEvents = new LinkedBlockingQueue<>(); + FileChangeListener listener = createEventListener(fileChangeEvents); + parent.addFileChangeListener(listener); + try (WatchService watcher = parentPath.getFileSystem().newWatchService()) { + parentPath.register( + watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE); + + Files.createFile(filePath); + assertWatchEvents(watcher, new ExpectedWatchEvent( + StandardWatchEventKinds.ENTRY_CREATE, filePath.getFileName())); + parent.refresh(); + assertFileChangeEvents(fileChangeEvents, "dataCreated:nio-cycle.txt"); + FileObject created = parent.getFileObject("nio-cycle.txt"); + assertNotNull(created); + + Files.delete(filePath); + assertWatchEvents(watcher, new ExpectedWatchEvent( + StandardWatchEventKinds.ENTRY_DELETE, filePath.getFileName())); + parent.refresh(); + assertFileChangeEvents(fileChangeEvents, "deleted:nio-cycle.txt"); + assertFalse(created.isValid()); + assertNull(parent.getFileObject("nio-cycle.txt")); + + Files.createFile(filePath); + assertWatchEvents(watcher, new ExpectedWatchEvent( + StandardWatchEventKinds.ENTRY_CREATE, filePath.getFileName())); + parent.refresh(); + assertFileChangeEvents(fileChangeEvents, "dataCreated:nio-cycle.txt"); + FileObject recreated = parent.getFileObject("nio-cycle.txt"); + assertNotNull(recreated); + assertNotSame(created, recreated); + } finally { + parent.removeFileChangeListener(listener); + } + assertEquals(2, children.length); + } + + private FileChangeListener createEventListener(BlockingQueue events) { + return new FileChangeAdapter() { + @Override + public void fileFolderCreated(FileEvent event) { + events.add("folderCreated:" + event.getFile().getNameExt()); + } + + @Override + public void fileDataCreated(FileEvent event) { + events.add("dataCreated:" + event.getFile().getNameExt()); + } + + @Override + public void fileDeleted(FileEvent event) { + events.add("deleted:" + event.getFile().getNameExt()); + } + + @Override + public void fileRenamed(FileRenameEvent event) { + events.add("renamed:" + event.getFile().getNameExt()); + } + }; + } + + private void assertFileChangeEvents(BlockingQueue events, String... expected) + throws InterruptedException { + List remaining = new ArrayList<>(Arrays.asList(expected)); + while (!remaining.isEmpty()) { + String event = events.poll(5, TimeUnit.SECONDS); + assertNotNull("Expected FileChangeListener event " + remaining, event); + assertTrue("Unexpected FileChangeListener event " + event, remaining.remove(event)); + } + } + + private void assertRenameEvents(BlockingQueue events, String renamed, + String deleted, String created) throws InterruptedException { + String first = events.poll(5, TimeUnit.SECONDS); + assertNotNull("Expected a FileChangeListener rename event", first); + if (renamed.equals(first) || deleted.equals(first) || created.equals(first)) { + return; + } + String second = events.poll(5, TimeUnit.SECONDS); + assertNotNull("Expected a second FileChangeListener event", second); + Set actual = new HashSet<>(Arrays.asList(first, second)); + assertEquals("Expected delete/create or rename event", + new HashSet<>(Arrays.asList(deleted, created)), actual); + } + + private void assertWatchEvents(WatchService watcher, ExpectedWatchEvent... expected) throws Exception { + List remaining = new ArrayList<>(Arrays.asList(expected)); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (!remaining.isEmpty()) { + long timeout = deadline - System.nanoTime(); + assertTrue("Expected WatchService events " + remaining, timeout > 0); + WatchKey key = watcher.poll(timeout, TimeUnit.NANOSECONDS); + assertNotNull("Expected WatchService events " + remaining, key); + for (WatchEvent event : key.pollEvents()) { + for (Iterator it = remaining.iterator(); it.hasNext();) { + ExpectedWatchEvent candidate = it.next(); + if (candidate.kind == event.kind() && candidate.context.equals(event.context())) { + it.remove(); + break; + } + } + } + assertTrue("WatchService key is no longer valid", key.reset()); + } + } + + private void assertWatchEventPresent(WatchService watcher, ExpectedWatchEvent expected) throws Exception { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (true) { + long timeout = deadline - System.nanoTime(); + assertTrue("Expected WatchService event " + expected, timeout > 0); + WatchKey key = watcher.poll(timeout, TimeUnit.NANOSECONDS); + assertNotNull("Expected WatchService event " + expected, key); + boolean found = false; + for (WatchEvent event : key.pollEvents()) { + assertEquals("Unexpected WatchService event kind", expected.kind, event.kind()); + assertEquals("Unexpected WatchService event context", expected.context, event.context()); + found = true; + } + assertTrue("WatchService key is no longer valid", key.reset()); + if (found) { + return; + } + } + } + + private static final class ExpectedWatchEvent { + private final WatchEvent.Kind kind; + private final Path context; + + ExpectedWatchEvent(WatchEvent.Kind kind, Path context) { + this.kind = kind; + this.context = context; + } + + @Override + public String toString() { + return kind.name() + ": " + context; + } + } + + private FileObject getFileObject() { + FileObject fileObject = root.getFileObject("pathtest/dir/file.txt"); + assertNotNull(fileObject); + return fileObject; + } + + private Path getPath() { + return FileUtil.toPath(getFileObject()); + } +} diff --git a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/XMLFileSystemTest.java b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/XMLFileSystemTest.java index 6380136376a5..3441b442a7b3 100644 --- a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/XMLFileSystemTest.java +++ b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/XMLFileSystemTest.java @@ -42,6 +42,7 @@ public static Test suite() { NbTestSuite suite = new NbTestSuite(); suite.addTestSuite(FileSystemTestHid.class); suite.addTestSuite(FileObjectTestHid.class); + suite.addTestSuite(PathTestHid.class); suite.addTestSuite(XMLFileSystemTestHid.class); return new XMLFileSystemTest(suite); diff --git a/platform/openide.loaders/test/unit/src/org/openide/loaders/FileLookupViaDataObjectTest.java b/platform/openide.loaders/test/unit/src/org/openide/loaders/FileLookupViaDataObjectTest.java index 3bede8606434..d3bc7f0610b3 100644 --- a/platform/openide.loaders/test/unit/src/org/openide/loaders/FileLookupViaDataObjectTest.java +++ b/platform/openide.loaders/test/unit/src/org/openide/loaders/FileLookupViaDataObjectTest.java @@ -23,6 +23,7 @@ import org.netbeans.junit.NbTestSuite; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileObjectTestHid; +import org.openide.filesystems.PathTestHid; import org.openide.filesystems.FileUtil; import org.openide.filesystems.LocalFileSystemTest; @@ -34,6 +35,7 @@ public FileLookupViaDataObjectTest(Test test) { public static Test suite() { NbTestSuite s = new NbTestSuite(); s.addTestSuite(FileObjectTestHid.class); + s.addTestSuite(PathTestHid.class); s.addTestSuite(Hid.class); return new FileLookupViaDataObjectTest(s); }