sdedic commented on code in PR #9820:
URL: https://github.com/apache/netbeans/pull/9820#discussion_r4670924187


##########
platform/openide.filesystems/src/org/openide/filesystems/NioFsForFileSystem.java:
##########
@@ -0,0 +1,135 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, ANY KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.openide.filesystems;
+
+import java.io.IOException;
+import java.nio.file.FileStore;
+import java.nio.file.FileSystem;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.WatchService;
+import java.nio.file.attribute.UserPrincipalLookupService;
+import java.nio.file.spi.FileSystemProvider;
+import java.util.Collections;
+import java.util.Set;
+
+final class NioFsForFileSystem extends FileSystem {
+    private final org.openide.filesystems.FileSystem fileSystem;
+    private final NioPathProvider provider;
+
+    NioFsForFileSystem(org.openide.filesystems.FileSystem fileSystem) {
+        this.fileSystem = fileSystem;
+        this.provider = new NioPathProvider(this);
+    }
+
+    org.openide.filesystems.FileSystem getFileSystem() {
+        return fileSystem;
+    }
+
+    @Override
+    public FileSystemProvider provider() {
+        return provider;
+    }
+
+    @Override
+    public void close() {
+    }
+
+    @Override
+    public boolean isOpen() {
+        return true;
+    }
+
+    @Override
+    public boolean isReadOnly() {
+        return fileSystem.isReadOnly();
+    }
+
+    @Override
+    public String getSeparator() {
+        return "/";
+    }
+
+    @Override
+    public Iterable<Path> getRootDirectories() {
+        return 
Collections.singletonList(NioPathForFileObject.create(fileSystem.getRoot(), 
this));
+    }
+
+    @Override
+    public Iterable<FileStore> getFileStores() {
+        return Collections.emptyList();
+    }
+
+    @Override
+    public Set<String> supportedFileAttributeViews() {
+        return Collections.singleton("basic");
+    }
+
+    @Override
+    public Path getPath(String first, String... more) {
+        StringBuilder value = new StringBuilder(first);
+        for (String part : more) {
+            if (!value.isEmpty() && value.charAt(value.length() - 1) != '/') {
+                value.append('/');
+            }
+            value.append(part);
+        }
+        String normalized = normalizedPath(value.toString());
+        FileObject fo = fileSystem.findResource(normalized);
+        String name = normalizeName(value.toString());
+        if (!value.toString().startsWith("/")) {
+            return NioPathForFileObject.relative(fo, this, name);
+        }
+        return NioPathForFileObject.create(fo, this, name);
+    }
+
+    private String normalizedPath(String value) {
+        if (value.isEmpty()) {
+            return "";
+        }
+        String result = value.replace('\\', '/');
+        while (result.startsWith("/")) {
+            result = result.substring(1);
+        }
+        return result;
+    }
+
+    private String normalizeName(String value) {

Review Comment:
   Nitpick: `normalizeName` implementation seems the same as `normalizePath`; 
is this intentional assuming they may diverge in the future ? Also the guard 
condition in normalizedPath is just an optimization; either should be in both 
or in none IMHO



##########
platform/openide.filesystems/src/org/openide/filesystems/NioPathForFileObject.java:
##########
@@ -0,0 +1,373 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.openide.filesystems;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.URI;
+import java.nio.file.LinkOption;
+import java.nio.file.Path;
+import java.nio.file.WatchEvent;
+import java.nio.file.WatchKey;
+import java.nio.file.WatchService;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Objects;
+
+final class NioPathForFileObject implements Path {
+    private final FileObject fileObject;
+    private final NioFsForFileSystem fileSystem;
+    private final String name;
+    private final boolean absolute;
+
+    private NioPathForFileObject(FileObject fileObject, NioFsForFileSystem 
fileSystem, String name) {
+        this(fileObject, fileSystem, name, true);
+    }
+
+    private NioPathForFileObject(FileObject fileObject, NioFsForFileSystem 
fileSystem, String name, boolean absolute) {
+        this.fileObject = fileObject;
+        this.fileSystem = fileSystem;
+        this.name = normalize(name);
+        this.absolute = absolute;
+    }
+
+    static NioPathForFileObject create(FileObject fileObject, 
NioFsForFileSystem fileSystem) {
+        return new NioPathForFileObject(fileObject, fileSystem, 
fullName(fileObject));
+    }
+
+    static NioPathForFileObject create(FileObject fileObject, 
NioFsForFileSystem fileSystem, String name) {
+        return new NioPathForFileObject(fileObject, fileSystem, name);
+    }
+
+    static NioPathForFileObject relative(FileObject fileObject, 
NioFsForFileSystem fileSystem, String name) {
+        return new NioPathForFileObject(fileObject, fileSystem, name, false);
+    }
+
+    FileObject getFileObject() {
+        if (!name.isEmpty()) {
+            FileObject resolved = 
fileSystem.getFileSystem().findResource(name);
+            if (resolved != null) {
+                return resolved;
+            }
+        }
+        return fileObject;
+    }
+
+    @Override
+    public java.nio.file.FileSystem getFileSystem() {
+        return fileSystem;
+    }
+
+    @Override
+    public boolean isAbsolute() {
+        return absolute;
+    }
+
+    @Override
+    public Path getRoot() {
+        return create(fileSystem.getFileSystem().getRoot(), fileSystem);
+    }
+
+    @Override
+    public Path getFileName() {
+        if (name.isEmpty()) {
+            return null;
+        }
+        int separator = name.lastIndexOf('/');
+        String fileName = separator == -1 ? name : name.substring(separator + 
1);
+        return fileName.isEmpty() ? null : relative(fileObject, fileSystem, 
fileName);
+    }
+
+    @Override
+    public Path getParent() {
+        if (name.isEmpty()) {
+            return null;
+        }
+        int separator = name.lastIndexOf('/');
+        if (separator == -1) {
+            return getRoot();
+        }
+        String parentName = name.substring(0, separator);
+        FileObject parent = 
fileSystem.getFileSystem().findResource(parentName);
+        if (parent == null && fileObject != null) {
+            parent = fileObject.getParent();
+        }
+        return create(parent, fileSystem, parentName);
+    }
+
+    @Override
+    public int getNameCount() {
+        if (name.isEmpty()) {
+            return 1;
+        }
+        int count = 0;
+        for (String part : name.split("/")) {
+            if (!part.isEmpty()) {
+                count++;
+            }
+        }
+        return count;
+    }
+
+    @Override
+    public Path getName(int index) {
+        if (index < 0 || index >= getNameCount()) {
+            throw new IllegalArgumentException("Illegal name index: " + index);
+        }
+        List<String> names = names();
+        return relative(null, fileSystem, names.get(index));
+    }
+
+    @Override
+    public Path subpath(int beginIndex, int endIndex) {
+        if (beginIndex < 0 || endIndex > getNameCount() || beginIndex >= 
endIndex) {
+            throw new IllegalArgumentException();
+        }
+        List<String> names = names();
+        return relative(null, fileSystem, String.join("/", 
names.subList(beginIndex, endIndex)));
+    }
+
+    @Override
+    public boolean startsWith(Path other) {
+        if (!(other instanceof NioPathForFileObject nio) || nio.fileSystem != 
fileSystem) {
+            return false;
+        }
+        if (nio.name.isEmpty()) {
+            return absolute;
+        }
+        return name.equals(nio.name) || name.startsWith(nio.name + "/");
+    }
+
+    @Override
+    public boolean startsWith(String other) {
+        return startsWith(fileSystem.getPath(other));
+    }
+
+    @Override
+    public boolean endsWith(Path other) {
+        if (!(other instanceof NioPathForFileObject nio) || nio.fileSystem != 
fileSystem) {
+            return false;
+        }
+        if (nio.absolute || nio.name.isEmpty()) {
+            return absolute == nio.absolute && name.equals(nio.name);
+        }
+        return name.equals(nio.name) || name.endsWith("/" + nio.name);
+    }
+
+    @Override
+    public boolean endsWith(String other) {
+        return endsWith(fileSystem.getPath(other));
+    }
+
+    @Override
+    public Path normalize() {
+        List<String> normalized = new ArrayList<>();
+        for (String part : names()) {
+            if (part.isEmpty() || part.equals(".")) {
+                continue;
+            }
+            if (part.equals("..")) {
+                if (!normalized.isEmpty()) {
+                    normalized.remove(normalized.size() - 1);

Review Comment:
   we have J21; can use `.removeLast()`.



##########
platform/openide.filesystems/src/org/openide/filesystems/FileSystem.java:
##########
@@ -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);

Review Comment:
   Nitpick, perf: maybe `create` need not to be synchronized



##########
platform/openide.filesystems/src/org/openide/filesystems/NioPathForFileObject.java:
##########
@@ -0,0 +1,373 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.openide.filesystems;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.URI;
+import java.nio.file.LinkOption;
+import java.nio.file.Path;
+import java.nio.file.WatchEvent;
+import java.nio.file.WatchKey;
+import java.nio.file.WatchService;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Objects;
+
+final class NioPathForFileObject implements Path {
+    private final FileObject fileObject;
+    private final NioFsForFileSystem fileSystem;
+    private final String name;
+    private final boolean absolute;
+
+    private NioPathForFileObject(FileObject fileObject, NioFsForFileSystem 
fileSystem, String name) {
+        this(fileObject, fileSystem, name, true);
+    }
+
+    private NioPathForFileObject(FileObject fileObject, NioFsForFileSystem 
fileSystem, String name, boolean absolute) {
+        this.fileObject = fileObject;
+        this.fileSystem = fileSystem;
+        this.name = normalize(name);
+        this.absolute = absolute;
+    }
+
+    static NioPathForFileObject create(FileObject fileObject, 
NioFsForFileSystem fileSystem) {
+        return new NioPathForFileObject(fileObject, fileSystem, 
fullName(fileObject));
+    }
+
+    static NioPathForFileObject create(FileObject fileObject, 
NioFsForFileSystem fileSystem, String name) {
+        return new NioPathForFileObject(fileObject, fileSystem, name);
+    }
+
+    static NioPathForFileObject relative(FileObject fileObject, 
NioFsForFileSystem fileSystem, String name) {
+        return new NioPathForFileObject(fileObject, fileSystem, name, false);
+    }
+
+    FileObject getFileObject() {
+        if (!name.isEmpty()) {
+            FileObject resolved = 
fileSystem.getFileSystem().findResource(name);
+            if (resolved != null) {
+                return resolved;
+            }
+        }
+        return fileObject;
+    }
+
+    @Override
+    public java.nio.file.FileSystem getFileSystem() {
+        return fileSystem;
+    }
+
+    @Override
+    public boolean isAbsolute() {
+        return absolute;
+    }
+
+    @Override
+    public Path getRoot() {
+        return create(fileSystem.getFileSystem().getRoot(), fileSystem);
+    }
+
+    @Override
+    public Path getFileName() {
+        if (name.isEmpty()) {
+            return null;
+        }
+        int separator = name.lastIndexOf('/');
+        String fileName = separator == -1 ? name : name.substring(separator + 
1);
+        return fileName.isEmpty() ? null : relative(fileObject, fileSystem, 
fileName);
+    }
+
+    @Override
+    public Path getParent() {
+        if (name.isEmpty()) {
+            return null;
+        }
+        int separator = name.lastIndexOf('/');
+        if (separator == -1) {
+            return getRoot();
+        }
+        String parentName = name.substring(0, separator);
+        FileObject parent = 
fileSystem.getFileSystem().findResource(parentName);
+        if (parent == null && fileObject != null) {
+            parent = fileObject.getParent();
+        }
+        return create(parent, fileSystem, parentName);
+    }
+
+    @Override
+    public int getNameCount() {
+        if (name.isEmpty()) {
+            return 1;
+        }
+        int count = 0;
+        for (String part : name.split("/")) {
+            if (!part.isEmpty()) {
+                count++;
+            }
+        }
+        return count;
+    }
+
+    @Override
+    public Path getName(int index) {
+        if (index < 0 || index >= getNameCount()) {
+            throw new IllegalArgumentException("Illegal name index: " + index);
+        }
+        List<String> names = names();
+        return relative(null, fileSystem, names.get(index));
+    }
+
+    @Override
+    public Path subpath(int beginIndex, int endIndex) {
+        if (beginIndex < 0 || endIndex > getNameCount() || beginIndex >= 
endIndex) {
+            throw new IllegalArgumentException();
+        }
+        List<String> names = names();
+        return relative(null, fileSystem, String.join("/", 
names.subList(beginIndex, endIndex)));
+    }
+
+    @Override
+    public boolean startsWith(Path other) {
+        if (!(other instanceof NioPathForFileObject nio) || nio.fileSystem != 
fileSystem) {
+            return false;
+        }
+        if (nio.name.isEmpty()) {
+            return absolute;
+        }
+        return name.equals(nio.name) || name.startsWith(nio.name + "/");
+    }
+
+    @Override
+    public boolean startsWith(String other) {
+        return startsWith(fileSystem.getPath(other));
+    }
+
+    @Override
+    public boolean endsWith(Path other) {
+        if (!(other instanceof NioPathForFileObject nio) || nio.fileSystem != 
fileSystem) {
+            return false;
+        }
+        if (nio.absolute || nio.name.isEmpty()) {
+            return absolute == nio.absolute && name.equals(nio.name);
+        }
+        return name.equals(nio.name) || name.endsWith("/" + nio.name);
+    }
+
+    @Override
+    public boolean endsWith(String other) {
+        return endsWith(fileSystem.getPath(other));
+    }
+
+    @Override
+    public Path normalize() {
+        List<String> normalized = new ArrayList<>();
+        for (String part : names()) {
+            if (part.isEmpty() || part.equals(".")) {

Review Comment:
   Note that `names()` never returns empty segments.



##########
platform/openide.filesystems/src/org/openide/filesystems/NioFileObjectChannel.java:
##########
@@ -0,0 +1,651 @@
+/*
+ * 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 {
+    /*
+     * 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 = options.contains(StandardOpenOption.READ);
+        boolean write = options.contains(StandardOpenOption.WRITE);
+        boolean append = options.contains(StandardOpenOption.APPEND);
+        if (append && read || append && 
options.contains(StandardOpenOption.TRUNCATE_EXISTING)) {
+            throw new IllegalArgumentException("Invalid append options");
+        }
+        write |= append;
+        if (!read && !write) {
+            read = true;
+        }
+        for (OpenOption option : options) {
+            Objects.requireNonNull(option, "option");
+            if (
+                option != StandardOpenOption.READ &&
+                option != StandardOpenOption.WRITE &&
+                option != StandardOpenOption.APPEND &&
+                option != StandardOpenOption.CREATE &&
+                option != StandardOpenOption.CREATE_NEW &&
+                option != StandardOpenOption.TRUNCATE_EXISTING
+            ) {
+                throw new UnsupportedOperationException("Unsupported open 
option: " + option);
+            }
+        }
+        if (attrs.length != 0) {
+            throw new UnsupportedOperationException("Initial attributes are 
not supported");
+        }
+        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()) {

Review Comment:
   Note: the specification for `StandardOpenOptions.CREATE` says:
   
   > The check for the existence of the file and the creation of the file if it 
does not exist is atomic with respect to other file system operations.
   
   Here the existence check is `file == null || !file.isValid()` - but eventual 
`createData` happens non-atomically. So another thread may eventually create 
the file in between.



##########
platform/openide.filesystems/src/org/openide/filesystems/NioFileObjectChannel.java:
##########
@@ -0,0 +1,651 @@
+/*
+ * 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 {
+    /*
+     * 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 = options.contains(StandardOpenOption.READ);
+        boolean write = options.contains(StandardOpenOption.WRITE);
+        boolean append = options.contains(StandardOpenOption.APPEND);
+        if (append && read || append && 
options.contains(StandardOpenOption.TRUNCATE_EXISTING)) {
+            throw new IllegalArgumentException("Invalid append options");
+        }
+        write |= append;
+        if (!read && !write) {
+            read = true;
+        }
+        for (OpenOption option : options) {
+            Objects.requireNonNull(option, "option");
+            if (
+                option != StandardOpenOption.READ &&
+                option != StandardOpenOption.WRITE &&
+                option != StandardOpenOption.APPEND &&
+                option != StandardOpenOption.CREATE &&
+                option != StandardOpenOption.CREATE_NEW &&
+                option != StandardOpenOption.TRUNCATE_EXISTING
+            ) {
+                throw new UnsupportedOperationException("Unsupported open 
option: " + option);
+            }
+        }
+        if (attrs.length != 0) {
+            throw new UnsupportedOperationException("Initial attributes are 
not supported");
+        }
+        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(), 8192), 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(), 8192 - maximum);

Review Comment:
   Another occurrence of the same hard upper limit. If you really want to 
enforce size-limited transfers, please replace with a documented constant at 
all places.



##########
platform/openide.filesystems/src/org/openide/filesystems/NioPathForFileObject.java:
##########
@@ -0,0 +1,373 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.openide.filesystems;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.URI;
+import java.nio.file.LinkOption;
+import java.nio.file.Path;
+import java.nio.file.WatchEvent;
+import java.nio.file.WatchKey;
+import java.nio.file.WatchService;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Objects;
+
+final class NioPathForFileObject implements Path {
+    private final FileObject fileObject;
+    private final NioFsForFileSystem fileSystem;
+    private final String name;
+    private final boolean absolute;
+
+    private NioPathForFileObject(FileObject fileObject, NioFsForFileSystem 
fileSystem, String name) {
+        this(fileObject, fileSystem, name, true);
+    }
+
+    private NioPathForFileObject(FileObject fileObject, NioFsForFileSystem 
fileSystem, String name, boolean absolute) {
+        this.fileObject = fileObject;
+        this.fileSystem = fileSystem;
+        this.name = normalize(name);
+        this.absolute = absolute;
+    }
+
+    static NioPathForFileObject create(FileObject fileObject, 
NioFsForFileSystem fileSystem) {
+        return new NioPathForFileObject(fileObject, fileSystem, 
fullName(fileObject));
+    }
+
+    static NioPathForFileObject create(FileObject fileObject, 
NioFsForFileSystem fileSystem, String name) {
+        return new NioPathForFileObject(fileObject, fileSystem, name);
+    }
+
+    static NioPathForFileObject relative(FileObject fileObject, 
NioFsForFileSystem fileSystem, String name) {
+        return new NioPathForFileObject(fileObject, fileSystem, name, false);
+    }
+
+    FileObject getFileObject() {
+        if (!name.isEmpty()) {
+            FileObject resolved = 
fileSystem.getFileSystem().findResource(name);
+            if (resolved != null) {
+                return resolved;
+            }
+        }
+        return fileObject;
+    }
+
+    @Override
+    public java.nio.file.FileSystem getFileSystem() {
+        return fileSystem;
+    }
+
+    @Override
+    public boolean isAbsolute() {
+        return absolute;
+    }
+
+    @Override
+    public Path getRoot() {
+        return create(fileSystem.getFileSystem().getRoot(), fileSystem);
+    }
+
+    @Override
+    public Path getFileName() {
+        if (name.isEmpty()) {
+            return null;
+        }
+        int separator = name.lastIndexOf('/');
+        String fileName = separator == -1 ? name : name.substring(separator + 
1);
+        return fileName.isEmpty() ? null : relative(fileObject, fileSystem, 
fileName);
+    }
+
+    @Override
+    public Path getParent() {
+        if (name.isEmpty()) {
+            return null;
+        }
+        int separator = name.lastIndexOf('/');
+        if (separator == -1) {
+            return getRoot();
+        }
+        String parentName = name.substring(0, separator);
+        FileObject parent = 
fileSystem.getFileSystem().findResource(parentName);
+        if (parent == null && fileObject != null) {
+            parent = fileObject.getParent();
+        }
+        return create(parent, fileSystem, parentName);
+    }
+
+    @Override
+    public int getNameCount() {
+        if (name.isEmpty()) {
+            return 1;
+        }
+        int count = 0;
+        for (String part : name.split("/")) {
+            if (!part.isEmpty()) {
+                count++;
+            }
+        }
+        return count;
+    }
+
+    @Override
+    public Path getName(int index) {
+        if (index < 0 || index >= getNameCount()) {
+            throw new IllegalArgumentException("Illegal name index: " + index);
+        }
+        List<String> names = names();
+        return relative(null, fileSystem, names.get(index));
+    }
+
+    @Override
+    public Path subpath(int beginIndex, int endIndex) {
+        if (beginIndex < 0 || endIndex > getNameCount() || beginIndex >= 
endIndex) {
+            throw new IllegalArgumentException();
+        }
+        List<String> names = names();
+        return relative(null, fileSystem, String.join("/", 
names.subList(beginIndex, endIndex)));
+    }
+
+    @Override
+    public boolean startsWith(Path other) {
+        if (!(other instanceof NioPathForFileObject nio) || nio.fileSystem != 
fileSystem) {
+            return false;
+        }
+        if (nio.name.isEmpty()) {
+            return absolute;
+        }
+        return name.equals(nio.name) || name.startsWith(nio.name + "/");
+    }
+
+    @Override
+    public boolean startsWith(String other) {
+        return startsWith(fileSystem.getPath(other));
+    }
+
+    @Override
+    public boolean endsWith(Path other) {
+        if (!(other instanceof NioPathForFileObject nio) || nio.fileSystem != 
fileSystem) {
+            return false;
+        }
+        if (nio.absolute || nio.name.isEmpty()) {
+            return absolute == nio.absolute && name.equals(nio.name);
+        }
+        return name.equals(nio.name) || name.endsWith("/" + nio.name);
+    }
+
+    @Override
+    public boolean endsWith(String other) {
+        return endsWith(fileSystem.getPath(other));
+    }
+
+    @Override
+    public Path normalize() {
+        List<String> normalized = new ArrayList<>();
+        for (String part : names()) {
+            if (part.isEmpty() || part.equals(".")) {
+                continue;
+            }
+            if (part.equals("..")) {
+                if (!normalized.isEmpty()) {
+                    normalized.remove(normalized.size() - 1);
+                }
+            } else {
+                normalized.add(part);
+            }
+        }
+        String normalizedName = String.join("/", normalized);
+        FileObject fo = 
fileSystem.getFileSystem().findResource(normalizedName);
+        return create(fo, fileSystem, normalizedName);
+    }
+
+    @Override
+    public Path resolve(Path other) {
+        if (other.isAbsolute()) {
+            return other;
+        }
+        if (!(other instanceof NioPathForFileObject nio)) {
+            return resolve(other.toString());
+        }
+        return resolve(nio.name);
+    }
+
+    @Override
+    public Path resolve(String other) {
+        if (other.isEmpty()) {
+            return this;
+        }
+        String result = name.isEmpty() ? normalize(other) : normalize(name + 
"/" + other);
+        FileObject fo = fileSystem.getFileSystem().findResource(result);
+        return create(fo, fileSystem, result);
+    }
+
+    @Override
+    public Path resolveSibling(Path other) {
+        if (other.isAbsolute()) {
+            return other;
+        }
+        Path parent = getParent();
+        return parent == null ? other : parent.resolve(other);
+    }
+
+    @Override
+    public Path resolveSibling(String other) {
+        return resolveSibling(fileSystem.getPath(other));
+    }
+
+    @Override
+    public Path relativize(Path other) {
+        if (!(other instanceof NioPathForFileObject nio) || nio.fileSystem != 
fileSystem) {
+            throw new IllegalArgumentException("Cannot relativize different 
file systems");
+        }
+        List<String> base = names();
+        List<String> target = nio.names();
+        int common = 0;
+        while (common < base.size() && common < target.size() && 
base.get(common).equals(target.get(common))) {
+            common++;
+        }
+        List<String> result = new ArrayList<>();
+        for (int i = common; i < base.size(); i++) {
+            result.add("..");
+        }
+        result.addAll(target.subList(common, target.size()));
+        String relative = String.join("/", result);
+        return relative(null, fileSystem, relative.isEmpty() ? "" : relative);
+    }
+
+    @Override
+    public URI toUri() {
+        return fileObject.toURI();
+    }
+
+    @Override
+    public Path toAbsolutePath() {
+        return this;
+    }
+
+    @Override
+    public Path toRealPath(LinkOption... options) throws IOException {
+        if (fileObject == null) {
+            throw new IOException("No FileObject for " + name);
+        }
+        return normalize();
+    }
+
+    @Override
+    public File toFile() {
+        if (fileObject != null) {
+            File disk = FileUtil.toFile(fileObject);
+            if (disk != null) {
+                return disk;
+            }
+        }
+        throw new UnsupportedOperationException("Virtual FileObject has no 
java.io.File");
+    }
+
+    @Override
+    public WatchKey register(WatchService watcher, WatchEvent.Kind<?>[] 
events, WatchEvent.Modifier... modifiers) throws IOException {
+        if (!(watcher instanceof NioWatchService nioWatcher)) {
+            throw new IllegalArgumentException("Unsupported WatchService");
+        }
+        return nioWatcher.register(this, events);
+    }
+
+    @Override
+    public WatchKey register(WatchService watcher, WatchEvent.Kind<?>... 
events) throws IOException {
+        return register(watcher, events, new WatchEvent.Modifier[0]);
+    }
+
+    @Override
+    public Iterator<Path> iterator() {
+        List<Path> paths = new ArrayList<>();
+        for (String part : names()) {
+            paths.add(relative(null, fileSystem, part));
+        }
+        return paths.iterator();
+    }
+
+    @Override
+    public int compareTo(Path other) {
+        return toString().compareTo(other.toString());
+    }
+
+    @Override
+    public String toString() {
+        return absolute ? (name.isEmpty() ? "/" : "/" + name) : name;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj) {
+            return true;
+        }
+        if (!(obj instanceof NioPathForFileObject other)) {
+            return false;
+        }
+        return fileSystem == other.fileSystem && absolute == other.absolute && 
name.equals(other.name);
+    }
+
+    @Override
+    public int hashCode() {
+        return Objects.hash(fileSystem, name, absolute);
+    }
+
+    private List<String> names() {
+        List<String> names = new ArrayList<>();
+        if (!name.isEmpty()) {
+            for (String part : name.split("/")) {
+                if (!part.isEmpty()) {

Review Comment:
   note that this may return the same value for `name == ""` and `name  == 
"/"`. Is it OK ?



##########
platform/openide.filesystems/src/org/openide/filesystems/MemoryFileSystem.java:
##########
@@ -362,7 +363,7 @@ public MemoryFileSystem.Entry remove(String key) {
     static final class Entry {
         /** String, Object */
         public Map<String, Object> attrs = Collections.synchronizedMap(new 
HashMap<String, Object>());
-        public byte[] data;
+        public volatile byte[] data;

Review Comment:
   This caught my attention. 
   
   There are calls to `getOrCreateEntry(...).data = `; but that means, that for 
a very short period of time, the (potentially) new entry for regular file (i.e. 
`createData`) is available for lookup (registered in synchronized block), but 
not yet marked as non-folder (.data != null) 
   
   Maybe there's a slight chance that `filesystem.folder(path)` might 
eventually return true in between `getOrCreateEntry()` and `.data = new 
byte[0]`). 
   
   If the reasoning holds, pls. file an issue on that - it's (strictly 
speaking) out of scope of this change, and must have been there for a long time.



##########
platform/openide.filesystems/src/org/openide/filesystems/NioFileObjectChannel.java:
##########
@@ -0,0 +1,651 @@
+/*
+ * 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 {
+    /*
+     * 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 = options.contains(StandardOpenOption.READ);
+        boolean write = options.contains(StandardOpenOption.WRITE);
+        boolean append = options.contains(StandardOpenOption.APPEND);
+        if (append && read || append && 
options.contains(StandardOpenOption.TRUNCATE_EXISTING)) {
+            throw new IllegalArgumentException("Invalid append options");
+        }
+        write |= append;
+        if (!read && !write) {
+            read = true;
+        }
+        for (OpenOption option : options) {
+            Objects.requireNonNull(option, "option");
+            if (

Review Comment:
   Nitpick: Maybe `!EnumSet.contains()` with a constant enumset containing 
supported options would be nicer ? Readability: I'd expect this guard to be the 
1st, before checking conflicting option semantics.



##########
platform/openide.filesystems/src/org/openide/filesystems/NioPathForFileObject.java:
##########
@@ -0,0 +1,373 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.openide.filesystems;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.URI;
+import java.nio.file.LinkOption;
+import java.nio.file.Path;
+import java.nio.file.WatchEvent;
+import java.nio.file.WatchKey;
+import java.nio.file.WatchService;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Objects;
+
+final class NioPathForFileObject implements Path {
+    private final FileObject fileObject;
+    private final NioFsForFileSystem fileSystem;
+    private final String name;
+    private final boolean absolute;
+
+    private NioPathForFileObject(FileObject fileObject, NioFsForFileSystem 
fileSystem, String name) {
+        this(fileObject, fileSystem, name, true);
+    }
+
+    private NioPathForFileObject(FileObject fileObject, NioFsForFileSystem 
fileSystem, String name, boolean absolute) {
+        this.fileObject = fileObject;
+        this.fileSystem = fileSystem;
+        this.name = normalize(name);
+        this.absolute = absolute;
+    }
+
+    static NioPathForFileObject create(FileObject fileObject, 
NioFsForFileSystem fileSystem) {
+        return new NioPathForFileObject(fileObject, fileSystem, 
fullName(fileObject));
+    }
+
+    static NioPathForFileObject create(FileObject fileObject, 
NioFsForFileSystem fileSystem, String name) {
+        return new NioPathForFileObject(fileObject, fileSystem, name);
+    }
+
+    static NioPathForFileObject relative(FileObject fileObject, 
NioFsForFileSystem fileSystem, String name) {
+        return new NioPathForFileObject(fileObject, fileSystem, name, false);
+    }
+
+    FileObject getFileObject() {
+        if (!name.isEmpty()) {
+            FileObject resolved = 
fileSystem.getFileSystem().findResource(name);
+            if (resolved != null) {
+                return resolved;
+            }
+        }
+        return fileObject;
+    }
+
+    @Override
+    public java.nio.file.FileSystem getFileSystem() {
+        return fileSystem;
+    }
+
+    @Override
+    public boolean isAbsolute() {
+        return absolute;
+    }
+
+    @Override
+    public Path getRoot() {
+        return create(fileSystem.getFileSystem().getRoot(), fileSystem);
+    }
+
+    @Override
+    public Path getFileName() {
+        if (name.isEmpty()) {
+            return null;
+        }
+        int separator = name.lastIndexOf('/');
+        String fileName = separator == -1 ? name : name.substring(separator + 
1);
+        return fileName.isEmpty() ? null : relative(fileObject, fileSystem, 
fileName);
+    }
+
+    @Override
+    public Path getParent() {
+        if (name.isEmpty()) {
+            return null;
+        }
+        int separator = name.lastIndexOf('/');
+        if (separator == -1) {
+            return getRoot();
+        }
+        String parentName = name.substring(0, separator);
+        FileObject parent = 
fileSystem.getFileSystem().findResource(parentName);
+        if (parent == null && fileObject != null) {
+            parent = fileObject.getParent();
+        }
+        return create(parent, fileSystem, parentName);
+    }
+
+    @Override
+    public int getNameCount() {
+        if (name.isEmpty()) {
+            return 1;
+        }
+        int count = 0;
+        for (String part : name.split("/")) {
+            if (!part.isEmpty()) {
+                count++;
+            }
+        }
+        return count;
+    }
+
+    @Override
+    public Path getName(int index) {
+        if (index < 0 || index >= getNameCount()) {
+            throw new IllegalArgumentException("Illegal name index: " + index);
+        }
+        List<String> names = names();
+        return relative(null, fileSystem, names.get(index));
+    }
+
+    @Override
+    public Path subpath(int beginIndex, int endIndex) {
+        if (beginIndex < 0 || endIndex > getNameCount() || beginIndex >= 
endIndex) {
+            throw new IllegalArgumentException();
+        }
+        List<String> names = names();
+        return relative(null, fileSystem, String.join("/", 
names.subList(beginIndex, endIndex)));
+    }
+
+    @Override
+    public boolean startsWith(Path other) {
+        if (!(other instanceof NioPathForFileObject nio) || nio.fileSystem != 
fileSystem) {
+            return false;
+        }
+        if (nio.name.isEmpty()) {
+            return absolute;
+        }
+        return name.equals(nio.name) || name.startsWith(nio.name + "/");
+    }
+
+    @Override
+    public boolean startsWith(String other) {
+        return startsWith(fileSystem.getPath(other));
+    }
+
+    @Override
+    public boolean endsWith(Path other) {
+        if (!(other instanceof NioPathForFileObject nio) || nio.fileSystem != 
fileSystem) {
+            return false;
+        }
+        if (nio.absolute || nio.name.isEmpty()) {
+            return absolute == nio.absolute && name.equals(nio.name);
+        }
+        return name.equals(nio.name) || name.endsWith("/" + nio.name);
+    }
+
+    @Override
+    public boolean endsWith(String other) {
+        return endsWith(fileSystem.getPath(other));
+    }
+
+    @Override
+    public Path normalize() {
+        List<String> normalized = new ArrayList<>();
+        for (String part : names()) {
+            if (part.isEmpty() || part.equals(".")) {
+                continue;
+            }
+            if (part.equals("..")) {
+                if (!normalized.isEmpty()) {
+                    normalized.remove(normalized.size() - 1);
+                }
+            } else {
+                normalized.add(part);
+            }
+        }
+        String normalizedName = String.join("/", normalized);
+        FileObject fo = 
fileSystem.getFileSystem().findResource(normalizedName);
+        return create(fo, fileSystem, normalizedName);
+    }
+
+    @Override
+    public Path resolve(Path other) {
+        if (other.isAbsolute()) {
+            return other;
+        }
+        if (!(other instanceof NioPathForFileObject nio)) {
+            return resolve(other.toString());
+        }
+        return resolve(nio.name);
+    }
+
+    @Override
+    public Path resolve(String other) {
+        if (other.isEmpty()) {
+            return this;
+        }
+        String result = name.isEmpty() ? normalize(other) : normalize(name + 
"/" + other);
+        FileObject fo = fileSystem.getFileSystem().findResource(result);
+        return create(fo, fileSystem, result);
+    }
+
+    @Override
+    public Path resolveSibling(Path other) {
+        if (other.isAbsolute()) {
+            return other;
+        }
+        Path parent = getParent();
+        return parent == null ? other : parent.resolve(other);
+    }
+
+    @Override
+    public Path resolveSibling(String other) {
+        return resolveSibling(fileSystem.getPath(other));
+    }
+
+    @Override
+    public Path relativize(Path other) {
+        if (!(other instanceof NioPathForFileObject nio) || nio.fileSystem != 
fileSystem) {
+            throw new IllegalArgumentException("Cannot relativize different 
file systems");
+        }
+        List<String> base = names();
+        List<String> target = nio.names();
+        int common = 0;
+        while (common < base.size() && common < target.size() && 
base.get(common).equals(target.get(common))) {
+            common++;
+        }
+        List<String> result = new ArrayList<>();
+        for (int i = common; i < base.size(); i++) {
+            result.add("..");
+        }
+        result.addAll(target.subList(common, target.size()));
+        String relative = String.join("/", result);
+        return relative(null, fileSystem, relative.isEmpty() ? "" : relative);
+    }
+
+    @Override
+    public URI toUri() {
+        return fileObject.toURI();
+    }
+
+    @Override
+    public Path toAbsolutePath() {
+        return this;
+    }
+
+    @Override
+    public Path toRealPath(LinkOption... options) throws IOException {
+        if (fileObject == null) {
+            throw new IOException("No FileObject for " + name);
+        }
+        return normalize();
+    }
+
+    @Override
+    public File toFile() {
+        if (fileObject != null) {
+            File disk = FileUtil.toFile(fileObject);
+            if (disk != null) {
+                return disk;
+            }
+        }
+        throw new UnsupportedOperationException("Virtual FileObject has no 
java.io.File");
+    }
+
+    @Override
+    public WatchKey register(WatchService watcher, WatchEvent.Kind<?>[] 
events, WatchEvent.Modifier... modifiers) throws IOException {
+        if (!(watcher instanceof NioWatchService nioWatcher)) {
+            throw new IllegalArgumentException("Unsupported WatchService");
+        }
+        return nioWatcher.register(this, events);
+    }
+
+    @Override
+    public WatchKey register(WatchService watcher, WatchEvent.Kind<?>... 
events) throws IOException {
+        return register(watcher, events, new WatchEvent.Modifier[0]);
+    }
+
+    @Override
+    public Iterator<Path> iterator() {
+        List<Path> paths = new ArrayList<>();
+        for (String part : names()) {
+            paths.add(relative(null, fileSystem, part));
+        }
+        return paths.iterator();
+    }
+
+    @Override
+    public int compareTo(Path other) {
+        return toString().compareTo(other.toString());
+    }
+
+    @Override
+    public String toString() {
+        return absolute ? (name.isEmpty() ? "/" : "/" + name) : name;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj) {
+            return true;
+        }
+        if (!(obj instanceof NioPathForFileObject other)) {
+            return false;
+        }
+        return fileSystem == other.fileSystem && absolute == other.absolute && 
name.equals(other.name);
+    }
+
+    @Override
+    public int hashCode() {
+        return Objects.hash(fileSystem, name, absolute);
+    }
+
+    private List<String> names() {
+        List<String> names = new ArrayList<>();
+        if (!name.isEmpty()) {
+            for (String part : name.split("/")) {
+                if (!part.isEmpty()) {
+                    names.add(part);
+                }
+            }
+        }
+        return names;
+    }
+
+    private static String normalize(String name) {
+        if (name == null) {

Review Comment:
   IMHO `normalize` is never called with `null` name in this patch.



##########
platform/openide.filesystems/src/org/openide/filesystems/NioPathForFileObject.java:
##########
@@ -0,0 +1,373 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.openide.filesystems;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.URI;
+import java.nio.file.LinkOption;
+import java.nio.file.Path;
+import java.nio.file.WatchEvent;
+import java.nio.file.WatchKey;
+import java.nio.file.WatchService;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Objects;
+
+final class NioPathForFileObject implements Path {
+    private final FileObject fileObject;
+    private final NioFsForFileSystem fileSystem;
+    private final String name;
+    private final boolean absolute;
+
+    private NioPathForFileObject(FileObject fileObject, NioFsForFileSystem 
fileSystem, String name) {
+        this(fileObject, fileSystem, name, true);
+    }
+
+    private NioPathForFileObject(FileObject fileObject, NioFsForFileSystem 
fileSystem, String name, boolean absolute) {
+        this.fileObject = fileObject;
+        this.fileSystem = fileSystem;
+        this.name = normalize(name);

Review Comment:
   I think that all paths to this constructor already perform normalization 
earlier; maybe this is redundant.



##########
platform/openide.filesystems/src/org/openide/filesystems/NioPathForFileObject.java:
##########
@@ -0,0 +1,373 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.openide.filesystems;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.URI;
+import java.nio.file.LinkOption;
+import java.nio.file.Path;
+import java.nio.file.WatchEvent;
+import java.nio.file.WatchKey;
+import java.nio.file.WatchService;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Objects;
+
+final class NioPathForFileObject implements Path {
+    private final FileObject fileObject;
+    private final NioFsForFileSystem fileSystem;
+    private final String name;
+    private final boolean absolute;
+
+    private NioPathForFileObject(FileObject fileObject, NioFsForFileSystem 
fileSystem, String name) {
+        this(fileObject, fileSystem, name, true);
+    }
+
+    private NioPathForFileObject(FileObject fileObject, NioFsForFileSystem 
fileSystem, String name, boolean absolute) {
+        this.fileObject = fileObject;
+        this.fileSystem = fileSystem;
+        this.name = normalize(name);
+        this.absolute = absolute;
+    }
+
+    static NioPathForFileObject create(FileObject fileObject, 
NioFsForFileSystem fileSystem) {
+        return new NioPathForFileObject(fileObject, fileSystem, 
fullName(fileObject));
+    }
+
+    static NioPathForFileObject create(FileObject fileObject, 
NioFsForFileSystem fileSystem, String name) {
+        return new NioPathForFileObject(fileObject, fileSystem, name);
+    }
+
+    static NioPathForFileObject relative(FileObject fileObject, 
NioFsForFileSystem fileSystem, String name) {
+        return new NioPathForFileObject(fileObject, fileSystem, name, false);
+    }
+
+    FileObject getFileObject() {
+        if (!name.isEmpty()) {
+            FileObject resolved = 
fileSystem.getFileSystem().findResource(name);
+            if (resolved != null) {
+                return resolved;
+            }
+        }
+        return fileObject;
+    }
+
+    @Override
+    public java.nio.file.FileSystem getFileSystem() {
+        return fileSystem;
+    }
+
+    @Override
+    public boolean isAbsolute() {
+        return absolute;
+    }
+
+    @Override
+    public Path getRoot() {
+        return create(fileSystem.getFileSystem().getRoot(), fileSystem);
+    }
+
+    @Override
+    public Path getFileName() {
+        if (name.isEmpty()) {
+            return null;
+        }
+        int separator = name.lastIndexOf('/');
+        String fileName = separator == -1 ? name : name.substring(separator + 
1);
+        return fileName.isEmpty() ? null : relative(fileObject, fileSystem, 
fileName);
+    }
+
+    @Override
+    public Path getParent() {
+        if (name.isEmpty()) {
+            return null;
+        }
+        int separator = name.lastIndexOf('/');
+        if (separator == -1) {
+            return getRoot();
+        }
+        String parentName = name.substring(0, separator);
+        FileObject parent = 
fileSystem.getFileSystem().findResource(parentName);
+        if (parent == null && fileObject != null) {
+            parent = fileObject.getParent();
+        }
+        return create(parent, fileSystem, parentName);
+    }
+
+    @Override
+    public int getNameCount() {
+        if (name.isEmpty()) {
+            return 1;
+        }
+        int count = 0;
+        for (String part : name.split("/")) {
+            if (!part.isEmpty()) {
+                count++;
+            }
+        }
+        return count;
+    }
+
+    @Override
+    public Path getName(int index) {
+        if (index < 0 || index >= getNameCount()) {
+            throw new IllegalArgumentException("Illegal name index: " + index);
+        }
+        List<String> names = names();
+        return relative(null, fileSystem, names.get(index));
+    }
+
+    @Override
+    public Path subpath(int beginIndex, int endIndex) {
+        if (beginIndex < 0 || endIndex > getNameCount() || beginIndex >= 
endIndex) {
+            throw new IllegalArgumentException();
+        }
+        List<String> names = names();
+        return relative(null, fileSystem, String.join("/", 
names.subList(beginIndex, endIndex)));
+    }
+
+    @Override
+    public boolean startsWith(Path other) {
+        if (!(other instanceof NioPathForFileObject nio) || nio.fileSystem != 
fileSystem) {
+            return false;
+        }
+        if (nio.name.isEmpty()) {
+            return absolute;
+        }
+        return name.equals(nio.name) || name.startsWith(nio.name + "/");
+    }
+
+    @Override
+    public boolean startsWith(String other) {
+        return startsWith(fileSystem.getPath(other));
+    }
+
+    @Override
+    public boolean endsWith(Path other) {
+        if (!(other instanceof NioPathForFileObject nio) || nio.fileSystem != 
fileSystem) {
+            return false;
+        }
+        if (nio.absolute || nio.name.isEmpty()) {
+            return absolute == nio.absolute && name.equals(nio.name);
+        }
+        return name.equals(nio.name) || name.endsWith("/" + nio.name);
+    }
+
+    @Override
+    public boolean endsWith(String other) {
+        return endsWith(fileSystem.getPath(other));
+    }
+
+    @Override
+    public Path normalize() {
+        List<String> normalized = new ArrayList<>();
+        for (String part : names()) {
+            if (part.isEmpty() || part.equals(".")) {
+                continue;
+            }
+            if (part.equals("..")) {
+                if (!normalized.isEmpty()) {
+                    normalized.remove(normalized.size() - 1);
+                }
+            } else {
+                normalized.add(part);
+            }
+        }
+        String normalizedName = String.join("/", normalized);
+        FileObject fo = 
fileSystem.getFileSystem().findResource(normalizedName);
+        return create(fo, fileSystem, normalizedName);
+    }
+
+    @Override
+    public Path resolve(Path other) {
+        if (other.isAbsolute()) {
+            return other;
+        }
+        if (!(other instanceof NioPathForFileObject nio)) {
+            return resolve(other.toString());
+        }
+        return resolve(nio.name);
+    }
+
+    @Override
+    public Path resolve(String other) {
+        if (other.isEmpty()) {
+            return this;
+        }
+        String result = name.isEmpty() ? normalize(other) : normalize(name + 
"/" + other);
+        FileObject fo = fileSystem.getFileSystem().findResource(result);
+        return create(fo, fileSystem, result);
+    }
+
+    @Override
+    public Path resolveSibling(Path other) {
+        if (other.isAbsolute()) {
+            return other;
+        }
+        Path parent = getParent();
+        return parent == null ? other : parent.resolve(other);
+    }
+
+    @Override
+    public Path resolveSibling(String other) {
+        return resolveSibling(fileSystem.getPath(other));
+    }
+
+    @Override
+    public Path relativize(Path other) {
+        if (!(other instanceof NioPathForFileObject nio) || nio.fileSystem != 
fileSystem) {
+            throw new IllegalArgumentException("Cannot relativize different 
file systems");
+        }
+        List<String> base = names();
+        List<String> target = nio.names();
+        int common = 0;
+        while (common < base.size() && common < target.size() && 
base.get(common).equals(target.get(common))) {
+            common++;
+        }
+        List<String> result = new ArrayList<>();
+        for (int i = common; i < base.size(); i++) {
+            result.add("..");
+        }
+        result.addAll(target.subList(common, target.size()));
+        String relative = String.join("/", result);
+        return relative(null, fileSystem, relative.isEmpty() ? "" : relative);
+    }
+
+    @Override
+    public URI toUri() {
+        return fileObject.toURI();
+    }
+
+    @Override
+    public Path toAbsolutePath() {
+        return this;
+    }
+
+    @Override
+    public Path toRealPath(LinkOption... options) throws IOException {
+        if (fileObject == null) {
+            throw new IOException("No FileObject for " + name);
+        }
+        return normalize();
+    }
+
+    @Override
+    public File toFile() {
+        if (fileObject != null) {
+            File disk = FileUtil.toFile(fileObject);
+            if (disk != null) {
+                return disk;
+            }
+        }
+        throw new UnsupportedOperationException("Virtual FileObject has no 
java.io.File");
+    }
+
+    @Override
+    public WatchKey register(WatchService watcher, WatchEvent.Kind<?>[] 
events, WatchEvent.Modifier... modifiers) throws IOException {
+        if (!(watcher instanceof NioWatchService nioWatcher)) {
+            throw new IllegalArgumentException("Unsupported WatchService");
+        }
+        return nioWatcher.register(this, events);
+    }
+
+    @Override
+    public WatchKey register(WatchService watcher, WatchEvent.Kind<?>... 
events) throws IOException {
+        return register(watcher, events, new WatchEvent.Modifier[0]);
+    }
+
+    @Override
+    public Iterator<Path> iterator() {
+        List<Path> paths = new ArrayList<>();
+        for (String part : names()) {
+            paths.add(relative(null, fileSystem, part));
+        }
+        return paths.iterator();
+    }
+
+    @Override
+    public int compareTo(Path other) {
+        return toString().compareTo(other.toString());
+    }
+
+    @Override
+    public String toString() {
+        return absolute ? (name.isEmpty() ? "/" : "/" + name) : name;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj) {
+            return true;
+        }
+        if (!(obj instanceof NioPathForFileObject other)) {
+            return false;
+        }
+        return fileSystem == other.fileSystem && absolute == other.absolute && 
name.equals(other.name);
+    }
+
+    @Override
+    public int hashCode() {
+        return Objects.hash(fileSystem, name, absolute);
+    }
+
+    private List<String> names() {
+        List<String> names = new ArrayList<>();
+        if (!name.isEmpty()) {
+            for (String part : name.split("/")) {
+                if (!part.isEmpty()) {
+                    names.add(part);
+                }
+            }
+        }
+        return names;
+    }
+
+    private static String normalize(String name) {
+        if (name == null) {
+            return "";
+        }
+        String result = name.replace('\\', '/');
+        while (result.startsWith("/")) {
+            result = result.substring(1);
+        }
+        return result;
+    }
+
+    private static String fullName(FileObject fileObject) {
+        if (fileObject == null) {
+            return "";
+        }
+        List<String> names = new ArrayList<>();
+        FileObject current = fileObject;
+        while (current != null) {
+            String name = current.getNameExt();
+            if (!name.isEmpty()) {
+                names.add(0, name);

Review Comment:
   What about `names.add(name)` and using `String.join("/", names.reversed())` ?



##########
platform/openide.filesystems/src/org/openide/filesystems/NioFileObjectChannel.java:
##########
@@ -0,0 +1,651 @@
+/*
+ * 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 {
+    /*
+     * 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());

Review Comment:
   Nitpick: I don't like much sucking entire file content to a `byte[]` here. 
Very long files cannot be really accessed through `j.n.Files.newByteChannel` 
(even to read a header/preamble !). 
   
   But it is documented.



##########
platform/openide.filesystems/src/org/openide/filesystems/NioFileObjectChannel.java:
##########
@@ -0,0 +1,651 @@
+/*
+ * 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 {
+    /*
+     * 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 = options.contains(StandardOpenOption.READ);
+        boolean write = options.contains(StandardOpenOption.WRITE);
+        boolean append = options.contains(StandardOpenOption.APPEND);
+        if (append && read || append && 
options.contains(StandardOpenOption.TRUNCATE_EXISTING)) {
+            throw new IllegalArgumentException("Invalid append options");
+        }
+        write |= append;
+        if (!read && !write) {
+            read = true;
+        }
+        for (OpenOption option : options) {
+            Objects.requireNonNull(option, "option");
+            if (
+                option != StandardOpenOption.READ &&
+                option != StandardOpenOption.WRITE &&
+                option != StandardOpenOption.APPEND &&
+                option != StandardOpenOption.CREATE &&
+                option != StandardOpenOption.CREATE_NEW &&
+                option != StandardOpenOption.TRUNCATE_EXISTING
+            ) {
+                throw new UnsupportedOperationException("Unsupported open 
option: " + option);
+            }
+        }
+        if (attrs.length != 0) {
+            throw new UnsupportedOperationException("Initial attributes are 
not supported");
+        }
+        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(), 8192), size - start);

Review Comment:
   Why `8k` upper limit to a read chunk here ?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

For further information about the NetBeans mailing lists, visit:
https://cwiki.apache.org/confluence/display/NETBEANS/Mailing+lists

Reply via email to