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/masterfs/test/unit/src/org/netbeans/modules/masterfs/providers/ProvidedExtensionsTest.java b/platform/masterfs/test/unit/src/org/netbeans/modules/masterfs/providers/ProvidedExtensionsTest.java index fda7aed60e55..27f42a259dd1 100644 --- a/platform/masterfs/test/unit/src/org/netbeans/modules/masterfs/providers/ProvidedExtensionsTest.java +++ b/platform/masterfs/test/unit/src/org/netbeans/modules/masterfs/providers/ProvidedExtensionsTest.java @@ -874,7 +874,7 @@ public boolean accept(File pathname) { return accepted; } }); - return childs.length == 0; + return childs.length == 0 && file.delete(); } return file.delete(); } diff --git a/platform/o.n.bootstrap/src/org/netbeans/NbFileTypeDetector.java b/platform/o.n.bootstrap/src/org/netbeans/NbFileTypeDetector.java new file mode 100644 index 000000000000..150863031bb8 --- /dev/null +++ b/platform/o.n.bootstrap/src/org/netbeans/NbFileTypeDetector.java @@ -0,0 +1,59 @@ +/* + * 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; + +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.spi.FileTypeDetector; +import org.openide.util.Lookup; +import org.openide.util.lookup.ServiceProvider; + +/** Delegates to other detectors registered in the NetBeans runtime. + *

+ * {@code Files.probeContentType }loads installed detectors with + * {@code ServiceLoader.load(FileTypeDetector.class, ClassLoader.getSystemClassLoader())}. + * In the running IDE registered detectors are however loaded by different classloaders. + * To mitigate that this class (registered on NetBeans application classapath) + * obtains all registered detectors (including + * {@code org.netbeans.modules.openide.filesystems.declmime.NioFileTypeDetector}) + * and delegates to them explicitly. + */ +@ServiceProvider(service = FileTypeDetector.class) +public final class NbFileTypeDetector extends FileTypeDetector { + private final Lookup.Result all; + + public NbFileTypeDetector() { + all = Lookup.getDefault().lookupResult(FileTypeDetector.class); + } + + @Override + public String probeContentType(Path path) throws IOException { + for (FileTypeDetector detector : all.allInstances()) { + if (detector == this) { + continue; + } + + String mime = detector.probeContentType(path); + if (mime != null) { + return mime; + } + } + return null; + } +} diff --git a/platform/o.n.core/nbproject/project.properties b/platform/o.n.core/nbproject/project.properties index e36f5298b657..318091a080b5 100644 --- a/platform/o.n.core/nbproject/project.properties +++ b/platform/o.n.core/nbproject/project.properties @@ -34,6 +34,7 @@ test.excludes=\ test.config.commit.includes=\ **/ValidateNbinst*Test.class,\ + **/ValidateMimeTypesTest.class,\ **/ValidateClassFilesTest.class,\ **/ValidateModulesTest.class # Test was disable as it was found to be flaky: diff --git a/platform/o.n.core/test/qa-functional/src/org/netbeans/core/validation/ValidateMimeTypesTest.java b/platform/o.n.core/test/qa-functional/src/org/netbeans/core/validation/ValidateMimeTypesTest.java new file mode 100644 index 000000000000..145dd2967d3d --- /dev/null +++ b/platform/o.n.core/test/qa-functional/src/org/netbeans/core/validation/ValidateMimeTypesTest.java @@ -0,0 +1,82 @@ +/* + * 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.core.validation; + +import java.io.IOException; +import java.nio.file.Files; +import junit.framework.Test; +import junit.framework.TestSuite; +import org.netbeans.junit.NbModuleSuite; +import org.netbeans.junit.NbTestCase; +import org.openide.filesystems.FileUtil; + +/** Checks that {@link Files#pr} and {@link FileObject#get} are consistent + * when running in the NetBeans IDE and platform. Goes thru all + * the templates and verifies their mime types. + */ +public final class ValidateMimeTypesTest extends NbTestCase { + public ValidateMimeTypesTest(String name) { + super(name); + } + + + public static Test suite() { + TestSuite suite = new TestSuite(); + suite.addTest(NbModuleSuite.createConfiguration(ValidateMimeTypesTest.class) + .clusters("(?!ergonomics).*") + .enableClasspathModules(false) + .enableModules(".*") + .gui(false).suite() + ); + return suite; + } + + public void testCheckTemplatesMimeTypes() throws IOException { + var errors = new StringBuilder(); + + var root = FileUtil.getConfigFile("Templates"); + assertNotNull("Templates directory found", root); + var en = root.getChildren(true); + while (en.hasMoreElements()) { + var file = en.nextElement(); + if (file.isFolder()) { + continue; + } + var path = FileUtil.toPath(file); + assertNotNull("Path found for " + file, path); + var nbMime = file.getMIMEType(); + var jdkMime = Files.probeContentType(path); + + if (nbMime.equals(jdkMime)) { + continue; + } + + errors.append("\n") + .append(file) + .append(" mime types differ among NetBeans and JDK: ") + .append(nbMime) + .append(" != ") + .append(jdkMime); + } + if (!errors.isEmpty()) { + errors.insert(0, "Found differences in MIME types:"); + fail(errors.toString()); + } + } +} diff --git a/platform/o.n.core/test/qa-functional/src/org/netbeans/core/validation/ValidateNbinstTest.java b/platform/o.n.core/test/qa-functional/src/org/netbeans/core/validation/ValidateNbinstTest.java index dd3841a8c7dd..5bdc2e2306da 100644 --- a/platform/o.n.core/test/qa-functional/src/org/netbeans/core/validation/ValidateNbinstTest.java +++ b/platform/o.n.core/test/qa-functional/src/org/netbeans/core/validation/ValidateNbinstTest.java @@ -19,59 +19,26 @@ package org.netbeans.core.validation; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileNotFoundException; import java.io.IOException; -import java.io.InputStream; -import java.io.PrintStream; import java.net.URL; -import java.net.URLConnection; import java.text.MessageFormat; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.HashSet; import java.util.List; -import java.util.Map; -import java.util.MissingResourceException; -import java.util.Properties; -import java.util.Set; -import java.util.TreeMap; import java.util.TreeSet; -import java.util.jar.Manifest; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import javax.swing.Action; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParser; -import javax.xml.parsers.SAXParserFactory; import junit.framework.Test; import junit.framework.TestSuite; -import org.netbeans.core.startup.layers.LayerCacheManager; import org.netbeans.junit.NbModuleSuite; import org.netbeans.junit.NbTestCase; -import org.netbeans.junit.Log; -import org.netbeans.junit.RandomlyFails; -import org.openide.cookies.InstanceCookie; import org.openide.filesystems.FileObject; -import org.openide.filesystems.FileSystem; import org.openide.filesystems.FileUtil; -import org.openide.filesystems.MultiFileSystem; -import org.openide.filesystems.XMLFileSystem; -import org.openide.loaders.DataFolder; -import org.openide.loaders.DataObject; -import org.openide.loaders.DataShadow; -import org.openide.modules.Dependency; -import org.openide.util.Enumerations; import org.openide.util.Lookup; import org.openide.util.Mutex; import org.openide.util.NbCollections; diff --git a/platform/openide.filesystems/apichanges.xml b/platform/openide.filesystems/apichanges.xml index 8872f3e0fb66..c6c4f248077e 100644 --- a/platform/openide.filesystems/apichanges.xml +++ b/platform/openide.filesystems/apichanges.xml @@ -19,12 +19,42 @@ under the License. --> - + Filesystems API + + +

FileObject output streams truncate on open and reject writes after close + + + + + + Both FileObject.getOutputStream() + and getOutputStream(FileLock) + truncate the file when the stream is opened, and writing to the stream after + it is closed throws IOException. Implementations of + FileObject must satisfy these requirements. + + + + + + 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/arch.xml b/platform/openide.filesystems/arch.xml index f79c553ee404..7117fc1f8bd2 100644 --- a/platform/openide.filesystems/arch.xml +++ b/platform/openide.filesystems/arch.xml @@ -21,6 +21,7 @@ --> + ]> - + + + toFile + reads the java.io.File attribute from the FileObject to + check for a corresponding java.io.File. If the attribute is + null, it may attempt to find a file using URL mapping. + @@ -857,14 +866,14 @@ No. -->

- + Cover of NetBeans Platform for Beginners book For general overview of the filesystem concepts, related topics, together with code samples, see chapter 3, - of NetBeans Platform for Beginners + of NetBeans Platform for Beginners by Jason Wexbridge and Walter Nyland. Many of the usecases are described at the overall documentation, 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/FileObject.java b/platform/openide.filesystems/src/org/openide/filesystems/FileObject.java index 82470e8c6b35..7ccbc4269dd0 100644 --- a/platform/openide.filesystems/src/org/openide/filesystems/FileObject.java +++ b/platform/openide.filesystems/src/org/openide/filesystems/FileObject.java @@ -769,9 +769,11 @@ public List asLines(final String encoding) throws IOException { } /** Get output stream. + * Writing to the stream after it has been closed throws an {@link IOException}. * @param lock the lock that belongs to this file (obtained by a call to * {@link #lock}) - * @return output stream to overwrite the contents of this file + * @return output stream to overwrite the contents of this file, truncated + * when the stream is opened * @exception IOException if an error occures (the file is invalid, etc.) */ public abstract OutputStream getOutputStream(FileLock lock) @@ -781,8 +783,10 @@ public abstract OutputStream getOutputStream(FileLock lock) * when this file object is {@linkplain #isValid() invalid} - since * version 9.23 it tries to recreate the parent hierarchy * and really open the stream. + * Writing to the stream after it has been closed throws an {@link IOException}. * - * @return output stream to overwrite the contents of this file + * @return output stream to overwrite the contents of this file, truncated + * when the stream is opened * @throws IOException if an error occurs * @throws FileAlreadyLockedException if the file is already locked * @since 6.6 diff --git a/platform/openide.filesystems/src/org/openide/filesystems/FileSystem.java b/platform/openide.filesystems/src/org/openide/filesystems/FileSystem.java index cf298713c856..1b9df623c892 100644 --- a/platform/openide.filesystems/src/org/openide/filesystems/FileSystem.java +++ b/platform/openide.filesystems/src/org/openide/filesystems/FileSystem.java @@ -25,9 +25,11 @@ import java.beans.PropertyChangeSupport; import java.beans.PropertyVetoException; import java.beans.VetoableChangeListener; +import java.io.File; import java.io.IOException; import java.io.Serializable; import java.net.URL; +import java.nio.file.Path; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; @@ -37,6 +39,7 @@ import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; +import static org.openide.filesystems.FileUtil.toFile; import org.openide.util.*; import org.openide.util.lookup.ServiceProvider; import org.openide.util.lookup.ServiceProviders; @@ -52,16 +55,16 @@ * normally includes XML layers created using {@link XMLFileSystem}.

*

Since version 7.1 you can dynamically change the content of the system filesystem. * Either by inserting your own implementation of a filesystem directly or by - * registering so called {@link Repository.LayerProvider}. With the - * {@link Repository.LayerProvider provider} you can show a dialog letting the user log in + * registering so called {@link Repository.LayerProvider}. With the + * {@link Repository.LayerProvider provider} you can show a dialog letting the user log in * to some server and only later make {@link XMLFileSystem additional XML layers} * available. - *

+ *

* In case you need to insert a dynamic file system with various definitions (NetBeans Platform menus, - * toolbars, layout of windows, etc.), you can create a filesystem implementation, + * toolbars, layout of windows, etc.), you can create a filesystem implementation, * then register it in default lookup. - * It is easiest to subclass {@link AbstractFileSystem} and implement - * few simple query interfaces ({@link AbstractFileSystem.List}, + * It is easiest to subclass {@link AbstractFileSystem} and implement + * few simple query interfaces ({@link AbstractFileSystem.List}, * {@link AbstractFileSystem.Info}, {@link AbstractFileSystem.Change}). * For example:

*
@@ -80,16 +83,16 @@ public static void initialize() throws SAXException {
         LoginFileSystem lfs = {@link Lookup}.getDefault().lookup(LoginFileSystem.class);
         lfs.initializeSomehow();
     }
-     
+
     private void initializeSomehow() {
         // do some initialization
         super.refresh();
-    } 
-    
+    }
+
     public String[] children(String path) {
         // compute list of children somehow
     }
-    
+
     // other method implementations follow...
 }
  * 
