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-nullPath 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.
-->
-
+
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 extends FileObject> 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:
* @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 extends OpenOption> 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 extends OpenOption> 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 extends OpenOption> options,
+ FileAttribute>... attrs) throws IOException {
+ return NioFileObjectChannel.open(fromPath(path), options, attrs);
+ }
+
+ @Override
+ public SeekableByteChannel newByteChannel(
+ Path path, Set extends OpenOption> options, FileAttribute>... attrs) throws IOException {
+ return NioFileObjectChannel.open(fromPath(path), options, attrs);
+ }
+
+ @Override
+ public DirectoryStream newDirectoryStream(Path dir, DirectoryStream.Filter super Path> 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 super Path> filter;
+
+ FileObjectDirectoryStream(Path directory, FileObject[] children, Filter super Path> 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