@@ -124,7 +127,7 @@ public abstract class FileSystem implements Serializable { /** Property name giving display name of filesystem. * @since 2.1 */ - public static final String PROP_DISPLAY_NAME = "displayName"; // NOI18N + public static final String PROP_DISPLAY_NAME = "displayName"; // NOI18N /** Property name giving root folder of filesystem. */ public static final String PROP_ROOT = "root"; // NOI18N @@ -170,6 +173,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() { @@ -276,17 +280,17 @@ protected final void setSystemName(String name) throws PropertyVetoException { o = systemName; n = systemName = name.intern(); } - + firePropertyChange(PROP_SYSTEM_NAME, o, n); /** backward compatibility for FileSystems that don`t fire * PROP_DISPLAY_NAME*/ firePropertyChange(PROP_DISPLAY_NAME, null, null); } - + /** * Caches the value of 'default' flag. It is extremely costly to call to FileUtil.getConfigRoot() - * during startup, as the getter for repository waits for the rapidly changing default Lookup. + * during startup, as the getter for repository waits for the rapidly changing default Lookup. * In a multi-context environment, the flag might be inappropriate for the current execution context; * an execution "A" could possibly reach an instance of default FS for execution "B". But as the two execution * should each operate with a different Repository with distinct instances of FileSystems, such condition @@ -311,7 +315,7 @@ public final boolean isDefault() { Exceptions.printStackTrace(ex); } if (defFS != null) { - // XXX hotfix + // XXX hotfix // assert defFS == (this == fs) : "Default filesystem used in foreign execution"; } return defFS = (this == fs); @@ -385,7 +389,7 @@ public FileObject find(String aPackage, String name, String ext) { /** Returns temporary folder if it is avaliable on this file system. * Method never returns null. IOException is thrown instead. * @return a file object for temporary folder - * @throws IOException + * @throws IOException * @since 7.60 */ public FileObject getTempFolder() throws IOException { @@ -399,20 +403,20 @@ public FileObject getTempFolder() throws IOException { * @param suffix suffix of the name of created file * @param deleteOnExit delete file on exit * @return new temporary file - * @throws IOException + * @throws IOException * @since 7.60 */ public FileObject createTempFile(FileObject parent, String prefix, String suffix, boolean deleteOnExit) throws IOException { throw new IOException("Unsupported operation"); // NOI18N } - + /** Finds various extensions for set of file objects coming from * this file system. * For example actions should be obtainable as:
      * actions = fs.{@link #findExtrasFor(java.util.Set) findExtrasFor}(foSet).{@link Lookup#lookupAll(java.lang.Class) lookupAll}({@link javax.swing.Action});
      * 
* @param objects the set of objects - * @return the lookup providing various extensions (usually visual) + * @return the lookup providing various extensions (usually visual) * for these objects * @since 8.12 */ @@ -435,9 +439,9 @@ private void readObject(java.io.ObjectInputStream in) public String toString() { return getSystemName() + "[" + super.toString() + "]"; // NOI18N } - + private static volatile Lookup.Result statusResult; - + private static StatusDecorator defaultStatus() { if (statusResult == null) { statusResult = Lookup.getDefault().lookupResult(StatusDecorator.class); @@ -472,7 +476,7 @@ private static StatusDecorator defaultStatus() { public StatusDecorator getDecorator() { return isDefault() ? defaultStatus() : STATUS_NONE; } - + /** Executes atomic action. The atomic action represents a set of * operations constituting one logical unit. It is guaranteed that during * execution of such an action no events about changes in the filesystem @@ -737,6 +741,27 @@ public final void removeFileChangeListener(FileChangeListener fcl) { void waitRefreshed() { } + final synchronized Path toVirtualPath(FileObject fo) { + if (nioFs == null) { + nioFs = new NioFsForFileSystem(this); + } + return NioPathForFileObject.create(fo, nioFs); + } + + /** Convert a fileobject to Path. Internally overridable by {@link MultiFileSystem}. + * + * @param fo + * @return + */ + Path toPath(FileObject fo) { + File f = FileUtil.toFile(fo); + if (f != null) { + return f.toPath(); + } else { + return toVirtualPath(fo); + } + } + /** 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. @@ -758,7 +783,7 @@ public static interface AtomicAction { */ public void run() throws IOException; } - + static interface AsyncAtomicAction extends AtomicAction { boolean isAsynchronous(); } diff --git a/platform/openide.filesystems/src/org/openide/filesystems/FileUtil.java b/platform/openide.filesystems/src/org/openide/filesystems/FileUtil.java index e2ebc7aa6200..d48ec1bbb06a 100644 --- a/platform/openide.filesystems/src/org/openide/filesystems/FileUtil.java +++ b/platform/openide.filesystems/src/org/openide/filesystems/FileUtil.java @@ -35,6 +35,7 @@ import java.net.URISyntaxException; import java.net.URL; import java.net.URLStreamHandler; +import java.nio.channels.FileChannel; import java.nio.file.Files; import java.nio.file.InvalidPathException; import java.nio.file.Path; @@ -63,6 +64,7 @@ import java.util.jar.JarInputStream; import java.util.logging.Level; import java.util.logging.Logger; + import org.netbeans.modules.openide.filesystems.declmime.MIMEResolverImpl; import org.openide.filesystems.FileSystem.AtomicAction; import org.openide.filesystems.spi.ArchiveRootProvider; @@ -802,12 +804,21 @@ public static FileObject createData(FileObject folder, String name) throws IOExc return data; } - /** Finds appropriate java.io.File to FileObject if possible. - * If not possible then null is returned. + /** Finds appropriate {@link File} for the provided {@link FileObject}, if possible. + * If you need JDK interoperability, + * consider using {@link #toPath(FileObject)} for obtaining a {@link Path} instead. + * The {@link #toPath(FileObject)} method is guaranteed to never return {@code null} + * for a valid {@link FileObject}. * This is the inverse operation of {@link #toFileObject}. + *

+ * Implementation note: This method checks {@code fo.getAttribute("java.io.File")} first, + * before attempting to resolve the file via URL mapping. + * * @param fo FileObject whose corresponding File will be looked for * @return java.io.File or null if no corresponding File exists. * @since 1.29 + * @see #toFileObject(File) + * @see #toPath */ public static File toFile(FileObject fo) { File retVal = (File) fo.getAttribute("java.io.File"); // NOI18N; @@ -833,16 +844,43 @@ 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 {@link Path} instance is created even for fully virtual {@code FileObject}s. + * + *

Emulation of {@link FileChannel} and {@link java.nio.channels.SeekableByteChannel}

+ * + * {@link FileChannel#open(Path, OpenOption...) Opening a writable channel} + * for a virtual path acquires a {@link FileObject#lock()} + * until the channel closes; another writable + * channel cannot be opened while the file is locked. It is recommended to + * finish all channel operations before closing it. A writable virtual + * channel returns the same exclusive whole-file lock for every lock + * request, regardless of the requested range or sharing mode. Releasing it + * has no effect; it remains valid until the channel closes. + * A virtual channel loads the file content into memory when it opens. Reads + * use that in-memory content; writes remain there until {@link FileChannel#force(boolean)} + * or close writes the pending content to the {@link FileObject}. Changes are + * not visible to other {@code FileObject} readers until then. + * Unlike native channels, a read-only virtual channel cannot be locked; + * both shared and exclusive lock requests throw + * {@link java.nio.channels.NonWritableChannelException}. + * Native paths use the native provider's locking instead. + * + * 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) { - File f = toFile(fo); - return f != null ? f.toPath() : null; + try { + Parameters.notNull("fo", fo); + return fo.getFileSystem().toPath(fo); + } catch (FileStateInvalidException ex) { + throw new IllegalStateException("FileObject has no valid filesystem", ex); + } } /** @@ -917,8 +955,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/MemoryFileSystem.java b/platform/openide.filesystems/src/org/openide/filesystems/MemoryFileSystem.java index 3f71c9fc2176..21368f756208 100644 --- a/platform/openide.filesystems/src/org/openide/filesystems/MemoryFileSystem.java +++ b/platform/openide.filesystems/src/org/openide/filesystems/MemoryFileSystem.java @@ -33,21 +33,21 @@ import java.net.URLConnection; import java.net.URLStreamHandler; import java.util.ArrayList; -import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; -import java.util.Iterator; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; +import java.util.function.Function; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.openide.util.Enumerations; import org.openide.util.URLStreamHandlerRegistration; import org.openide.util.lookup.ServiceProvider; @@ -57,6 +57,7 @@ */ final class MemoryFileSystem extends AbstractFileSystem implements AbstractFileSystem.Info, AbstractFileSystem.Change, AbstractFileSystem.List, AbstractFileSystem.Attr { private static final Logger ERR = Logger.getLogger(MemoryFileSystem.class.getName()); + private static final byte[] EMPTY_ARR = new byte[0]; private static final AtomicLong COUNT = new AtomicLong(); private final long id = COUNT.incrementAndGet(); @@ -100,15 +101,24 @@ public MemoryFileSystem(String[] resources) { if (resources[i].endsWith("/")) { // folder - getOrCreateEntry(resources[i]).data = null; + onEntry(resources[i], (entry) -> { + entry.data = null; + return null; + }); } else { - getOrCreateEntry(resources[i]).data = new byte[0]; + onEntry(resources[i], (entry) -> { + entry.data = EMPTY_ARR; + return null; + }); } } } - /** finds entry for given name */ - private Entry getOrCreateEntry(String n) { + /** Locates entry of given name and performs an action on + * it. The lookup of the entry is synchronized on {@link #entries} field. + * The action runs inside of the {@link #entries} monitor as well. + */ + private T onEntry(String n, Function action) { if ((n.length() > 0) && (n.charAt(0) == '/')) { n = n.substring(1); } @@ -122,7 +132,7 @@ private Entry getOrCreateEntry(String n) { entries.put(n, x); } - return x; + return action.apply(x); } } @@ -167,13 +177,17 @@ public boolean isReadOnly() { return false; } + @Override public Enumeration attributes(String name) { if (!isValidEntry(name)) { - return org.openide.util.Enumerations.empty(); + return Enumerations.empty(); + } else { + String[] snapshot = onEntry(name, entry -> entry.attrs.keySet().toArray(String[]::new)); + return Enumerations.array(snapshot); } - return Collections.enumeration(getOrCreateEntry(name).attrs.keySet()); } + @Override public String[] children(String f) { if ((f.length() > 0) && (f.charAt(0) == '/')) { f = f.substring(1); @@ -208,6 +222,7 @@ public String[] children(String f) { } } + @Override public void createData(String name) throws IOException { if (isValidEntry(name, Boolean.FALSE)) { StringBuffer message = new StringBuffer(); @@ -215,7 +230,10 @@ public void createData(String name) throws IOException { throw new IOException(message.toString());//NOI18N } - getOrCreateEntry(name).data = new byte[0]; + onEntry(name, (entry) -> { + entry.data = new byte[0]; + return null; + }); } public void createFolder(String name) throws java.io.IOException { @@ -225,7 +243,10 @@ public void createFolder(String name) throws java.io.IOException { throw new IOException(message.toString());//NOI18N } - getOrCreateEntry(name).data = null; + onEntry(name, (entry) -> { + entry.data = null; + return null; + }); } public void delete(String name) throws IOException { @@ -237,23 +258,21 @@ public void delete(String name) throws IOException { public void deleteAttributes(String name) { } + @Override public boolean folder(String name) { - return getOrCreateEntry(name).data == null; + return onEntry(name, (entry) -> entry.data == null); } public InputStream inputStream(String name) throws java.io.FileNotFoundException { - byte[] arr = getOrCreateEntry(name).data; - + byte[] arr = onEntry(name, (entry) -> entry.data); if (arr == null) { arr = new byte[0]; } - return new ByteArrayInputStream(arr); } public java.util.Date lastModified(String name) { - java.util.Date d = getOrCreateEntry(name).last; - + java.util.Date d = onEntry(name, (entry) -> entry.last); return (d == null) ? created : d; } @@ -263,19 +282,28 @@ public void lock(String name) throws IOException { public void markUnimportant(String name) { } + @Override public String mimeType(String name) { - return (String) getOrCreateEntry(name).attrs.get("mimeType"); + return onEntry(name, (entry) -> (String)entry.attrs.get("mimeType")); } + @Override public OutputStream outputStream(final String name) throws java.io.IOException { + onEntry(name, (entry) -> { + entry.data = new byte[0]; + return null; + }); class Out extends ByteArrayOutputStream { @Override public void close() throws IOException { super.close(); - getOrCreateEntry(name).data = toByteArray(); - getOrCreateEntry(name).last = new Date(); + onEntry(name, (entry) -> { + entry.data = toByteArray(); + entry.last = new Date(); + return null; + }); } } @@ -283,7 +311,7 @@ public void close() throws IOException { } public Object readAttribute(String name, String attrName) { - return isValidEntry(name) ? getOrCreateEntry(name).attrs.get(attrName) : null; + return isValidEntry(name) ? onEntry(name, (entry) -> entry.attrs.get(attrName)) : null; } public boolean readOnly(String name) { @@ -318,18 +346,22 @@ public void rename(String oldName, String newName) public void renameAttributes(String oldName, String newName) { } + @Override public long size(String name) { - byte[] d = getOrCreateEntry(name).data; - + byte[] d = onEntry(name, (entry) -> entry.data); return (d == null) ? 0 : d.length; } public void unlock(String name) { } + @Override public void writeAttribute(String name, String attrName, Object value) throws IOException { - getOrCreateEntry(name).attrs.put(attrName, value); + onEntry(name, entry -> { + entry.attrs.put(attrName, value); + return null; + }); } private Map initEntry() { @@ -360,10 +392,12 @@ public MemoryFileSystem.Entry remove(String key) { } static final class Entry { - /** String, Object */ - public Map attrs = Collections.synchronizedMap(new HashMap()); - public byte[] data; - public java.util.Date last; + /** @GuardedBy("entries") */ + Map attrs = new HashMap<>(); + /** @GuardedBy("entries") */ + byte[] data; + /** @GuardedBy("entries") */ + java.util.Date last; private final String entryName; Entry(String entryName) { diff --git a/platform/openide.filesystems/src/org/openide/filesystems/MultiFileSystem.java b/platform/openide.filesystems/src/org/openide/filesystems/MultiFileSystem.java index 6b5122eb8154..4dd114787823 100644 --- a/platform/openide.filesystems/src/org/openide/filesystems/MultiFileSystem.java +++ b/platform/openide.filesystems/src/org/openide/filesystems/MultiFileSystem.java @@ -20,6 +20,7 @@ package org.openide.filesystems; import java.io.IOException; +import java.nio.file.Path; import java.util.Arrays; import java.util.Collection; import java.util.Collections; @@ -95,10 +96,10 @@ * be able to mask files not provided by their immediate siblings, but by cousins. For this reason, nested * subclasses may call {@link #setPropagateMasks} to make the mask files propagate up one or more nesting levels * and thus remain potent against cousin delegates. - * - *

To support rollback, two pseudo-attribute is defined since 8.5: {@code revealEntries} typed - * as Map<String, FileObject & Callable>. The attribute is available on a folder, and contains information - * on child FileObjects, which have been overriden or masked by the writable layer of the MFS. Map is keyed by + * + *

To support rollback, two pseudo-attribute is defined since 8.5: {@code revealEntries} typed + * as Map<String, FileObject & Callable>. The attribute is available on a folder, and contains information + * on child FileObjects, which have been overriden or masked by the writable layer of the MFS. Map is keyed by * child name, the value is a FileObject that allows access to the masked child attributes and/or content. *

* The returned FileObjects do not leak its neighbours from the lower layers. The parent, children or siblings are @@ -243,19 +244,19 @@ private MultiFileObject getMultiRoot() { synchronized (MultiFileSystem.class) { if (root != null) { retval = root; - } + } } - + if (retval == null) { retval = new MultiFileObject(this); } - + synchronized (MultiFileSystem.class) { if (root == null) { root = retval; - } + } } - + return root; } @@ -598,4 +599,17 @@ boolean canHaveRootAttributeOnReadOnlyFS(String name) { } return tmp.contains(name); } + + /** + * Always use {@link #toVirtualPath} as the multi filesystem mixes + * different levels and needs to keep the "virtualized abstraction" to + * merge them properly. + * + * @param fo + * @return + */ + @Override + Path toPath(FileObject fo) { + return toVirtualPath(fo); + } } diff --git a/platform/openide.filesystems/src/org/openide/filesystems/NioFileObjectChannel.java b/platform/openide.filesystems/src/org/openide/filesystems/NioFileObjectChannel.java new file mode 100644 index 000000000000..cf14d4f4acd0 --- /dev/null +++ b/platform/openide.filesystems/src/org/openide/filesystems/NioFileObjectChannel.java @@ -0,0 +1,662 @@ +/* + * 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.OutputStream; +import java.nio.ByteBuffer; +import java.nio.MappedByteBuffer; +import java.nio.channels.ClosedChannelException; +import java.nio.channels.ClosedByInterruptException; +import java.nio.channels.FileChannel; +import java.nio.channels.NonReadableChannelException; +import java.nio.channels.NonWritableChannelException; +import java.nio.channels.ReadableByteChannel; +import java.nio.channels.WritableByteChannel; +import java.nio.file.FileAlreadyExistsException; +import java.nio.file.NoSuchFileException; +import java.nio.file.OpenOption; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.FileAttribute; +import java.util.Arrays; +import java.util.Objects; +import java.util.Set; + +final class NioFileObjectChannel extends FileChannel { + /** typical size for a buffer operation */ + private static final int CHUNK_SIZE = 8192; + /* + * State.class guards channel state. A writable channel owns its FileObject lock + * until close, even if an operation is still running. All operations reserve + * the channel while accessing its in-memory content; a reentrant operation + * cannot safely wait for its own reservation. + */ + private final FileObject file; + private final NioLock nioLock; + private final boolean readable; + private final boolean append; + // A reentrant close cannot wait for its own operation, so that operation + // releases the FileObject lock on exit. Keep this outside State: changing + // its snapshot during the operation would invalidate its completion. + private volatile boolean closeLockDeferred; + // @GuardedBy("State.class") Every transition creates a fresh snapshot. + // all methods manipulating this field should be inside of {@link State} class + private State state; + private NioFileObjectChannel(FileObject file, FileLock fileLock, boolean readable, boolean append) + throws IOException { + this.file = file; + this.nioLock = fileLock == null ? null : new NioLock(this, fileLock); + this.readable = readable; + this.append = append; + ByteBuffer content = ByteBuffer.wrap(file.asBytes()); + this.state = new State(append ? content.limit() : 0, null, content, false); + } + + static FileChannel open(NioPathForFileObject path, Set options, + FileAttribute... attrs) throws IOException { + boolean read = false; + boolean write = false; + boolean append = false; + for (OpenOption option : options) { + Objects.requireNonNull(option, "option"); + if (option == StandardOpenOption.READ) { + read = true; + continue; + } + if (option == StandardOpenOption.WRITE) { + write = true; + continue; + } + if (option == StandardOpenOption.APPEND) { + append = true; + continue; + } + if ( + option != StandardOpenOption.CREATE && + option != StandardOpenOption.CREATE_NEW && + option != StandardOpenOption.TRUNCATE_EXISTING + ) { + throw new UnsupportedOperationException("Unsupported open option: " + option); + } + } + if (append && read || append && options.contains(StandardOpenOption.TRUNCATE_EXISTING)) { + throw new IllegalArgumentException("Invalid append options"); + } + write |= append; + if (!read && !write) { + read = true; + } + if (attrs.length != 0) { + throw new UnsupportedOperationException("No attributes specified!"); + } + FileObject file = findFile(path, options, write); + FileLock token = write ? file.lock() : null; + NioFileObjectChannel channel = null; + try { + if (token != null && !token.isValid()) { + throw new IOException("FileObject does not support locking: " + file); + } + channel = new NioFileObjectChannel(file, token, read, append); + if (write && options.contains(StandardOpenOption.TRUNCATE_EXISTING)) { + channel.truncate(0); + } + return channel; + } catch (IOException | RuntimeException | Error ex) { + try { + if (channel != null) { + channel.close(); + } else if (token != null) { + token.releaseLock(); + } + } catch (IOException | RuntimeException | Error closeException) { + ex.addSuppressed(closeException); + } + throw ex; + } + } + + static FileObject findFile(NioPathForFileObject path, Set options, + boolean write) throws IOException { + FileObject file = path.getFileObject(); + if (file != null && file.isValid() && write && options.contains(StandardOpenOption.CREATE_NEW)) { + throw new FileAlreadyExistsException(path.toString()); + } + if (file == null || !file.isValid()) { + if (!write || !(options.contains(StandardOpenOption.CREATE) || options.contains(StandardOpenOption.CREATE_NEW))) { + throw new NoSuchFileException(path.toString()); + } + NioPathForFileObject parent = (NioPathForFileObject) path.getParent(); + FileObject folder = parent == null ? null : parent.getFileObject(); + if (folder == null || !folder.isValid()) { + throw new NoSuchFileException(path.toString()); + } + file = folder.createData(path.getFileName().toString()); + } + if (!file.isData()) { + throw new IOException("Not a regular file: " + path); + } + if (write && file.isReadOnly()) { + throw new java.nio.file.AccessDeniedException(path.toString()); + } + return file; + } + + private void checkOpen() throws ClosedChannelException { + if (!isOpen()) { + throw new ClosedChannelException(); + } + } + + private ClosedByInterruptException interruptedOperation() throws IOException { + try { + close(); + } finally { + Thread.currentThread().interrupt(); + } + return new ClosedByInterruptException(); + } + + @Override + public int read(ByteBuffer dst) throws IOException { + checkReadable(dst); + if (!dst.hasRemaining()) { + return 0; + } + State previous = State.beginOperation(this); + State next = previous; + try { + int count = readImpl(dst, previous.position(), previous.content()); + if (count > 0) { + next = previous.withPosition(previous.position() + count); + } + return count; + } finally { + State.endOperation(this, previous, next); + } + } + + @Override + public int read(ByteBuffer dst, long at) throws IOException { + checkReadable(dst); + if (at < 0) { + throw new IllegalArgumentException("Negative position"); + } + if (!dst.hasRemaining()) { + return 0; + } + State previous = State.beginOperation(this); + try { + return readImpl(dst, at, previous.content()); + } finally { + State.endOperation(this, previous, previous); + } + } + + private void checkReadable(ByteBuffer dst) throws IOException { + checkOpen(); + if (!readable) { + throw new NonReadableChannelException(); + } + if (dst.isReadOnly()) { + throw new IllegalArgumentException("Read-only buffer"); + } + } + + private static int readImpl(ByteBuffer dst, long at, ByteBuffer content) { + int size = content.limit(); + if (at >= size) { + return -1; + } + int start = (int) at; + int count = Math.min(Math.min(dst.remaining(), CHUNK_SIZE), size - start); + dst.put(content.array(), start, count); + return count; + } + + @Override + public long read(ByteBuffer[] dsts, int offset, int length) throws IOException { + checkOpen(); + if (!readable) { + throw new NonReadableChannelException(); + } + Objects.checkFromIndexSize(offset, length, dsts.length); + int maximum = 0; + for (int i = offset; i < offset + length; i++) { + checkReadable(dsts[i]); + maximum += Math.min(dsts[i].remaining(), CHUNK_SIZE - maximum); + } + if (maximum == 0) { + return 0; + } + State previous = State.beginOperation(this); + State next = previous; + try { + if (previous.position() >= previous.size()) { + return -1; + } + int copied = 0; + long at = previous.position(); + for (int i = offset; i < offset + length && copied < maximum; i++) { + int count = Math.min(dsts[i].remaining(), maximum - copied); + count = Math.min(count, previous.size() - (int) at); + if (count > 0) { + dsts[i].put(previous.content().array(), (int) at, count); + at += count; + copied += count; + } + } + if (copied > 0) { + next = previous.withPosition(previous.position() + copied); + } + return copied; + } finally { + State.endOperation(this, previous, next); + } + } + + @Override + public int write(ByteBuffer src) throws IOException { + State previous = State.beginOperation(this); + State next = previous; + try { + long at = append ? previous.size() : previous.position(); + int start = src.position(); + next = writeImpl(previous, src, at); + int n = src.position() - start; + next = next.withPosition(at + n); + return n; + } finally { + State.endOperation(this, previous, next); + } + } + + @Override + public int write(ByteBuffer src, long at) throws IOException { + State previous = State.beginOperation(this); + State next = previous; + int start = src.position(); + try { + next = writeImpl(previous, src, at); + return src.position() - start; + } finally { + State.endOperation(this, previous, next); + } + } + + private State writeImpl(State state, ByteBuffer src, long at) throws IOException { + if (nioLock == null) { + throw new NonWritableChannelException(); + } + if (at < 0) { + throw new IllegalArgumentException("Negative position"); + } + int start = src.position(); + int count = src.remaining(); + if (count == 0) { + return state; + } + if (at > Integer.MAX_VALUE - count) { + throw new IOException("File is too large for virtual channel"); + } + int end = Math.max(state.size(), (int) at + count); + ByteBuffer content = ensureCapacity(state.content(), end); + if (at > state.size()) { + Arrays.fill(content.array(), state.size(), (int) at, (byte) 0); + } + src.get(start, content.array(), (int) at, count); + src.position(start + count); + content.limit(end); + return state.withContent(content).withDirty(true); + } + + private static ByteBuffer ensureCapacity(ByteBuffer content, int size) { + if (size > content.capacity()) { + int doubled = content.capacity() <= Integer.MAX_VALUE / 2 + ? content.capacity() * 2 : Integer.MAX_VALUE; + return ByteBuffer.wrap(Arrays.copyOf(content.array(), Math.max(size, doubled))); + } + return content.duplicate(); + } + + @Override + public long write(ByteBuffer[] srcs, int offset, int length) throws IOException { + State previous = State.beginOperation(this); + State next = previous; + try { + if (nioLock == null) { + throw new NonWritableChannelException(); + } + Objects.checkFromIndexSize(offset, length, srcs.length); + long total = 0; + for (int i = offset; i < offset + length; i++) { + long at = append ? next.size() : next.position(); + int start = srcs[i].position(); + next = writeImpl(next, srcs[i], at); + int n = srcs[i].position() - start; + next = next.withPosition(at + n); + total += n; + } + return total; + } finally { + State.endOperation(this, previous, next); + } + } + + @Override + public long position() throws IOException { + checkOpen(); + return State.snapshot(this).position(); + } + + @Override + public FileChannel position(long newPosition) throws IOException { + State previous = State.beginOperation(this); + State next = previous; + try { + if (newPosition < 0) { + throw new IllegalArgumentException("Negative position"); + } + next = previous.withPosition(newPosition); + return this; + } finally { + State.endOperation(this, previous, next); + } + } + + @Override + public long size() throws IOException { + checkOpen(); + return State.snapshot(this).size(); + } + + @Override + public FileChannel truncate(long size) throws IOException { + State previous = State.beginOperation(this); + State next = previous; + try { + if (nioLock == null) { + throw new NonWritableChannelException(); + } + if (size < 0) { + throw new IllegalArgumentException("Negative size"); + } + if (size < previous.size()) { + ByteBuffer content = previous.content().duplicate(); + content.limit((int) size); + next = previous.withContent(content).withDirty(true); + } + next = next.withPosition(Math.min(previous.position(), size)); + return this; + } finally { + State.endOperation(this, previous, next); + } + } + + @Override + public void force(boolean metaData) throws IOException { + State previous = State.beginOperation(this); + State next = previous; + try { + if (previous.dirty()) { + writeBytes(previous.content()); + next = previous.withDirty(false); + } + } finally { + State.endOperation(this, previous, next); + } + } + + private void writeBytes(ByteBuffer content) throws IOException { + try (OutputStream output = file.getOutputStream(nioLock.fileLock)) { + output.write(content.array(), 0, content.limit()); + } + } + + @Override + public long transferTo(long position, long count, WritableByteChannel target) throws IOException { + checkOpen(); + if (!readable) { + throw new NonReadableChannelException(); + } + Objects.requireNonNull(target, "target"); + if (position < 0 || count < 0) { + throw new IllegalArgumentException(); + } + long total = 0; + ByteBuffer buffer = ByteBuffer.allocate((int) Math.min(count, CHUNK_SIZE)); + while (total < count) { + buffer.clear(); + buffer.limit((int) Math.min(buffer.capacity(), count - total)); + int n = read(buffer, position + total); + if (n <= 0) { + break; + } + buffer.flip(); + int written = target.write(buffer); + total += written; + if (written < n) { + break; + } + } + return total; + } + + @Override + public long transferFrom(ReadableByteChannel src, long position, long count) throws IOException { + checkOpen(); + if (nioLock == null) { + throw new NonWritableChannelException(); + } + Objects.requireNonNull(src, "src"); + if (position < 0 || count < 0) { + throw new IllegalArgumentException(); + } + if (position > size()) { + return 0; + } + long total = 0; + ByteBuffer buffer = ByteBuffer.allocate((int) Math.min(count, CHUNK_SIZE)); + while (total < count) { + buffer.clear(); + buffer.limit((int) Math.min(buffer.capacity(), count - total)); + int n = src.read(buffer); + if (n <= 0) { + break; + } + buffer.flip(); + total += write(buffer, position + total); + } + return total; + } + + @Override + public MappedByteBuffer map(MapMode mode, long position, long size) { + throw new UnsupportedOperationException("Mapping virtual files is not supported"); + } + + @Override + public java.nio.channels.FileLock lock(long position, long size, boolean shared) throws IOException { + return tryLock(position, size, shared); + } + + @Override + public java.nio.channels.FileLock tryLock(long position, long size, boolean shared) throws IOException { + checkOpen(); + if (nioLock == null) { + throw new NonWritableChannelException(); + } + return nioLock; + } + + @Override + protected void implCloseChannel() throws IOException { + State.channelClosed(); + if (!State.awaitOperationOnClose(this)) { + closeLockDeferred = nioLock != null; + return; + } + try { + State snapshot = State.snapshot(this); + if (nioLock != null && snapshot.dirty()) { + writeBytes(snapshot.content()); + } + } finally { + if (nioLock != null) { + nioLock.releaseFileLock(); + } + } + } + + private static final class NioLock extends java.nio.channels.FileLock { + private final NioFileObjectChannel channel; + private final FileLock fileLock; + + NioLock(NioFileObjectChannel channel, FileLock fileLock) { + super(channel, 0, Long.MAX_VALUE, false); + this.channel = channel; + this.fileLock = fileLock; + } + + @Override + public boolean isValid() { + return channel.isOpen(); + } + + @Override + public void release() { + // The FileObject lock belongs to the channel and is released on close. + } + + private void releaseFileLock() { + fileLock.releaseLock(); + } + } + + // The buffer limit is the logical size; its shared array is accessed only + // by the reserved operation or by close after the operation completes. + private record State(long position, Thread operationOwner, ByteBuffer content, boolean dirty) { + private static synchronized State snapshot(NioFileObjectChannel self) { + return self.state; + } + + private static synchronized boolean update(NioFileObjectChannel self, State previous, State next) { + if (self.state != previous) { + return false; + } else { + self.state = next; + return true; + } + } + + private State withPosition(long value) { + return new State(value, operationOwner, content, dirty); + } + + private State withContent(ByteBuffer value) { + return new State(position, operationOwner, value, dirty); + } + + private State withDirty(boolean value) { + return new State(position, operationOwner, content, value); + } + + private int size() { + return content.limit(); + } + + private static State beginOperation(NioFileObjectChannel self) throws IOException { + try { + synchronized (State.class) { + State previous = awaitOperation(self); + State next = new State(previous.position(), Thread.currentThread(), + previous.content(), previous.dirty()); + if (!update(self, previous, next)) { + throw new IllegalStateException("Channel state changed during operation reservation"); + } + return next; + } + } catch (InterruptedException ex) { + throw self.interruptedOperation(); + } + } + + private static synchronized State awaitOperation(NioFileObjectChannel self) + throws IOException, InterruptedException { + State snapshot; + while ((snapshot = snapshot(self)).operationOwner() != null) { + self.checkOpen(); + if (snapshot.operationOwner() == Thread.currentThread()) { + throw new IOException("Reentrant channel operation during a write"); + } + State.class.wait(); + } + self.checkOpen(); + return snapshot; + } + + private static void endOperation(NioFileObjectChannel self, State previous, State next) + throws IOException { + boolean closed; + boolean releaseDeferred; + synchronized (State.class) { + if (!update(self, previous, + new State(next.position(), null, next.content(), next.dirty()))) { + throw new IllegalStateException("Channel state changed during operation"); + } + State.class.notifyAll(); + closed = !self.isOpen(); + releaseDeferred = closed && self.closeLockDeferred && self.nioLock != null; + if (releaseDeferred) { + self.closeLockDeferred = false; + } + } + if (releaseDeferred) { + self.nioLock.releaseFileLock(); + } + if (closed) { + throw new ClosedChannelException(); + } + } + + private static boolean awaitOperationOnClose(NioFileObjectChannel self) { + boolean interrupted = false; + synchronized (State.class) { + while (self.state.operationOwner() != null) { + if (self.state.operationOwner() == Thread.currentThread()) { + return false; + } + try { + State.class.wait(); + } catch (InterruptedException ex) { + interrupted = true; + } + } + } + if (interrupted) { + Thread.currentThread().interrupt(); + } + return true; + } + + private static synchronized void channelClosed() { + State.class.notifyAll(); + } + + } +} 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..9e88ca28f6d1 --- /dev/null +++ b/platform/openide.filesystems/src/org/openide/filesystems/NioFsForFileSystem.java @@ -0,0 +1,140 @@ +/* + * 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 name = normalizePath(value.toString()); + FileObject fo = fileSystem.findResource(name); + if (!value.toString().startsWith("/")) { + return NioPathForFileObject.relative(fo, this, name); + } + return NioPathForFileObject.create(fo, this, name); + } + + private static boolean isSlashOrBackSlash(char ch) { + return ch == '/' || ch == '\\'; + } + + static String normalizePath(String name) { + if (name == null) { + return ""; + } + StringBuilder result = new StringBuilder(name.length()); + for (int i = 0; i < name.length(); i++) { + char c = name.charAt(i); + if (isSlashOrBackSlash(c)) { + if (!result.isEmpty() && result.charAt(result.length() - 1) != '/') { + result.append('/'); + } + } else { + result.append(c); + } + } + if (!result.isEmpty() && result.charAt(result.length() - 1) == '/') { + result.setLength(result.length() - 1); + } + return result.toString(); + } + + @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..8241f6a6c779 --- /dev/null +++ b/platform/openide.filesystems/src/org/openide/filesystems/NioPathForFileObject.java @@ -0,0 +1,408 @@ +/* + * 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.net.URISyntaxException; +import java.nio.file.LinkOption; +import java.nio.file.NoSuchFileException; +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; + +import static org.openide.filesystems.NioFsForFileSystem.normalizePath; + +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; + assert normalizePath(name).equals(name) : + "Name should be normalized " + name + " != " + normalizePath(name); + this.name = 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 absolute ? create(fileSystem.getFileSystem().getRoot(), fileSystem) : null; + } + + @Override + public Path getFileName() { + if (name.isEmpty()) { + return absolute ? null : this; + } + 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 absolute ? getRoot() : null; + } + String parentName = name.substring(0, separator); + FileObject parent = fileSystem.getFileSystem().findResource(parentName); + if (parent == null && fileObject != null) { + parent = fileObject.getParent(); + } + return new NioPathForFileObject(parent, fileSystem, parentName, absolute); + } + + @Override + public int getNameCount() { + if (name.isEmpty()) { + return absolute ? 0 : 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); + } + if (name.isEmpty()) { + return this; + } + 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(); + } + if (name.isEmpty()) { + return this; + } + 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 (absolute != nio.absolute) { + return false; + } + if (nio.name.isEmpty()) { + return absolute || name.isEmpty(); + } + 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()) { + assert !part.isEmpty(); + if (part.equals(".")) { + continue; + } + if (part.equals("..")) { + if (!normalized.isEmpty() && !normalized.get(normalized.size() - 1).equals("..")) { + normalized.removeLast(); + } else if (!absolute) { + normalized.add(part); + } + } else { + normalized.add(part); + } + } + String normalizedName = String.join("/", normalized); + FileObject fo = fileSystem.getFileSystem().findResource(normalizedName); + return new NioPathForFileObject(fo, fileSystem, normalizedName, absolute); + } + + @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; + } + Path otherPath = fileSystem.getPath(other); + if (otherPath.isAbsolute()) { + return otherPath; + } + String result = normalizePath(name.isEmpty() ? other : name + "/" + other); + FileObject fo = fileSystem.getFileSystem().findResource(result); + return new NioPathForFileObject(fo, fileSystem, result, absolute); + } + + @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"); + } + if (absolute != nio.absolute) { + throw new IllegalArgumentException("Cannot relativize absolute and relative paths"); + } + 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() { + FileObject root = fileSystem.getFileSystem().getRoot(); + FileObject resolved = name.isEmpty() ? root : fileSystem.getFileSystem().findResource(name); + if (resolved != null) { + return resolved.toURI(); + } + String rootUri = root.toURI().toString(); + try { + String encodedPath = new URI(null, null, "/" + name, null).getRawPath().substring(1); + return URI.create(rootUri + (rootUri.endsWith("/") ? "" : "/") + encodedPath); + } catch (URISyntaxException ex) { + throw new IllegalArgumentException("Cannot represent path as URI: " + name, ex); + } + } + + @Override + public Path toAbsolutePath() { + if (absolute) { + return this; + } + FileObject fo = name.isEmpty() ? fileSystem.getFileSystem().getRoot() + : fileSystem.getFileSystem().findResource(name); + return create(fo, fileSystem, name); + } + + @Override + public Path toRealPath(LinkOption... options) throws IOException { + NioPathForFileObject normalized = (NioPathForFileObject) toAbsolutePath().normalize(); + FileObject resolved = normalized.getFileObject(); + if (resolved == null || !resolved.isValid()) { + throw new NoSuchFileException(toString()); + } + return normalized; + } + + @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<>(); + if (name.isEmpty() && !absolute) { + paths.add(this); + } + 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 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(name); + } + current = current.getParent(); + } + return String.join("/", names.reversed()); + } + + 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..4bf6ddd4bad5 --- /dev/null +++ b/platform/openide.filesystems/src/org/openide/filesystems/NioPathProvider.java @@ -0,0 +1,514 @@ +/* + * 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.FilterOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URI; +import java.nio.channels.Channels; +import java.nio.channels.SeekableByteChannel; +import java.nio.channels.FileChannel; +import java.nio.file.AccessDeniedException; +import java.nio.file.AccessMode; +import java.nio.file.CopyOption; +import java.nio.file.DirectoryIteratorException; +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.StandardOpenOption; +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.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.atomic.AtomicReference; + +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 FileChannel newFileChannel(Path path, Set options, + FileAttribute... attrs) throws IOException { + return NioFileObjectChannel.open(fromPath(path), options, attrs); + } + + @Override + public SeekableByteChannel newByteChannel( + Path path, Set options, FileAttribute... attrs) throws IOException { + return NioFileObjectChannel.open(fromPath(path), options, attrs); + } + + @Override + public DirectoryStream newDirectoryStream(Path dir, DirectoryStream.Filter filter) + throws IOException { + NioPathForFileObject nio = fromPath(dir); + Objects.requireNonNull(filter, "filter"); + FileObject folder = nio.getFileObject(); + if (folder == null || !folder.isValid()) { + throw new NoSuchFileException(dir.toString()); + } + if (!folder.isFolder()) { + throw new NotDirectoryException(dir.toString()); + } + return new FileObjectDirectoryStream(dir, folder.getChildren(), filter); + } + + /** + * Iterates over a snapshot of the directory's children. Unlike the + * {@link DirectoryStream} contract, multiple independent iterators are + * allowed, and {@link #close()} does nothing: existing and new iterators + * remain usable afterward. No directory resource is held open. + */ + private static final class FileObjectDirectoryStream implements DirectoryStream { + private final Path directory; + private final FileObject[] children; + private final Filter filter; + + FileObjectDirectoryStream(Path directory, FileObject[] children, Filter filter) { + this.directory = directory; + this.children = children; + this.filter = filter; + } + + @Override + public Iterator iterator() { + return new FileObjectDirectoryIterator(); + } + + private final class FileObjectDirectoryIterator implements Iterator { + private record State(int index, Path next) {} + private final AtomicReference state = new AtomicReference<>(new State(0, null)); + + @Override + public boolean hasNext() { + while (true) { + State previous = state.get(); + if (previous.next() != null) { + return true; + } + if (previous.index() == children.length) { + return false; + } + // Filtering is outside the state update and may be retried after a concurrent change. + Path candidate = directory.resolve(children[previous.index()].getNameExt()); + boolean accepted; + try { + accepted = filter.accept(candidate); + } catch (IOException ex) { + throw new DirectoryIteratorException(ex); + } + State next = new State(previous.index() + 1, accepted ? candidate : null); + if (state.compareAndSet(previous, next) && accepted) { + return true; + } + } + } + + @Override + public Path next() { + while (true) { + State previous = state.get(); + if (previous.next() == null) { + if (!hasNext()) { + throw new NoSuchElementException(); + } + continue; + } + State next = new State(previous.index(), null); + if (state.compareAndSet(previous, next)) { + return previous.next(); + } + } + } + } + + @Override + public void close() { + } + } + + @Override + public void createDirectory(Path dir, FileAttribute... attrs) throws IOException { + NioPathForFileObject nio = fromPath(dir); + FileObject existing = nio.getFileObject(); + if (existing != null && existing.isValid()) { + throw new java.nio.file.FileAlreadyExistsException(dir.toString()); + } + Path parent = dir.getParent(); + NioPathForFileObject nioParent = parent instanceof NioPathForFileObject ? fromPath(parent) : null; + FileObject folder = nioParent == null ? null : nioParent.getFileObject(); + if (folder == null || !folder.isValid()) { + throw new NoSuchFileException(dir.toString()); + } + folder.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 boolean regularFile = fo.isData(); + final boolean directory = fo.isFolder(); + final long size = fo.getSize(); + 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 regularFile; + } + + @Override + public boolean isDirectory() { + return directory; + } + + @Override + public boolean isSymbolicLink() { + return false; + } + + @Override + public boolean isOther() { + return !regularFile && !directory; + } + + @Override + public long size() { + return size; + } + + @Override + public Object fileKey() { + return fo; + } + }; + return type.cast(attrs); + } + + @Override + public Map readAttributes( + Path path, String attributes, LinkOption... options) throws IOException { + int separator = attributes.indexOf(':'); + if (separator >= 0 && !attributes.substring(0, separator).equals("basic")) { + throw new UnsupportedOperationException("Unsupported attribute view: " + attributes.substring(0, separator)); + } + String selection = attributes.substring(separator + 1); + if (selection.isEmpty()) { + throw new IllegalArgumentException("No attributes specified"); + } + BasicFileAttributes attrs = readAttributes(path, BasicFileAttributes.class, options); + Map all = new HashMap<>(); + all.put("lastModifiedTime", attrs.lastModifiedTime()); + all.put("lastAccessTime", attrs.lastAccessTime()); + all.put("creationTime", attrs.creationTime()); + all.put("size", attrs.size()); + all.put("isRegularFile", attrs.isRegularFile()); + all.put("isDirectory", attrs.isDirectory()); + all.put("isSymbolicLink", attrs.isSymbolicLink()); + all.put("isOther", attrs.isOther()); + all.put("fileKey", attrs.fileKey()); + Map result = new HashMap<>(); + for (String name : selection.split(",", -1)) { + if (name.equals("*")) { + result.putAll(all); + } else if (all.containsKey(name)) { + result.put(name, all.get(name)); + } else { + throw new IllegalArgumentException("Unrecognized attribute: " + name); + } + } + return result; + } + + @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 { + Set selected = new HashSet<>(); + for (OpenOption option : options) { + Objects.requireNonNull(option, "option"); + if (option == StandardOpenOption.READ) { + throw new IllegalArgumentException("READ is not supported for output streams"); + } + selected.add(option); + } + if (selected.isEmpty()) { + selected.add(StandardOpenOption.CREATE); + selected.add(StandardOpenOption.TRUNCATE_EXISTING); + } + selected.add(StandardOpenOption.WRITE); + if (canUseFileObjectOutputStream(selected)) { + return NioFileObjectChannel.findFile(fromPath(path), selected, true).getOutputStream(); + } else { + FileChannel channel = newFileChannel(path, selected); + OutputStream output = Channels.newOutputStream(channel); + return new FilterOutputStream(output) { + @Override + public void flush() throws IOException { + channel.force(false); + super.flush(); + } + }; + } + } + + private static boolean canUseFileObjectOutputStream(Set options) { + return overwritesFile(options) && hasOnlyOverwriteOptions(options); + } + + private static boolean overwritesFile(Set options) { + return options.contains(StandardOpenOption.TRUNCATE_EXISTING) + || options.contains(StandardOpenOption.CREATE_NEW); + } + + private static boolean hasOnlyOverwriteOptions(Set options) { + return Set.of(StandardOpenOption.WRITE, StandardOpenOption.CREATE, + StandardOpenOption.CREATE_NEW, StandardOpenOption.TRUNCATE_EXISTING).containsAll(options); + } + + private NioPathForFileObject fromPath(Path path) { + if (!(path instanceof NioPathForFileObject nio)) { + throw new IllegalArgumentException("Not a NetBeans FileObject path"); + } + return nio; + } + +} 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..17207f9ebd91 --- /dev/null +++ b/platform/openide.filesystems/src/org/openide/filesystems/NioWatchService.java @@ -0,0 +1,284 @@ +/* + * 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.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; +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 final Set registeredKeys = new HashSet<>(); + private volatile boolean closed; + + WatchKey register(Path path, WatchEvent.Kind[] events) { + checkClosed(); + NioWatchKey key = new NioWatchKey(this, path, events); + synchronized (registeredKeys) { + if (!closed) { + if (key.isValid()) { + registeredKeys.add(key); + } + return key; + } + } + key.cancel(); + throw new ClosedWatchServiceException(); + } + + @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(Optional entry) { + if (entry != null && entry.isEmpty()) { + // Relay the close marker so every blocked consumer wakes up. + keys.offer(entry); + } + checkClosed(); + if (entry != null) { + NioWatchKey key = entry.orElseThrow(); + key.dequeued(); + return key; + } + return null; + } + + @Override + public void close() { + List registered; + synchronized (registeredKeys) { + if (closed) { + return; + } + closed = true; + registered = new ArrayList<>(registeredKeys); + registeredKeys.clear(); + } + keys.clear(); + keys.offer(Optional.empty()); + for (NioWatchKey key : registered) { + key.cancel(); + } + } + + 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 volatile 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(); + this.watchedObject = path instanceof NioPathForFileObject nio ? nio.getFileObject() : 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) { + if (event.getFile() == watchedObject) { + invalidate(true); + } else { + 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 (watchedObject != null) { + watchedObject.addFileChangeListener(listener); + } + } + + 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 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(Optional.of(this)); + } + } + + private synchronized void dequeued() { + queued = false; + } + + @Override + public void cancel() { + invalidate(false); + } + + private void invalidate(boolean signal) { + synchronized (this) { + if (!valid) { + return; + } + valid = false; + if (signal && !service.closed && !signalled) { + signalled = true; + enqueue(); + } + } + synchronized (service.registeredKeys) { + service.registeredKeys.remove(this); + } + 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/src/org/openide/filesystems/StreamPool.java b/platform/openide.filesystems/src/org/openide/filesystems/StreamPool.java index 79a34dd80f3f..5830a4c67d22 100644 --- a/platform/openide.filesystems/src/org/openide/filesystems/StreamPool.java +++ b/platform/openide.filesystems/src/org/openide/filesystems/StreamPool.java @@ -329,7 +329,7 @@ private static synchronized void removeStreamPools(StreamPool fsPool, StreamPool private static final class NotifyOutputStream extends FilterOutputStream { private static final OutputStream emptyOs = new ByteArrayOutputStream(); private Exception ex; - private boolean closed = false; + private volatile boolean closed = false; AbstractFolder fo; /** defines if should be fired fileChanged event after close of stream */ @@ -350,11 +350,22 @@ private void setOriginal(OutputStream os) { out = os; } + @Override + public void write(int b) throws IOException { + if (closed) { + throw new IOException("Stream is closed"); // NOI18N + } + out.write(b); + } + /** Faster implementation of writing than is implemented in * the filter output stream. */ @Override public void write(byte[] b, int off, int len) throws IOException { + if (closed) { + throw new IOException("Stream is closed"); // NOI18N + } out.write(b, off, len); } diff --git a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/FileObjectTestHid.java b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/FileObjectTestHid.java index 4be64f9b850e..725d32e4f6c5 100644 --- a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/FileObjectTestHid.java +++ b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/FileObjectTestHid.java @@ -2940,6 +2940,47 @@ public void testGetOutputStream() throws java.io.IOException { } + public void testOutputStreamTruncatesOnOpen() throws Exception { + checkSetUp(); + FileObject file = getTestFile1(root); + if (fs.isReadOnly() || file.isReadOnly()) { + return; + } + writeStr(file, "original"); + try (OutputStream output = file.getOutputStream()) { + assertEquals("Opening the stream truncates the file", 0L, file.getSize()); + output.write(new byte[] {1, 2, 3}); + } + assertEquals(3L, file.getSize()); + } + + public void testOutputStreamRejectsWriteAfterClose() throws Exception { + checkSetUp(); + FileObject file = getTestFile1(root); + if (fs.isReadOnly() || file.isReadOnly()) { + return; + } + assertClosedOutputStreamRejectsWrites(file.getOutputStream()); + try (FileLock lock = file.lock()) { + assertClosedOutputStreamRejectsWrites(file.getOutputStream(lock)); + } + } + + private static void assertClosedOutputStreamRejectsWrites(OutputStream output) throws IOException { + output.write(1); + output.close(); + try { + output.write(2); + fail("A closed output stream must reject single-byte writes"); + } catch (IOException expected) { + } + try { + output.write(new byte[] {3, 4}, 0, 2); + fail("A closed output stream must reject array writes"); + } catch (IOException expected) { + } + } + public void testGetOutputStream1() throws java.io.IOException { checkSetUp(); 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..9cd4a241a16d 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 @@ -20,9 +20,42 @@ package org.openide.filesystems; import java.io.ByteArrayOutputStream; +import java.io.FilterOutputStream; +import java.io.IOException; +import java.io.InputStream; import java.io.OutputStream; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Proxy; +import java.net.URI; import java.net.URL; import java.net.URLConnection; +import java.nio.ByteBuffer; +import java.nio.channels.ClosedByInterruptException; +import java.nio.channels.ClosedChannelException; +import java.nio.channels.FileChannel; +import java.nio.file.DirectoryStream; +import java.nio.file.Files; +import java.nio.file.NotDirectoryException; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; +import java.nio.charset.StandardCharsets; +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.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; /** * @@ -86,4 +119,695 @@ 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")); + } + + public void testPathOutputStreamUsesFileObjectStream() throws Exception { + FileObject file = testedFS.getRoot().createData("output-stream.txt"); + AbstractFileSystem fs = (AbstractFileSystem) testedFS; + AbstractFileSystem.Info original = fs.info; + AtomicInteger opens = new AtomicInteger(); + try { + fs.info = withInfoCallback(original, (method, args) -> { + if (method.equals("outputStream")) { + opens.incrementAndGet(); + } + }); + List direct = outputStreamOpenCounts(file.getOutputStream(), opens); + for (StandardOpenOption[] options : new StandardOpenOption[][] { + {}, + {StandardOpenOption.TRUNCATE_EXISTING}, + {StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING} + }) { + opens.set(0); + List path = outputStreamOpenCounts( + Files.newOutputStream(FileUtil.toPath(file), options), opens); + assertEquals("Path writes should use the FileObject stream", direct, path); + } + for (StandardOpenOption[] options : new StandardOpenOption[][] { + {}, + {StandardOpenOption.CREATE_NEW} + }) { + file.delete(); + opens.set(0); + List path = outputStreamOpenCounts( + Files.newOutputStream(FileUtil.toPath(testedFS.getRoot()).resolve("output-stream.txt"), options), + opens); + assertEquals("A new path should use the FileObject stream", direct, path); + file = testedFS.getRoot().getFileObject("output-stream.txt"); + } + } finally { + fs.info = original; + } + } + + private static List outputStreamOpenCounts(OutputStream output, AtomicInteger opens) + throws IOException { + List counts = new ArrayList<>(); + try (output) { + counts.add(opens.get()); + output.write('A'); + counts.add(opens.get()); + output.write('B'); + counts.add(opens.get()); + } + counts.add(opens.get()); + return counts; + } + + public void testDirectoryStreamRelativePathAndNonDirectory() throws Exception { + FileObject folder = testedFS.getRoot().createFolder("directory-stream"); + FileObject file = folder.createData("entry.txt"); + Path relative = FileUtil.toPath(folder).getFileSystem().getPath("directory-stream"); + assertFalse(relative.isAbsolute()); + try (DirectoryStream stream = Files.newDirectoryStream(relative)) { + Iterator entries = stream.iterator(); + assertTrue(entries.hasNext()); + assertEquals(relative.resolve("entry.txt"), entries.next()); + assertFalse(entries.hasNext()); + } + try (DirectoryStream stream = Files.newDirectoryStream(FileUtil.toPath(file))) { + fail("A file is not a directory: " + stream); + } catch (NotDirectoryException expected) { + } + } + + public void testDirectoryStreamIndependentIterators() throws Exception { + FileObject folder = testedFS.getRoot().createFolder("directory-stream"); + folder.createData("first.txt"); + folder.createData("second.txt"); + DirectoryStream stream = Files.newDirectoryStream(FileUtil.toPath(folder)); + try { + Iterator first = stream.iterator(); + Iterator second = stream.iterator(); + Iterator untouched = stream.iterator(); + Path firstEntry = first.next(); + assertEquals("Each iterator must start at the beginning", firstEntry, second.next()); + assertTrue(first.hasNext()); + stream.close(); + Path secondEntry = first.next(); + assertFalse(firstEntry.equals(secondEntry)); + assertFalse(first.hasNext()); + assertEquals(secondEntry, second.next()); + assertFalse(second.hasNext()); + assertEquals(firstEntry, untouched.next()); + assertEquals(secondEntry, untouched.next()); + assertFalse(untouched.hasNext()); + Iterator afterClose = stream.iterator(); + assertEquals(firstEntry, afterClose.next()); + assertEquals(secondEntry, afterClose.next()); + assertFalse(afterClose.hasNext()); + } finally { + stream.close(); + } + } + + public void testDirectoryStreamFilterCanCloseStream() throws Exception { + FileObject folder = testedFS.getRoot().createFolder("directory-stream"); + folder.createData("entry.txt"); + ExecutorService executor = Executors.newSingleThreadExecutor(); + AtomicReference> reference = new AtomicReference<>(); + try (DirectoryStream stream = Files.newDirectoryStream(FileUtil.toPath(folder), entry -> { + try { + executor.submit(() -> { + reference.get().close(); + return null; + }).get(5, TimeUnit.SECONDS); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + throw new IOException(ex); + } catch (ExecutionException | TimeoutException ex) { + throw new IOException(ex); + } + return true; + })) { + reference.set(stream); + Iterator entries = stream.iterator(); + assertTrue(entries.hasNext()); + assertEquals(FileUtil.toPath(folder).resolve("entry.txt"), entries.next()); + assertFalse(entries.hasNext()); + } finally { + executor.shutdownNow(); + } + } + + public void testDirectoryStreamConcurrentIteration() throws Exception { + FileObject folder = testedFS.getRoot().createFolder("directory-stream"); + folder.createData("first.txt"); + folder.createData("second.txt"); + CountDownLatch filtering = new CountDownLatch(2); + AtomicInteger calls = new AtomicInteger(); + ExecutorService executor = Executors.newFixedThreadPool(2); + try (DirectoryStream stream = Files.newDirectoryStream(FileUtil.toPath(folder), entry -> { + if (calls.incrementAndGet() <= 2) { + filtering.countDown(); + try { + if (!filtering.await(5, TimeUnit.SECONDS)) { + throw new IOException("Concurrent filter calls did not start"); + } + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + throw new IOException(ex); + } + } + return true; + })) { + Iterator entries = stream.iterator(); + Future first = executor.submit(entries::next); + Future second = executor.submit(entries::next); + Set result = new HashSet<>(); + result.add(first.get(5, TimeUnit.SECONDS)); + result.add(second.get(5, TimeUnit.SECONDS)); + assertEquals(Set.of(FileUtil.toPath(folder).resolve("first.txt"), + FileUtil.toPath(folder).resolve("second.txt")), result); + assertFalse(entries.hasNext()); + } finally { + executor.shutdownNow(); + } + } + + public void testChannelDoesNotHoldMonitorsInFileSystemLock() throws Exception { + MemoryFileSystem fs = (MemoryFileSystem) testedFS; + FileObject first = fs.getRoot().createData("first.txt"); + FileObject second = fs.getRoot().createData("second.txt"); + AbstractFileSystem.Info original = fs.info; + ExecutorService executor = Executors.newSingleThreadExecutor(); + AtomicInteger callbacks = new AtomicInteger(); + try (FileChannel other = FileChannel.open(FileUtil.toPath(second), StandardOpenOption.WRITE)) { + fs.info = withInfoCallback(original, (method, args) -> { + if ((method.equals("lock") || method.equals("unlock") + || method.equals("inputStream") || method.equals("outputStream")) + && "first.txt".equals(args[0])) { + callbacks.incrementAndGet(); + Future parallel = executor.submit(() -> { + try (java.nio.channels.FileLock held = other.tryLock()) { + assertNotNull(held); + other.position(); + } catch (Exception ex) { + throw new IllegalStateException(ex); + } + }); + parallel.get(5, TimeUnit.SECONDS); + } + }); + try (FileChannel channel = FileChannel.open(FileUtil.toPath(first), StandardOpenOption.WRITE)) { + try (java.nio.channels.FileLock held = channel.tryLock()) { + assertNotNull(held); + } + channel.write(ByteBuffer.wrap(new byte[] {1})); + channel.force(false); + } + assertTrue("I/O and unlock callbacks must run", callbacks.get() >= 2); + } finally { + fs.info = original; + executor.shutdownNow(); + } + } + + public void testChannelCloseFlushesBufferedWriteAndReleasesFileObjectLock() throws Exception { + MemoryFileSystem fs = (MemoryFileSystem) testedFS; + FileObject file = fs.getRoot().createData("writing.txt"); + AbstractFileSystem.Info original = fs.info; + AtomicInteger unlocks = new AtomicInteger(); + try (FileChannel channel = FileChannel.open(FileUtil.toPath(file), StandardOpenOption.WRITE)) { + fs.info = withInfoCallback(original, (method, args) -> { + if (method.equals("unlock") && "writing.txt".equals(args[0])) { + unlocks.incrementAndGet(); + } + }); + channel.write(ByteBuffer.wrap(new byte[] {1})); + assertEquals("Buffered content is not visible before close", 0, file.getSize()); + channel.close(); + assertEquals("Close writes buffered content", 1, file.getSize()); + assertEquals("Close releases the FileObject lock", 1, unlocks.get()); + assertFalse(file.isLocked()); + } finally { + fs.info = original; + } + } + + public void testInterruptedOperationClosesOutsideStateMonitor() throws Exception { + MemoryFileSystem fs = (MemoryFileSystem) testedFS; + FileObject file = fs.getRoot().createData("interrupt-writing.txt"); + FileObject otherFile = fs.getRoot().createData("interrupt-other.txt"); + AbstractFileSystem.Info original = fs.info; + CountDownLatch entered = new CountDownLatch(1); + CountDownLatch proceed = new CountDownLatch(1); + CountDownLatch waitingStarted = new CountDownLatch(1); + AtomicReference waitingThread = new AtomicReference<>(); + ExecutorService executor = Executors.newFixedThreadPool(3); + try (FileChannel channel = FileChannel.open(FileUtil.toPath(file), StandardOpenOption.WRITE); + FileChannel other = FileChannel.open(FileUtil.toPath(otherFile), StandardOpenOption.WRITE)) { + fs.info = withInfoCallback(original, (method, args) -> { + if (method.equals("outputStream") && "interrupt-writing.txt".equals(args[0])) { + entered.countDown(); + if (!proceed.await(5, TimeUnit.SECONDS)) { + throw new java.io.IOException("Timed out waiting for test"); + } + } + if (method.equals("unlock") && "interrupt-writing.txt".equals(args[0])) { + Future probe = executor.submit(() -> other.position()); + assertEquals(0, probe.get(5, TimeUnit.SECONDS).longValue()); + } + }); + channel.write(ByteBuffer.wrap(new byte[] {1})); + Future force = executor.submit(() -> { + channel.force(false); + return null; + }); + assertTrue("Force did not begin", entered.await(5, TimeUnit.SECONDS)); + Future waiting = executor.submit(() -> { + waitingThread.set(Thread.currentThread()); + waitingStarted.countDown(); + channel.position(1); + return null; + }); + assertTrue(waitingStarted.await(5, TimeUnit.SECONDS)); + assertWaiting(waitingThread.get()); + waitingThread.get().interrupt(); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(2); + while (channel.isOpen() && System.nanoTime() < deadline) { + Thread.sleep(10); + } + assertFalse("The interrupted operation must close the channel", channel.isOpen()); + proceed.countDown(); + try { + waiting.get(5, TimeUnit.SECONDS); + fail("An interrupted operation must fail"); + } catch (ExecutionException expected) { + assertTrue(expected.getCause() instanceof ClosedByInterruptException); + } + try { + force.get(5, TimeUnit.SECONDS); + fail("The force must observe the close"); + } catch (ExecutionException expected) { + assertTrue(expected.getCause() instanceof ClosedChannelException); + } + assertFalse(file.isLocked()); + } finally { + proceed.countDown(); + fs.info = original; + executor.shutdownNow(); + } + } + + public void testChannelClosePersistsBufferedTruncateAndReleasesFileObjectLock() throws Exception { + MemoryFileSystem fs = (MemoryFileSystem) testedFS; + FileObject file = fs.getRoot().createData("pending-update.txt"); + try (OutputStream out = file.getOutputStream()) { + out.write(new byte[] {1, 2}); + } + AbstractFileSystem.Info original = fs.info; + AtomicInteger unlocks = new AtomicInteger(); + try (FileChannel channel = FileChannel.open(FileUtil.toPath(file), StandardOpenOption.WRITE)) { + fs.info = withInfoCallback(original, (method, args) -> { + if (method.equals("unlock") && "pending-update.txt".equals(args[0])) { + unlocks.incrementAndGet(); + } + }); + channel.truncate(1); + assertEquals("Truncate is buffered until close", 2, file.getSize()); + channel.close(); + assertEquals(1, file.getSize()); + assertEquals("Close releases the FileObject lock", 1, unlocks.get()); + assertEquals("The lock must be released exactly once", 1, unlocks.get()); + assertFalse(file.isLocked()); + } finally { + fs.info = original; + } + } + + public void testChannelBufferGrowthAndTruncateGap() throws Exception { + FileObject file = testedFS.getRoot().createData("buffer-growth.txt"); + try (FileChannel channel = FileChannel.open(FileUtil.toPath(file), + StandardOpenOption.READ, StandardOpenOption.WRITE)) { + channel.write(ByteBuffer.wrap(new byte[] {1, 2, 3, 4})); + channel.truncate(1); + channel.write(ByteBuffer.wrap(new byte[] {9}), 6); + assertEquals(7, channel.size()); + ByteBuffer contents = ByteBuffer.allocate(7); + assertEquals(7, channel.read(contents, 0)); + assertTrue(Arrays.equals(new byte[] {1, 0, 0, 0, 0, 0, 9}, contents.array())); + channel.force(false); + assertTrue(Arrays.equals(contents.array(), file.asBytes())); + channel.write(ByteBuffer.wrap(new byte[] {8}), 7); + } + assertTrue(Arrays.equals(new byte[] {1, 0, 0, 0, 0, 0, 9, 8}, file.asBytes())); + } + + public void testChannelOpenReleasesFileObjectLockOnFailure() throws Exception { + MemoryFileSystem fs = (MemoryFileSystem) testedFS; + FileObject file = fs.getRoot().createData("failure.txt"); + try (OutputStream out = file.getOutputStream()) { + out.write(1); + } + AbstractFileSystem.Info original = fs.info; + AtomicBoolean fail = new AtomicBoolean(true); + try { + fs.info = withInfoCallback(original, (method, args) -> { + if (method.equals("lock") && fail.getAndSet(false)) { + throw new java.io.IOException("Test lock failure"); + } + }); + try { + FileChannel.open(FileUtil.toPath(file), StandardOpenOption.WRITE).close(); + fail("A filesystem lock failure must be propagated"); + } catch (java.io.IOException expected) { + assertEquals("Test lock failure", expected.getMessage()); + } + assertFalse(file.isLocked()); + FileChannel truncated = FileChannel.open(FileUtil.toPath(file), StandardOpenOption.WRITE, + StandardOpenOption.TRUNCATE_EXISTING); + fs.info = (AbstractFileSystem.Info) Proxy.newProxyInstance( + AbstractFileSystem.Info.class.getClassLoader(), + new Class[] {AbstractFileSystem.Info.class}, (proxy, method, args) -> { + try { + Object result = method.invoke(original, args); + if (method.getName().equals("outputStream")) { + return new FilterOutputStream((OutputStream) result) { + @Override + public void write(byte[] b, int off, int len) throws java.io.IOException { + throw new java.io.IOException("Test truncate failure"); + } + }; + } + return result; + } catch (InvocationTargetException ex) { + throw ex.getCause(); + } + }); + try { + truncated.force(false); + fail("A truncate failure must be propagated"); + } catch (java.io.IOException expected) { + assertEquals("Test truncate failure", expected.getMessage()); + } + assertTrue("A failed force keeps the channel lock until close", file.isLocked()); + fs.info = original; + truncated.close(); + assertFalse("Closing the channel releases its FileObject lock", file.isLocked()); + fs.info = withInfoCallback(original, (method, args) -> { + if (method.equals("size") && "failure.txt".equals(args[0])) { + throw new IllegalStateException("Test append initialization failure"); + } + }); + try { + FileChannel.open(FileUtil.toPath(file), StandardOpenOption.APPEND).close(); + fail("An append initialization failure must be propagated"); + } catch (IllegalStateException expected) { + assertEquals("Test append initialization failure", expected.getMessage()); + } + assertFalse("Failed append initialization must release its FileObject lock", file.isLocked()); + fs.info = original; + try (FileChannel channel = FileChannel.open(FileUtil.toPath(file), StandardOpenOption.WRITE)) { + assertTrue(channel.isOpen()); + } + } finally { + fs.info = original; + } + } + + public void testChannelForceFailureRetainsBufferedChanges() throws Exception { + MemoryFileSystem fs = (MemoryFileSystem) testedFS; + FileObject file = fs.getRoot().createData("write-failure.txt"); + AbstractFileSystem.Info original = fs.info; + try (FileChannel channel = FileChannel.open(FileUtil.toPath(file), StandardOpenOption.WRITE)) { + fs.info = (AbstractFileSystem.Info) Proxy.newProxyInstance( + AbstractFileSystem.Info.class.getClassLoader(), + new Class[] {AbstractFileSystem.Info.class}, (proxy, method, args) -> { + try { + Object result = method.invoke(original, args); + if (method.getName().equals("outputStream") && "write-failure.txt".equals(args[0])) { + return new FilterOutputStream((OutputStream) result) { + @Override + public void write(byte[] b, int off, int len) throws java.io.IOException { + throw new java.io.IOException("Test write failure"); + } + }; + } + return result; + } catch (InvocationTargetException ex) { + throw ex.getCause(); + } + }); + ByteBuffer source = ByteBuffer.allocateDirect(4); + source.put(new byte[] {'-', 'x', 'y', '-'}).flip(); + source.position(1); + source.limit(3); + source = source.asReadOnlyBuffer(); + channel.position(1); + assertEquals(2, channel.write(source)); + assertEquals("A buffered write consumes its source", 3, source.position()); + assertEquals("A buffered write advances the channel", 3, channel.position()); + try { + channel.force(false); + fail("A force failure must be propagated"); + } catch (java.io.IOException expected) { + assertEquals("Test write failure", expected.getMessage()); + } + fs.info = original; + channel.force(false); + assertTrue(Arrays.equals(new byte[] {0, 'x', 'y'}, file.asBytes())); + } finally { + fs.info = original; + } + } + + public void testGatheringWriteCommitsPositionAtEnd() throws Exception { + MemoryFileSystem fs = (MemoryFileSystem) testedFS; + FileObject file = fs.getRoot().createData("gathering-position.txt"); + AbstractFileSystem.Info original = fs.info; + AtomicInteger writes = new AtomicInteger(); + try (FileChannel channel = FileChannel.open(FileUtil.toPath(file), StandardOpenOption.WRITE)) { + fs.info = withInfoCallback(original, (method, args) -> { + if (method.equals("outputStream") && "gathering-position.txt".equals(args[0])) { + writes.incrementAndGet(); + assertEquals("Force preserves the committed position", 2, channel.position()); + } + }); + assertEquals(2, channel.write(new ByteBuffer[] { + ByteBuffer.wrap(new byte[] {'a'}), ByteBuffer.wrap(new byte[] {'b'}) + })); + assertEquals(0, writes.get()); + assertEquals(2, channel.position()); + channel.force(false); + assertEquals(1, writes.get()); + assertEquals("ab", new String(file.asBytes(), StandardCharsets.UTF_8)); + } finally { + fs.info = original; + } + } + + public void testGatheringWriteFailureCommitsCompletedBuffers() throws Exception { + FileObject file = testedFS.getRoot().createData("gathering-failure.txt"); + try (FileChannel channel = FileChannel.open(FileUtil.toPath(file), StandardOpenOption.WRITE)) { + ByteBuffer first = ByteBuffer.wrap(new byte[] {'a'}); + try { + channel.write(new ByteBuffer[] {first, null}); + fail("A null buffer must be rejected"); + } catch (NullPointerException expected) { + } + assertEquals(1, first.position()); + assertEquals("The completed write must advance the channel", 1, channel.position()); + channel.force(false); + assertEquals("a", new String(file.asBytes(), StandardCharsets.UTF_8)); + } + } + + public void testRelativeReadWaitsForPositionChangingWrite() throws Exception { + MemoryFileSystem fs = (MemoryFileSystem) testedFS; + FileObject file = fs.getRoot().createData("read-during-write.txt"); + try (OutputStream out = file.getOutputStream()) { + out.write("abc".getBytes(StandardCharsets.UTF_8)); + } + try (FileChannel channel = FileChannel.open(FileUtil.toPath(file), + StandardOpenOption.READ, StandardOpenOption.WRITE)) { + assertEquals(1, channel.write(ByteBuffer.wrap(new byte[] {'X'}))); + assertEquals(1, channel.position()); + ByteBuffer read = ByteBuffer.allocate(1); + assertEquals(1, channel.read(read)); + assertEquals("b", new String(read.array(), StandardCharsets.UTF_8)); + assertEquals(2, channel.position()); + channel.force(false); + assertEquals("Xbc", new String(file.asBytes(), StandardCharsets.UTF_8)); + } + } + + public void testConcurrentPositionedWritesDoNotLoseUpdates() throws Exception { + MemoryFileSystem fs = (MemoryFileSystem) testedFS; + FileObject file = fs.getRoot().createData("concurrent-write.txt"); + try (OutputStream out = file.getOutputStream()) { + out.write("abcd".getBytes(StandardCharsets.UTF_8)); + } + ExecutorService executor = Executors.newFixedThreadPool(2); + try (FileChannel channel = FileChannel.open(FileUtil.toPath(file), StandardOpenOption.WRITE)) { + Future write1 = executor.submit(() -> channel.write(ByteBuffer.wrap(new byte[] {'X'}), 0)); + Future write2 = executor.submit(() -> channel.write(ByteBuffer.wrap(new byte[] {'Y'}), 1)); + assertEquals(1, write1.get(5, TimeUnit.SECONDS).intValue()); + assertEquals(1, write2.get(5, TimeUnit.SECONDS).intValue()); + channel.force(false); + assertEquals("XYcd", new String(file.asBytes(), StandardCharsets.UTF_8)); + assertEquals("Positioned writes must not change the channel position", 0, channel.position()); + } finally { + executor.shutdownNow(); + } + } + + public void testReentrantWriteIsRejected() throws Exception { + MemoryFileSystem fs = (MemoryFileSystem) testedFS; + FileObject file = fs.getRoot().createData("reentrant-write.txt"); + AbstractFileSystem.Info original = fs.info; + AtomicBoolean checked = new AtomicBoolean(); + try (FileChannel channel = FileChannel.open(FileUtil.toPath(file), StandardOpenOption.WRITE)) { + fs.info = withInfoCallback(original, (method, args) -> { + if (method.equals("outputStream") && "reentrant-write.txt".equals(args[0])) { + try { + channel.write(ByteBuffer.wrap(new byte[] {'Y'}), 0); + fail("A reentrant write must not overwrite an in-progress update"); + } catch (java.io.IOException expected) { + assertEquals("Reentrant channel operation during a write", expected.getMessage()); + checked.set(true); + } + } + }); + assertEquals(1, channel.write(ByteBuffer.wrap(new byte[] {'X'}))); + channel.force(false); + assertTrue("The filesystem callback must run", checked.get()); + assertEquals("X", new String(file.asBytes(), StandardCharsets.UTF_8)); + } finally { + fs.info = original; + } + } + + public void testChannelReadsUseCachedContent() throws Exception { + MemoryFileSystem fs = (MemoryFileSystem) testedFS; + FileObject file = fs.getRoot().createData("read-retry.txt"); + try (OutputStream out = file.getOutputStream()) { + out.write("abcdef".getBytes(StandardCharsets.UTF_8)); + } + AbstractFileSystem.Info original = fs.info; + AtomicInteger inputStreams = new AtomicInteger(); + fs.info = withInfoCallback(original, (method, args) -> { + if (method.equals("inputStream") && "read-retry.txt".equals(args[0])) { + inputStreams.incrementAndGet(); + } + }); + try (FileChannel channel = FileChannel.open(FileUtil.toPath(file), StandardOpenOption.READ)) { + assertEquals("Opening the channel loads the file once", 1, inputStreams.get()); + ByteBuffer dst = ByteBuffer.allocate(2); + assertEquals(2, channel.read(dst)); + assertEquals("ab", new String(dst.array(), StandardCharsets.UTF_8)); + channel.position(3); + ByteBuffer positioned = ByteBuffer.allocate(2); + assertEquals(2, channel.read(positioned, 3)); + assertEquals("de", new String(positioned.array(), StandardCharsets.UTF_8)); + ByteBuffer[] parts = {ByteBuffer.allocate(1), ByteBuffer.allocate(1)}; + channel.position(4); + assertEquals(2, channel.read(parts, 0, parts.length)); + assertEquals("e", new String(parts[0].array(), StandardCharsets.UTF_8)); + assertEquals("f", new String(parts[1].array(), StandardCharsets.UTF_8)); + assertEquals("Reads reuse the content loaded on open", 1, inputStreams.get()); + } finally { + fs.info = original; + } + } + + public void testChannelReadsOnlyRequestDestinationCapacity() throws Exception { + MemoryFileSystem fs = (MemoryFileSystem) testedFS; + FileObject file = fs.getRoot().createData("bounded-read.txt"); + try (OutputStream out = file.getOutputStream()) { + out.write(new byte[10000]); + } + AbstractFileSystem.Info original = fs.info; + AtomicInteger inputStreams = new AtomicInteger(); + fs.info = withInfoCallback(original, (method, args) -> { + if (method.equals("inputStream") && "bounded-read.txt".equals(args[0])) { + inputStreams.incrementAndGet(); + } + }); + try (FileChannel channel = FileChannel.open(FileUtil.toPath(file), StandardOpenOption.READ)) { + assertEquals(1, inputStreams.get()); + ByteBuffer relative = ByteBuffer.allocate(4); + relative.position(2); + assertEquals(2, channel.read(relative)); + assertEquals(1, channel.read(ByteBuffer.allocate(1), 10)); + assertEquals(3, channel.read(new ByteBuffer[] {ByteBuffer.allocate(1), ByteBuffer.allocate(2)})); + assertEquals(8192, channel.read(ByteBuffer.allocate(10000))); + assertEquals("Reads do not reopen the file", 1, inputStreams.get()); + } finally { + fs.info = original; + } + } + + public void testConcurrentChannelReadsCommitDistinctRanges() throws Exception { + MemoryFileSystem fs = (MemoryFileSystem) testedFS; + FileObject file = fs.getRoot().createData("concurrent-read.txt"); + try (OutputStream out = file.getOutputStream()) { + out.write("abcdef".getBytes(StandardCharsets.UTF_8)); + } + ExecutorService executor = Executors.newFixedThreadPool(2); + try (FileChannel channel = FileChannel.open(FileUtil.toPath(file), StandardOpenOption.READ)) { + Future first = executor.submit(() -> { + ByteBuffer buffer = ByteBuffer.allocate(2); + assertEquals(2, channel.read(buffer)); + return new String(buffer.array(), StandardCharsets.UTF_8); + }); + Future second = executor.submit(() -> { + ByteBuffer buffer = ByteBuffer.allocate(2); + assertEquals(2, channel.read(buffer)); + return new String(buffer.array(), StandardCharsets.UTF_8); + }); + Set actual = new HashSet<>(); + actual.add(first.get(5, TimeUnit.SECONDS)); + actual.add(second.get(5, TimeUnit.SECONDS)); + assertEquals(Set.of("ab", "cd"), actual); + assertEquals(4, channel.position()); + } finally { + executor.shutdownNow(); + } + } + + private void assertWaiting(Thread thread) throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (thread.getState() != Thread.State.WAITING && System.nanoTime() < deadline) { + Thread.sleep(10); + } + assertEquals("The second operation must be waiting", Thread.State.WAITING, thread.getState()); + } + + @FunctionalInterface + private interface InfoCallback { + void invoke(String method, Object[] args) throws Exception; + } + + private static AbstractFileSystem.Info withInfoCallback( + AbstractFileSystem.Info original, InfoCallback callback) { + return (AbstractFileSystem.Info) Proxy.newProxyInstance( + AbstractFileSystem.Info.class.getClassLoader(), + new Class[] {AbstractFileSystem.Info.class}, (proxy, method, args) -> { + callback.invoke(method.getName(), args); + try { + return method.invoke(original, args); + } catch (InvocationTargetException ex) { + throw ex.getCause(); + } + }); + } } 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..0315802b3fd2 --- /dev/null +++ b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java @@ -0,0 +1,1688 @@ +/* + * 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.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URI; +import java.nio.ByteBuffer; +import java.nio.channels.Channels; +import java.nio.channels.FileChannel; +import java.nio.channels.ClosedChannelException; +import java.nio.channels.NonWritableChannelException; +import java.nio.channels.OverlappingFileLockException; +import java.nio.channels.SeekableByteChannel; +import java.nio.charset.StandardCharsets; +import java.nio.file.ClosedWatchServiceException; +import java.nio.file.DirectoryIteratorException; +import java.nio.file.DirectoryStream; +import java.nio.file.FileAlreadyExistsException; +import java.nio.file.Files; +import java.nio.file.NoSuchFileException; +import java.nio.file.OpenOption; +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.nio.file.attribute.FileTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Set; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.FutureTask; +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 testDirectoryStreamFilter() throws Exception { + Path folder = getPath().getParent(); + try (DirectoryStream stream = Files.newDirectoryStream(folder, + entry -> entry.getFileName().toString().equals("file.txt"))) { + Iterator entries = stream.iterator(); + assertTrue(entries.hasNext()); + assertTrue("Repeated hasNext must not consume the entry", entries.hasNext()); + assertEquals(getPath(), entries.next()); + assertFalse(entries.hasNext()); + try { + entries.next(); + fail("An exhausted iterator must throw"); + } catch (NoSuchElementException expected) { + } + try { + entries.remove(); + fail("A directory iterator must not support remove"); + } catch (UnsupportedOperationException expected) { + } + } + } + + public void testDirectoryStreamCloseAndReadAhead() throws Exception { + Path directory = getPath().getParent(); + boolean virtual = directory.getFileSystem() instanceof NioFsForFileSystem; + DirectoryStream stream = Files.newDirectoryStream(directory); + try { + Iterator entries = stream.iterator(); + assertTrue(entries.hasNext()); + stream.close(); + assertNotNull("A read-ahead entry must remain available after close", entries.next()); + int remaining = 0; + while (entries.hasNext()) { + entries.next(); + assertTrue("A closed stream must eventually be exhausted", ++remaining <= 2); + } + try { + entries.next(); + fail("An exhausted closed stream must throw"); + } catch (NoSuchElementException expected) { + } + if (!virtual) { + try { + stream.iterator(); + fail("A closed directory stream must not provide an iterator"); + } catch (IllegalStateException expected) { + } + } + } finally { + stream.close(); + } + + if (!virtual) { + DirectoryStream closedBeforeIterator = Files.newDirectoryStream(directory); + closedBeforeIterator.close(); + try { + closedBeforeIterator.iterator(); + fail("A closed directory stream must not provide its first iterator"); + } catch (IllegalStateException expected) { + } + } + } + + public void testDirectoryStreamFilterIOException() throws Exception { + IOException failure = new IOException("filter failed"); + try (DirectoryStream stream = Files.newDirectoryStream(getPath().getParent(), entry -> { + throw failure; + })) { + try { + stream.iterator().hasNext(); + fail("Filter failure must be reported during iteration"); + } catch (DirectoryIteratorException ex) { + assertSame(failure, ex.getCause()); + } + } + } + + public void testDirectoryStreamInvalidTargets() throws Exception { + for (Path invalid : Arrays.asList(getPath(), getPath().resolveSibling("missing-directory"))) { + try (DirectoryStream stream = Files.newDirectoryStream(invalid)) { + fail("Opening a non-directory must fail: " + invalid + ", got " + stream); + } catch (IOException expected) { + } + } + } + + 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 testRelativePathNormalizationAndResolution() throws Exception { + java.nio.file.FileSystem fs = getPath().getFileSystem(); + Path base = fs.getPath("alpha", "beta"); + Path relative = fs.getPath("gamma", "..", "delta"); + + assertNull(base.getRoot()); + assertEquals(fs.getPath("alpha"), base.getParent()); + assertNull(fs.getPath("alpha").getParent()); + assertEquals(fs.getPath("alpha", "beta", "gamma", "..", "delta"), base.resolve(relative)); + assertEquals(fs.getPath("alpha", "beta", "delta"), base.resolve(relative).normalize()); + assertEquals(fs.getPath("..", "..", "alpha"), fs.getPath("..", "alpha", "..", "..", "alpha").normalize()); + assertEquals(fs.getPath(""), fs.getPath("alpha", "..").normalize()); + assertEquals(fs.getPath("alpha", "other"), base.resolveSibling("other")); + assertEquals(fs.getPath("other"), fs.getPath("alpha").resolveSibling("other")); + Path simple = fs.getPath("gamma", "delta"); + assertEquals(simple, base.relativize(base.resolve(simple))); + } + + public void testEmptyPathNamesAndResolution() throws Exception { + java.nio.file.FileSystem fs = getPath().getFileSystem(); + Path empty = fs.getPath(""); + Path name = fs.getPath("alpha"); + assertNull(empty.getRoot()); + assertNull(empty.getParent()); + assertEquals(empty, empty.getFileName()); + assertEquals(1, empty.getNameCount()); + assertEquals(empty, empty.getName(0)); + assertEquals(empty, empty.subpath(0, 1)); + Iterator names = empty.iterator(); + assertTrue(names.hasNext()); + assertEquals(empty, names.next()); + assertFalse(names.hasNext()); + assertEquals(name, empty.resolve(name)); + assertEquals(name, name.resolve(empty)); + assertEquals(empty, name.resolveSibling(empty)); + assertEquals(name, empty.relativize(name)); + assertEquals(fs.getPath(".."), name.relativize(empty)); + } + + public void testRootPathNamesAndResolution() throws Exception { + Path rootPath = getPath().getRoot(); + Path name = rootPath.getFileSystem().getPath("alpha"); + assertNull(rootPath.getParent()); + assertNull(rootPath.getFileName()); + assertEquals(0, rootPath.getNameCount()); + assertFalse(rootPath.iterator().hasNext()); + try { + rootPath.getName(0); + fail("A root has no name elements"); + } catch (IllegalArgumentException expected) { + } + assertEquals(name, rootPath.resolveSibling(name)); + assertEquals(name, rootPath.relativize(rootPath.resolve(name))); + assertEquals(rootPath, rootPath.resolve("../..").normalize()); + } + + public void testPathRedundantSeparators() throws Exception { + java.nio.file.FileSystem fs = getPath().getFileSystem(); + String separator = fs.getSeparator(); + Path path = fs.getPath("alpha" + separator + separator + "beta" + separator); + assertEquals(fs.getPath("alpha", "beta"), path); + assertEquals(fs.getPath("alpha"), path.getParent()); + assertEquals(fs.getPath("beta"), path.getFileName()); + Path rootPath = getPath().getRoot(); + assertEquals(rootPath.resolve(fs.getPath("alpha", "beta")), rootPath.resolve(path)); + } + + public void testResolveRelativizeRoundTrips() throws Exception { + java.nio.file.FileSystem fs = getPath().getFileSystem(); + Path rootPath = getPath().getRoot(); + List paths = Arrays.asList(fs.getPath(""), fs.getPath("alpha"), + fs.getPath("alpha", "beta"), fs.getPath("other", "leaf")); + for (Path base : paths) { + for (Path target : paths) { + assertEquals(target, base.resolve(base.relativize(target)).normalize()); + Path absoluteBase = rootPath.resolve(base); + Path absoluteTarget = rootPath.resolve(target); + assertEquals(absoluteTarget, absoluteBase.resolve(absoluteBase.relativize(absoluteTarget)).normalize()); + } + } + } + + public void testAbsoluteAndRelativePathsAreDistinct() throws Exception { + java.nio.file.FileSystem fs = getPath().getFileSystem(); + Path relative = fs.getPath("alpha", "beta"); + Path absolute = getPath().getRoot().resolve(relative); + + assertFalse(relative.isAbsolute()); + assertTrue(absolute.isAbsolute()); + assertEquals(absolute, relative.resolve(absolute)); + assertEquals(absolute, relative.resolve(absolute.toString())); + assertEquals(getPath().getRoot(), getPath().getRoot().resolve("..").normalize()); + assertFalse(relative.startsWith(absolute)); + assertFalse(absolute.startsWith(relative)); + try { + absolute.relativize(relative); + fail("Cannot relativize an absolute path against a relative path"); + } catch (IllegalArgumentException expected) { + } + try { + relative.relativize(absolute); + fail("Cannot relativize a relative path against an absolute path"); + } catch (IllegalArgumentException expected) { + } + } + + 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) { + if (isFileSystemBasedPath(path)) { + 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 testVirtualPathUriForMissingAndRelativePaths() throws Exception { + Path root = getPath().getRoot(); + if (!(root instanceof NioPathForFileObject)) { + return; + } + Path missing = getPath().resolveSibling("missing space #%25.txt"); + URI before = missing.toUri(); + assertTrue(before.isAbsolute()); + assertTrue(before.toASCIIString().endsWith("/missing%20space%20%23%2525.txt")); + assertEquals(before, missing.toAbsolutePath().toUri()); + + Path relative = root.relativize(missing); + assertTrue(relative.toAbsolutePath().isAbsolute()); + assertEquals(missing, relative.toAbsolutePath()); + assertEquals(before, relative.toUri()); + assertEquals(root.toUri(), root.relativize(root).toUri()); + assertTrue(missing.resolve("child").toUri().toASCIIString().endsWith( + "/missing%20space%20%23%2525.txt/child")); + + if (!testedFS.isReadOnly()) { + Path created = getPath().resolveSibling("uri-created.txt"); + URI createdUri = created.toUri(); + Files.createFile(created); + assertEquals("The URI must identify the same location after creation", createdUri, created.toUri()); + } + } + + public void testPathForNonExistingFileObjects() throws Exception { + FileObject folder = getFileObject().getParent(); + FileObject missing = folder.getFileObject("missing-object.txt", false); + FileObject nested = folder.getFileObject("missing-parent/missing-child.txt", false); + assertNotNull(missing); + assertNotNull(nested); + assertFalse(missing.isValid()); + assertFalse(nested.isValid()); + + Path path = FileUtil.toPath(missing); + Path nestedPath = FileUtil.toPath(nested); + Path folderPath = path instanceof NioPathForFileObject + ? testedFS.toVirtualPath(folder) : FileUtil.toPath(folder); + assertEquals(folderPath.resolve("missing-object.txt"), path); + assertEquals(folderPath.resolve("missing-parent/missing-child.txt"), nestedPath); + assertFalse(Files.exists(path)); + assertFalse(Files.exists(nestedPath)); + assertEquals(missing.toURI(), path.toUri()); + assertTrue(nestedPath.toUri().toASCIIString().endsWith("/missing-parent/missing-child.txt")); + try { + path.toRealPath(); + fail("A path for a missing FileObject has no real path"); + } catch (IOException expected) { + } + + if (!testedFS.isReadOnly()) { + URI before = path.toUri(); + Files.writeString(path, "created"); + assertEquals("created", Files.readString(path)); + assertEquals(before, path.toUri()); + assertEquals(path, path.toRealPath()); + + FileObject missingFolder = folder.getFileObject("missing-folder", false); + Path folderToCreate = FileUtil.toPath(missingFolder); + Files.createDirectory(folderToCreate); + assertTrue(Files.isDirectory(folderToCreate)); + + URI nestedUri = nestedPath.toUri(); + Files.createDirectory(nestedPath.getParent()); + Files.writeString(nestedPath, "nested"); + assertEquals("nested", Files.readString(nestedPath)); + assertEquals(nestedUri, nestedPath.toUri()); + assertEquals(nestedPath, nestedPath.toRealPath()); + } + } + + 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); + if (isFileSystemBasedPath(path)) { + Files.setLastModifiedTime(path, FileTime.fromMillis( + System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1))); + file.refresh(); + } + 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 testFileObjectAndPathOutputStreams() throws Exception { + if (testedFS.isReadOnly()) { + return; + } + FileObject file = getFileObject(); + Path path = FileUtil.toPath(file); + byte[][] results = new byte[2][]; + for (int i = 0; i < results.length; i++) { + Files.writeString(path, "old content"); + try (OutputStream output = i == 0 ? file.getOutputStream() : Files.newOutputStream(path)) { + output.write('A'); + output.write(new byte[] {'x', 'B', 'C', 'x'}, 1, 2); + output.flush(); + output.write('D'); + } + results[i] = Files.readAllBytes(path); + } + assertTrue("FileObject and Path output streams produce the same contents", + Arrays.equals(results[0], results[1])); + assertEquals("ABCD", new String(results[0], StandardCharsets.UTF_8)); + } + + public void testOutputStreamAppendWriteAndTruncate() throws Exception { + if (testedFS.isReadOnly()) { + return; + } + Path path = getPath(); + Files.writeString(path, "abcdef"); + try (OutputStream output = Files.newOutputStream(path, StandardOpenOption.APPEND)) { + output.write('X'); + output.write('Y'); + output.flush(); + assertEquals("abcdefXY", Files.readString(path)); + } + assertEquals("abcdefXY", Files.readString(path)); + try (OutputStream output = Files.newOutputStream(path, StandardOpenOption.WRITE)) { + output.write("12".getBytes(StandardCharsets.UTF_8)); + } + assertEquals("12cdefXY", Files.readString(path)); + try (OutputStream output = Files.newOutputStream(path, StandardOpenOption.TRUNCATE_EXISTING)) { + assertEquals("Truncation happens when the stream opens", 0L, Files.size(path)); + output.write('Z'); + } + assertEquals("Z", Files.readString(path)); + try (OutputStream output = Files.newOutputStream(path)) { + output.flush(); + assertEquals("Default options truncate an existing file on open", 0L, Files.size(path)); + } + assertEquals(0L, Files.size(path)); + } + + public void testOutputStreamCreateOptions() throws Exception { + if (testedFS.isReadOnly()) { + return; + } + Path path = getPath().resolveSibling("stream-created.txt"); + for (OpenOption option : Arrays.asList(StandardOpenOption.WRITE, StandardOpenOption.APPEND, + StandardOpenOption.TRUNCATE_EXISTING)) { + try (OutputStream output = Files.newOutputStream(path, option)) { + fail("Opening a missing file without CREATE must fail: " + output); + } catch (NoSuchFileException expected) { + } + } + try (OutputStream output = Files.newOutputStream(path, StandardOpenOption.CREATE_NEW)) { + output.write('A'); + } + try (OutputStream output = Files.newOutputStream(path, StandardOpenOption.CREATE_NEW)) { + fail("CREATE_NEW must reject an existing file: " + output); + } catch (FileAlreadyExistsException expected) { + } + assertEquals("A", Files.readString(path)); + + Path appended = path.resolveSibling("stream-append-created.txt"); + try (OutputStream output = Files.newOutputStream(appended, + StandardOpenOption.CREATE, StandardOpenOption.APPEND)) { + output.write('B'); + } + assertEquals("B", Files.readString(appended)); + + Path defaultCreated = path.resolveSibling("stream-default-created.txt"); + try (OutputStream output = Files.newOutputStream(defaultCreated)) { + output.write('C'); + } + assertEquals("C", Files.readString(defaultCreated)); + } + + public void testOutputStreamInvalidOptions() throws Exception { + if (testedFS.isReadOnly()) { + return; + } + Path path = getPath(); + byte[] before = Files.readAllBytes(path); + try (OutputStream output = Files.newOutputStream(path, StandardOpenOption.READ)) { + fail("An output stream cannot be opened for reading: " + output); + } catch (IllegalArgumentException expected) { + } + try (OutputStream output = Files.newOutputStream(path, + StandardOpenOption.APPEND, StandardOpenOption.TRUNCATE_EXISTING)) { + fail("APPEND and TRUNCATE_EXISTING cannot be combined: " + output); + } catch (IllegalArgumentException expected) { + } + OpenOption unsupported = new OpenOption() {}; + try (OutputStream output = Files.newOutputStream(path, unsupported)) { + fail("An unknown open option must fail: " + output); + } catch (UnsupportedOperationException expected) { + } + assertTrue("Invalid options must not modify the file", Arrays.equals(before, Files.readAllBytes(path))); + } + + 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 testBasicAttributesForFileAndDirectory() throws Exception { + BasicFileAttributes file = Files.readAttributes(getPath(), BasicFileAttributes.class); + assertTrue(file.isRegularFile()); + assertFalse(file.isDirectory()); + assertFalse(file.isSymbolicLink()); + assertFalse(file.isOther()); + + BasicFileAttributes directory = Files.readAttributes(getPath().getParent(), BasicFileAttributes.class); + assertTrue(directory.isDirectory()); + assertFalse(directory.isRegularFile()); + assertFalse(directory.isSymbolicLink()); + assertFalse(directory.isOther()); + } + + public void testBasicAttributeSelection() throws Exception { + Path path = getPath(); + BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class); + Map selected = Files.readAttributes(path, "basic:size,lastModifiedTime,isDirectory"); + assertEquals(Set.of("size", "lastModifiedTime", "isDirectory"), selected.keySet()); + assertEquals(attributes.size(), selected.get("size")); + assertEquals(attributes.lastModifiedTime(), selected.get("lastModifiedTime")); + assertEquals(attributes.isDirectory(), selected.get("isDirectory")); + assertEquals(Map.of("size", attributes.size()), Files.readAttributes(path, "size")); + + Map all = Files.readAttributes(path, "basic:*"); + assertEquals(Set.of("size", "lastModifiedTime", "lastAccessTime", "creationTime", + "isRegularFile", "isDirectory", "isSymbolicLink", "isOther", "fileKey"), all.keySet()); + assertEquals(all, Files.readAttributes(path, "size,*")); + Map fileKey = Files.readAttributes(path, "fileKey"); + assertEquals(Set.of("fileKey"), fileKey.keySet()); + assertEquals(all.get("fileKey"), fileKey.get("fileKey")); + assertEquals(Map.of("isRegularFile", false, "isDirectory", true), + Files.readAttributes(path.getParent(), "isRegularFile,isDirectory")); + } + + public void testBasicAttributesOfMissingFile() throws Exception { + Path missing = getPath().resolveSibling("missing-attributes.txt"); + try { + Files.readAttributes(missing, BasicFileAttributes.class); + fail("Reading attributes of a missing file must fail"); + } catch (NoSuchFileException expected) { + } + try { + Files.readAttributes(missing, "basic:size"); + fail("Reading selected attributes of a missing file must fail"); + } catch (NoSuchFileException expected) { + } + } + + public void testInvalidBasicAttributeSelection() throws Exception { + for (String selection : Arrays.asList("", "basic:", "size,notAnAttribute")) { + try { + Files.readAttributes(getPath(), selection); + fail("Invalid selection must fail: " + selection); + } catch (IllegalArgumentException expected) { + } + } + try { + Files.readAttributes(getPath(), "unsupportedView:*"); + fail("An unsupported attribute view must fail"); + } catch (UnsupportedOperationException expected) { + } + } + + public void testBasicAttributesAfterFileChanges() throws Exception { + if (testedFS.isReadOnly()) { + return; + } + Path path = getPath(); + Files.writeString(path, "abc"); + BasicFileAttributes before = Files.readAttributes(path, BasicFileAttributes.class); + Files.writeString(path, "abcdefgh"); + BasicFileAttributes after = Files.readAttributes(path, BasicFileAttributes.class); + assertEquals(3L, before.size()); + assertEquals(8L, after.size()); + assertTrue(before.isRegularFile()); + assertTrue(after.isRegularFile()); + Files.delete(path); + assertTrue("The earlier attributes describe the file before deletion", before.isRegularFile()); + assertEquals(8L, after.size()); + } + + public void testPathFileChannelLock() throws Exception { + if (testedFS.isReadOnly()) { + return; + } + FileObject file = getFileObject(); + Path path = getPath(); + assertFalse(file.isLocked()); + + if (FileUtil.toFile(file) != null && isFileSystemBasedPath(path)) { + 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()); + } + + private static boolean isFileSystemBasedPath(Path path) { + return "file".equals(path.getFileSystem().provider().getScheme()); + } + + public void testPathFileChannelOverlappingLocks() throws Exception { + Path path = getPath(); + if (testedFS.isReadOnly() || FileUtil.toFile(getFileObject()) == null || !isFileSystemBasedPath(path)) { + return; + } + try (FileChannel first = FileChannel.open(path, StandardOpenOption.WRITE); + FileChannel second = FileChannel.open(path, StandardOpenOption.WRITE)) { + java.nio.channels.FileLock held = first.lock(0, 10, false); + try { + try { + second.tryLock(5, 10, false); + fail("Overlapping locks in the same JVM must be rejected"); + } catch (OverlappingFileLockException expected) { + } + try (java.nio.channels.FileLock disjoint = second.tryLock(10, 10, false)) { + assertNotNull(disjoint); + assertTrue(disjoint.isValid()); + } + } finally { + held.release(); + } + try (java.nio.channels.FileLock acquired = second.tryLock(0, 10, false)) { + assertNotNull(acquired); + assertTrue(acquired.isValid()); + } + } + } + + public void testPathFileChannelCloseReleasesLock() throws Exception { + if (testedFS.isReadOnly() || FileUtil.toFile(getFileObject()) == null) { + return; + } + Path path = getPath(); + java.nio.channels.FileLock held; + try (FileChannel channel = FileChannel.open(path, StandardOpenOption.WRITE)) { + held = channel.lock(); + assertTrue(held.isValid()); + } + assertFalse(held.isValid()); + try (FileChannel channel = FileChannel.open(path, StandardOpenOption.WRITE); + java.nio.channels.FileLock acquired = channel.tryLock()) { + assertNotNull(acquired); + assertTrue(acquired.isValid()); + } + } + + public void testPathFileChannelRead() throws Exception { + Path path = getPath(); + if (!testedFS.isReadOnly()) { + Files.writeString(path, "channel read"); + } + byte[] expected = Files.readAllBytes(path); + FileChannel channel = FileChannel.open(path, StandardOpenOption.READ); + try (channel) { + assertEquals(expected.length, channel.size()); + ByteBuffer data = ByteBuffer.allocate(expected.length + 1); + while (data.hasRemaining() && channel.read(data) != -1) { + } + assertEquals(expected.length, data.position()); + assertTrue(Arrays.equals(expected, Arrays.copyOf(data.array(), data.position()))); + assertEquals(expected.length, channel.position()); + assertEquals(-1, channel.read(ByteBuffer.allocate(1))); + assertEquals(0, channel.read(ByteBuffer.allocate(0))); + try { + channel.read(ByteBuffer.allocate(1).asReadOnlyBuffer()); + fail("Reading into a read-only buffer must fail"); + } catch (IllegalArgumentException ex) { + } + assertEquals(expected.length, channel.position()); + if (expected.length != 0) { + assertEquals(1, channel.read(ByteBuffer.allocate(1), 0)); + assertEquals(expected.length, channel.position()); + } + } + try { + channel.read(ByteBuffer.allocate(1)); + fail("Reading a closed channel must fail"); + } catch (ClosedChannelException ex) { + } + } + + public void testVirtualPathFileChannelLockBridgesFileObject() throws Exception { + if (testedFS.isReadOnly() || FileUtil.toFile(getFileObject()) != null) { + return; + } + FileObject file = getFileObject(); + Path path = FileUtil.toPath(file); + try (FileLock fileLock = file.lock()) { + try { + FileChannel.open(path, StandardOpenOption.WRITE).close(); + fail("Opening a writable channel must respect the FileObject lock"); + } catch (FileAlreadyLockedException expected) { + } + } + try (FileChannel channel = FileChannel.open(path, StandardOpenOption.WRITE)) { + assertTrue("The channel owns the FileObject lock", file.isLocked()); + try (FileChannel reader = FileChannel.open(path, StandardOpenOption.READ)) { + assertTrue(reader.isOpen()); + } + try { + FileChannel.open(path, StandardOpenOption.WRITE).close(); + fail("A second writable channel must not open"); + } catch (FileAlreadyLockedException expected) { + } + java.nio.channels.FileLock nioLock = channel.tryLock(); + try (nioLock) { + assertNotNull(nioLock); + assertTrue(file.isLocked()); + channel.write(ByteBuffer.wrap(new byte[] {1, 2, 3})); + channel.force(false); + assertTrue(Arrays.equals(new byte[] {1, 2, 3}, file.asBytes())); + try { + file.lock().releaseLock(); + fail("FileObject lock must conflict with the NIO lock"); + } catch (FileAlreadyLockedException expected) { + } + assertSame("Repeated acquisition returns the channel's lock", nioLock, channel.tryLock()); + assertSame("Range requests use the whole-file lock", nioLock, channel.tryLock(1, 2, false)); + assertSame("Shared requests use the exclusive lock", nioLock, channel.lock(2, 1, true)); + assertEquals(0, nioLock.position()); + assertEquals(Long.MAX_VALUE, nioLock.size()); + assertFalse(nioLock.isShared()); + } + assertTrue("Releasing the NIO lock has no effect", nioLock.isValid()); + assertTrue("Releasing an NIO lock must retain channel ownership", file.isLocked()); + try { + file.lock().releaseLock(); + fail("The channel must keep the FileObject lock until close"); + } catch (FileAlreadyLockedException expected) { + } + try (java.nio.channels.FileLock again = channel.lock()) { + assertSame(nioLock, again); + assertTrue(file.isLocked()); + assertTrue(again.isValid()); + } + } + assertFalse(file.isLocked()); + java.nio.channels.FileLock held; + try (FileChannel channel = FileChannel.open(path, StandardOpenOption.WRITE)) { + held = channel.lock(); + assertTrue(file.isLocked()); + } + assertFalse(held.isValid()); + assertFalse(file.isLocked()); + try (FileChannel channel = FileChannel.open(path, StandardOpenOption.READ)) { + try { + channel.tryLock(0, Long.MAX_VALUE, true); + fail("Read-only virtual channels cannot acquire even a shared lock"); + } catch (NonWritableChannelException expected) { + } + } + } + + public void testPathFileChannelWriteAndPosition() throws Exception { + if (testedFS.isReadOnly()) { + return; + } + Path path = getPath(); + Files.writeString(path, "abcdef"); + try (FileChannel channel = FileChannel.open(path, StandardOpenOption.READ, StandardOpenOption.WRITE)) { + assertEquals(2, channel.write(ByteBuffer.wrap(new byte[] {'X', 'Y'}), 2)); + assertEquals(0, channel.position()); + channel.force(false); + assertEquals("abXYef", Files.readString(path)); + channel.position(5); + assertEquals(1, channel.write(ByteBuffer.wrap(new byte[] {'Z'}))); + assertEquals(6, channel.position()); + channel.force(false); + channel.truncate(3); + assertEquals(3, channel.position()); + assertEquals(3, channel.size()); + channel.force(false); + assertEquals("abX", Files.readString(path)); + ByteArrayOutputStream transferred = new ByteArrayOutputStream(); + assertEquals(2, channel.transferTo(1, 2, Channels.newChannel(transferred))); + assertEquals("bX", transferred.toString("UTF-8")); + assertEquals(1, channel.transferFrom( + Channels.newChannel(new ByteArrayInputStream(new byte[] {'Z'})), 1, 1)); + channel.force(false); + assertEquals("aZX", Files.readString(path)); + assertEquals(3, channel.position()); + } + } + + public void testPathFileChannelCreateAndAppend() throws Exception { + if (testedFS.isReadOnly()) { + return; + } + Path path = getPath().resolveSibling("channel-created.txt"); + try (FileChannel channel = FileChannel.open(path, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)) { + channel.write(ByteBuffer.wrap(new byte[] {'a', 'b'})); + } + try (FileChannel channel = FileChannel.open(path, StandardOpenOption.APPEND)) { + assertEquals(2, channel.position()); + channel.position(0); + channel.write(ByteBuffer.wrap(new byte[] {'c'})); + } + assertEquals("abc", Files.readString(path)); + try (FileChannel channel = FileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING)) { + assertEquals(0, channel.size()); + } + assertEquals("", Files.readString(path)); + } + + public void testPathByteChannelOptionsAndLocking() throws Exception { + if (testedFS.isReadOnly()) { + return; + } + Path path = getPath(); + FileObject file = FileUtil.toFileObject(path); + boolean virtual = FileUtil.toFile(file) == null; + Files.writeString(path, "abcdef"); + try (SeekableByteChannel channel = Files.newByteChannel(path, + StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING)) { + assertEquals(0, channel.size()); + if (virtual) { + assertTrue(file.isLocked()); + } + channel.write(ByteBuffer.wrap(new byte[] {'x'})); + } + if (virtual) { + assertFalse(file.isLocked()); + } + assertEquals("x", Files.readString(path)); + + try (SeekableByteChannel channel = Files.newByteChannel(path, StandardOpenOption.APPEND)) { + assertEquals(1, channel.position()); + channel.position(0); + channel.write(ByteBuffer.wrap(new byte[] {'y'})); + } + assertEquals("xy", Files.readString(path)); + + try { + Files.newByteChannel(path, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE); + fail("CREATE_NEW must reject an existing file"); + } catch (FileAlreadyExistsException expected) { + } + } + + 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 testWatchServiceCloseWakesWaiters() throws Exception { + if (testedFS.isReadOnly()) { + return; + } + Path folder = getPath().getParent(); + WatchService watcher = folder.getFileSystem().newWatchService(); + FutureTask take = new FutureTask<>(watcher::take); + FutureTask poll = new FutureTask<>(() -> watcher.poll(1, TimeUnit.MINUTES)); + Thread takeThread = new Thread(take, "watch-take"); + Thread pollThread = new Thread(poll, "watch-poll"); + try { + WatchKey key = folder.register(watcher, StandardWatchEventKinds.ENTRY_CREATE); + takeThread.start(); + pollThread.start(); + awaitWatchWaiter(takeThread); + awaitWatchWaiter(pollThread); + watcher.close(); + assertFalse(key.isValid()); + assertFalse(key.reset()); + assertWatchClosed(take); + assertWatchClosed(poll); + try { + watcher.poll(); + fail("Polling a closed watcher must fail"); + } catch (ClosedWatchServiceException expected) { + } + try { + folder.register(watcher, StandardWatchEventKinds.ENTRY_CREATE); + fail("Registering with a closed watcher must fail"); + } catch (ClosedWatchServiceException expected) { + } + watcher.close(); + } finally { + watcher.close(); + take.cancel(true); + poll.cancel(true); + takeThread.join(5000); + pollThread.join(5000); + } + } + + public void testWatchKeyCancellation() throws Exception { + if (testedFS.isReadOnly()) { + return; + } + FileObject folder = getFileObject().getParent(); + Path folderPath = FileUtil.toPath(folder); + try (WatchService watcher = folderPath.getFileSystem().newWatchService()) { + WatchKey key = folderPath.register(watcher, StandardWatchEventKinds.ENTRY_CREATE); + folder.createData("before-cancel.txt"); + assertSame(key, watcher.poll(5, TimeUnit.SECONDS)); + assertTrue(key.reset()); + key.cancel(); + assertFalse(key.isValid()); + assertFalse(key.reset()); + assertSame("A queued key remains available after cancellation", key, watcher.poll(5, TimeUnit.SECONDS)); + List> pending = key.pollEvents(); + assertEquals(1, pending.size()); + assertEquals(folderPath.getFileSystem().getPath("before-cancel.txt"), pending.get(0).context()); + folder.createData("after-cancel.txt"); + assertNull(watcher.poll(200, TimeUnit.MILLISECONDS)); + assertTrue(key.pollEvents().isEmpty()); + key.cancel(); + } + } + + public void testWatchKeyWhenDirectoryIsDeleted() throws Exception { + if (testedFS.isReadOnly()) { + return; + } + FileObject directory = getFileObject().getParent().createFolder("watched-deleted"); + Path path = FileUtil.toPath(directory); + try (WatchService watcher = path.getFileSystem().newWatchService()) { + WatchKey key = path.register(watcher, StandardWatchEventKinds.ENTRY_CREATE); + directory.delete(); + assertSame("Deleting the watched directory must signal its key", + key, watcher.poll(5, TimeUnit.SECONDS)); + assertFalse(key.isValid()); + assertFalse(key.reset()); + } + } + + private void awaitWatchWaiter(Thread thread) throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (thread.getState() != Thread.State.WAITING + && thread.getState() != Thread.State.TIMED_WAITING) { + assertTrue("Watch thread did not block: " + thread.getState(), System.nanoTime() < deadline); + Thread.sleep(10); + } + } + + private void assertWatchClosed(FutureTask operation) throws Exception { + try { + operation.get(5, TimeUnit.SECONDS); + fail("A blocked watch operation must fail when closed"); + } catch (ExecutionException ex) { + assertTrue("Expected ClosedWatchServiceException: " + ex.getCause(), + ex.getCause() instanceof ClosedWatchServiceException); + } + } + + 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);