From 1e503010762fbfd5f180c95cda692b5dce2e3ed7 Mon Sep 17 00:00:00 2001 From: Jaroslav Tulach Date: Sat, 21 Nov 2026 20:48:55 +0100 Subject: [PATCH 01/16] More tests for existing FileUtil.toPath --- .../filesystems/LocalFileSystemTest.java | 1 + .../org/openide/filesystems/PathTestHid.java | 142 ++++++++++++++++++ 2 files changed, 143 insertions(+) create mode 100644 platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java diff --git a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/LocalFileSystemTest.java b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/LocalFileSystemTest.java index ff625f84eb80..a44a087b647f 100644 --- a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/LocalFileSystemTest.java +++ b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/LocalFileSystemTest.java @@ -39,6 +39,7 @@ public static Test suite() { suite.addTestSuite(URLMapperTestHidden.class); suite.addTestSuite(URLMapperTestInternalHidden.class); suite.addTestSuite(FileUtilTestHidden.class); + suite.addTestSuite(PathTestHid.class); suite.addTestSuite(FileUtilJavaIOFileHidden.class); return new LocalFileSystemTest(suite); diff --git a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java new file mode 100644 index 000000000000..01ae9769e350 --- /dev/null +++ b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java @@ -0,0 +1,142 @@ +/* + * 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.nio.file.Path; +import java.nio.file.StandardWatchEventKinds; +import java.nio.file.WatchEvent; +import java.nio.file.WatchKey; +import java.nio.file.WatchService; +import java.util.Iterator; + +public class PathTestHid extends TestBaseHid { + + private FileObject root; + + public PathTestHid(String name) { + super(name); + } + + @Override + protected String[] getResources(String testName) { + return new String[] { + "pathtest/dir/file.txt", + "pathtest/dir/sibling.txt" + }; + } + + @Override + @SuppressWarnings("deprecation") + protected void setUp() throws Exception { + super.setUp(); + Repository.getDefault().addFileSystem(testedFS); + root = testedFS.findResource(getResourcePrefix()); + } + + @Override + @SuppressWarnings("deprecation") + protected void tearDown() throws Exception { + Repository.getDefault().removeFileSystem(testedFS); + super.tearDown(); + } + + public void testPathAccessorsAndNames() throws Exception { + Path path = getPath(); + + assertNotNull(path.getFileSystem()); + assertTrue(path.isAbsolute()); + assertNotNull(path.getRoot()); + assertEquals("file.txt", path.getFileName().toString()); + assertNotNull(path.getParent()); + assertTrue(path.getNameCount() > 0); + assertEquals(path.getFileName(), path.getName(path.getNameCount() - 1)); + assertEquals(path.getNameCount(), path.subpath(0, path.getNameCount()).getNameCount()); + assertTrue(path.startsWith(path.getRoot())); + assertTrue(path.startsWith(path.getParent())); + assertTrue(path.startsWith(path.getParent().toString())); + assertTrue(path.endsWith(path.getFileName())); + assertTrue(path.endsWith(path.getFileName().toString())); + assertEquals(path, path.normalize()); + + Iterator names = path.iterator(); + Path lastName = null; + while (names.hasNext()) { + lastName = names.next(); + } + assertEquals(path.getFileName(), lastName); + } + + public void testPathResolutionAndRelativization() throws Exception { + Path path = getPath(); + + Path parent = path.getParent(); + Path fileName = path.getFileName(); + assertEquals(path, parent.resolve(fileName)); + assertEquals(path, parent.resolve(fileName.toString())); + assertEquals(path, path.resolveSibling(path.getFileName())); + assertEquals(path, path.resolveSibling(path.getFileName().toString())); + assertEquals("sibling.txt", path.resolveSibling("sibling.txt").getFileName().toString()); + + Path relative = parent.relativize(path); + assertEquals(fileName, relative); + assertEquals(path, parent.resolve(relative)); + assertEquals(path.getFileSystem().getPath(""), path.relativize(path)); + } + + public void testPathConversionAndComparison() throws Exception { + FileObject fileObject = getFileObject(); + Path path = getPath(); + + Path samePath = path.getFileSystem().getPath(path.toString()); + assertEquals(path, samePath); + assertEquals(path.hashCode(), samePath.hashCode()); + assertEquals(0, path.compareTo(samePath)); + assertEquals(fileObject, FileUtil.toFileObject(path)); + assertTrue(path.toUri().isAbsolute()); + assertEquals(path.toAbsolutePath().toUri(), path.toUri()); + assertFalse(path.toString().isEmpty()); + + File file = FileUtil.toFile(fileObject); + assertEquals(file, path.toFile()); + assertEquals(file.getCanonicalFile().toPath(), path.toRealPath()); + } + + public void testPathWatchRegistration() throws Exception { + Path path = getPath(); + + try (WatchService watcher = path.getFileSystem().newWatchService()) { + WatchEvent.Kind[] events = {StandardWatchEventKinds.ENTRY_CREATE}; + WatchKey key = path.getParent().register(watcher, events); + assertTrue(key.isValid()); + WatchKey keyWithModifiers = path.getParent().register(watcher, events, new WatchEvent.Modifier[0]); + assertTrue(keyWithModifiers.isValid()); + } + } + + private FileObject getFileObject() { + FileObject fileObject = root.getFileObject("pathtest/dir/file.txt"); + assertNotNull(fileObject); + return fileObject; + } + + private Path getPath() { + return FileUtil.toPath(getFileObject()); + } +} From 35ecd7358bf6bd54bb5f5d68c9e188036ac524c9 Mon Sep 17 00:00:00 2001 From: Jaroslav Tulach Date: Sat, 21 Nov 2026 21:05:15 +0100 Subject: [PATCH 02/16] Testing also FileUtil.toFileObject(path) --- .../org/openide/filesystems/PathTestHid.java | 73 +++++++++++++++++-- 1 file changed, 68 insertions(+), 5 deletions(-) diff --git a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java index 01ae9769e350..3f629dd95bce 100644 --- a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java +++ b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java @@ -19,12 +19,17 @@ package org.openide.filesystems; import java.io.File; +import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardWatchEventKinds; import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.util.Iterator; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; public class PathTestHid extends TestBaseHid { @@ -118,15 +123,73 @@ public void testPathConversionAndComparison() throws Exception { assertEquals(file.getCanonicalFile().toPath(), path.toRealPath()); } - public void testPathWatchRegistration() throws Exception { - Path path = getPath(); + public void testFileSystemConversion() throws Exception { + FileObject fileObject = getFileObject(); + Path originalPath = getPath(); + java.nio.file.FileSystem nioFileSystem = originalPath.getFileSystem(); + Path path = nioFileSystem.getPath(originalPath.toString()); + + FileObject converted = FileUtil.toFileObject(path); + assertEquals(fileObject, converted); + assertSame(testedFS, converted.getFileSystem()); + } + + public void testCreateFileAndFolderThroughPath() throws Exception { + FileObject parent = getFileObject().getParent(); + Path folderPath = getPath().getParent().resolve("nio-folder"); + Path filePath = folderPath.resolve("nio-file.txt"); + + Files.createDirectory(folderPath); + Files.createFile(filePath); + Files.writeString(filePath, "created through NIO"); + + parent.refresh(); + FileObject folder = parent.getFileObject("nio-folder"); + assertNotNull(folder); + FileObject file = folder.getFileObject("nio-file.txt"); + assertNotNull(file); + assertTrue(folder.isFolder()); + assertTrue(file.isData()); + assertEquals(folder, file.getParent()); + assertEquals("created through NIO", file.asText()); + } - try (WatchService watcher = path.getFileSystem().newWatchService()) { + public void testWatchServiceAndFileChangeListener() throws Exception { + FileObject watchedFolder = getFileObject().getParent(); + Path folderPath = FileUtil.toPath(watchedFolder); + Path createdPath = folderPath.resolve("nio-watched.txt"); + CountDownLatch created = new CountDownLatch(1); + AtomicReference createdFile = new AtomicReference<>(); + FileChangeListener listener = new FileChangeAdapter() { + @Override + public void fileDataCreated(FileEvent event) { + if (event.getFile().getNameExt().equals("nio-watched.txt")) { + createdFile.set(event.getFile()); + created.countDown(); + } + } + }; + watchedFolder.addFileChangeListener(listener); + try (WatchService watcher = folderPath.getFileSystem().newWatchService()) { WatchEvent.Kind[] events = {StandardWatchEventKinds.ENTRY_CREATE}; - WatchKey key = path.getParent().register(watcher, events); + WatchKey key = folderPath.register(watcher, events); assertTrue(key.isValid()); - WatchKey keyWithModifiers = path.getParent().register(watcher, events, new WatchEvent.Modifier[0]); + WatchKey keyWithModifiers = folderPath.register(watcher, events, new WatchEvent.Modifier[0]); assertTrue(keyWithModifiers.isValid()); + + Files.createFile(createdPath); + + WatchKey eventKey = watcher.poll(5, TimeUnit.SECONDS); + assertNotNull(eventKey); + List> watchEvents = eventKey.pollEvents(); + assertEquals(1, watchEvents.size()); + assertEquals(createdPath.getFileName(), watchEvents.get(0).context()); + + watchedFolder.refresh(); + assertTrue("FileChangeListener was not notified", created.await(5, TimeUnit.SECONDS)); + assertEquals(FileUtil.toFileObject(createdPath), createdFile.get()); + } finally { + watchedFolder.removeFileChangeListener(listener); } } From e47e6420524eef1cfa5a3fcfac5c45877574c61f Mon Sep 17 00:00:00 2001 From: Jaroslav Tulach Date: Sat, 21 Nov 2026 21:12:17 +0100 Subject: [PATCH 03/16] Renaming via Path tests --- .../org/openide/filesystems/PathTestHid.java | 174 ++++++++++++++++++ 1 file changed, 174 insertions(+) diff --git a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java index 3f629dd95bce..cf257c81ac0e 100644 --- a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java +++ b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java @@ -25,9 +25,13 @@ import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; +import java.util.ArrayList; +import java.util.Arrays; import java.util.Iterator; import java.util.List; +import java.util.concurrent.BlockingQueue; import java.util.concurrent.CountDownLatch; +import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; @@ -193,6 +197,176 @@ public void fileDataCreated(FileEvent event) { } } + public void testRenameFileThroughPath() throws Exception { + FileObject file = getFileObject(); + FileObject parent = file.getParent(); + Path filePath = getPath(); + Path renamedPath = filePath.resolveSibling("nio-renamed.txt"); + BlockingQueue fileChangeEvents = new LinkedBlockingQueue<>(); + FileChangeListener listener = createEventListener(fileChangeEvents); + parent.addFileChangeListener(listener); + try (WatchService watcher = filePath.getFileSystem().newWatchService()) { + filePath.getParent().register( + watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE); + + Files.move(filePath, renamedPath); + + assertWatchEvents( + watcher, + new ExpectedWatchEvent(StandardWatchEventKinds.ENTRY_DELETE, filePath.getFileName()), + new ExpectedWatchEvent(StandardWatchEventKinds.ENTRY_CREATE, renamedPath.getFileName())); + parent.refresh(); + assertFileChangeEvents(fileChangeEvents, "deleted:file.txt", "dataCreated:nio-renamed.txt"); + assertFalse(file.isValid()); + assertNotNull(parent.getFileObject("nio-renamed.txt")); + } finally { + parent.removeFileChangeListener(listener); + } + } + + public void testRenameFolderThroughPath() throws Exception { + Path folderPath = getPath().getParent(); + Path parentPath = folderPath.getParent(); + Path renamedPath = parentPath.resolve("nio-renamed-folder"); + FileObject parent = getFileObject().getParent().getParent(); + FileObject folder = parent.getFileObject(folderPath.getFileName().toString()); + assertNotNull(folder); + BlockingQueue fileChangeEvents = new LinkedBlockingQueue<>(); + FileChangeListener listener = createEventListener(fileChangeEvents); + parent.addFileChangeListener(listener); + try (WatchService watcher = parentPath.getFileSystem().newWatchService()) { + parentPath.register( + watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE); + + Files.move(folderPath, renamedPath); + + assertWatchEvents( + watcher, + new ExpectedWatchEvent(StandardWatchEventKinds.ENTRY_DELETE, folderPath.getFileName()), + new ExpectedWatchEvent(StandardWatchEventKinds.ENTRY_CREATE, renamedPath.getFileName())); + parent.refresh(); + assertFileChangeEvents( + fileChangeEvents, "deleted:dir", "folderCreated:nio-renamed-folder"); + assertFalse(folder.isValid()); + assertNotNull(parent.getFileObject("nio-renamed-folder")); + } finally { + parent.removeFileChangeListener(listener); + } + } + + public void testCreateDeleteAndRecreateThroughPath() throws Exception { + FileObject parent = getFileObject().getParent(); + Path parentPath = getPath().getParent(); + Path filePath = parentPath.resolve("nio-cycle.txt"); + BlockingQueue fileChangeEvents = new LinkedBlockingQueue<>(); + FileChangeListener listener = createEventListener(fileChangeEvents); + parent.addFileChangeListener(listener); + try (WatchService watcher = parentPath.getFileSystem().newWatchService()) { + parentPath.register( + watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE); + + Files.createFile(filePath); + assertWatchEvents(watcher, new ExpectedWatchEvent( + StandardWatchEventKinds.ENTRY_CREATE, filePath.getFileName())); + parent.refresh(); + assertFileChangeEvents(fileChangeEvents, "dataCreated:nio-cycle.txt"); + FileObject created = parent.getFileObject("nio-cycle.txt"); + assertNotNull(created); + + Files.delete(filePath); + assertWatchEvents(watcher, new ExpectedWatchEvent( + StandardWatchEventKinds.ENTRY_DELETE, filePath.getFileName())); + parent.refresh(); + assertFileChangeEvents(fileChangeEvents, "deleted:nio-cycle.txt"); + assertFalse(created.isValid()); + assertNull(parent.getFileObject("nio-cycle.txt")); + + Files.createFile(filePath); + assertWatchEvents(watcher, new ExpectedWatchEvent( + StandardWatchEventKinds.ENTRY_CREATE, filePath.getFileName())); + parent.refresh(); + assertFileChangeEvents(fileChangeEvents, "dataCreated:nio-cycle.txt"); + FileObject recreated = parent.getFileObject("nio-cycle.txt"); + assertNotNull(recreated); + assertNotSame(created, recreated); + } finally { + parent.removeFileChangeListener(listener); + } + } + + private FileChangeListener createEventListener(BlockingQueue events) { + return new FileChangeAdapter() { + @Override + public void fileFolderCreated(FileEvent event) { + events.add("folderCreated:" + event.getFile().getNameExt()); + } + + @Override + public void fileDataCreated(FileEvent event) { + events.add("dataCreated:" + event.getFile().getNameExt()); + } + + @Override + public void fileDeleted(FileEvent event) { + events.add("deleted:" + event.getFile().getNameExt()); + } + + @Override + public void fileRenamed(FileRenameEvent event) { + events.add("renamed:" + event.getFile().getNameExt()); + } + }; + } + + private void assertFileChangeEvents(BlockingQueue events, String... expected) + throws InterruptedException { + List remaining = new ArrayList<>(Arrays.asList(expected)); + while (!remaining.isEmpty()) { + String event = events.poll(5, TimeUnit.SECONDS); + assertNotNull("Expected FileChangeListener event " + remaining, event); + assertTrue("Unexpected FileChangeListener event " + event, remaining.remove(event)); + } + } + + private void assertWatchEvents(WatchService watcher, ExpectedWatchEvent... expected) throws Exception { + List remaining = new ArrayList<>(Arrays.asList(expected)); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (!remaining.isEmpty()) { + long timeout = deadline - System.nanoTime(); + assertTrue("Expected WatchService events " + remaining, timeout > 0); + WatchKey key = watcher.poll(timeout, TimeUnit.NANOSECONDS); + assertNotNull("Expected WatchService events " + remaining, key); + for (WatchEvent event : key.pollEvents()) { + boolean matched = false; + for (Iterator it = remaining.iterator(); it.hasNext();) { + ExpectedWatchEvent candidate = it.next(); + if (candidate.kind == event.kind() && candidate.context.equals(event.context())) { + it.remove(); + matched = true; + break; + } + } + assertTrue("Unexpected WatchService event " + event.kind() + ": " + event.context(), matched); + } + assertTrue("WatchService key is no longer valid", key.reset()); + } + } + + private static final class ExpectedWatchEvent { + private final WatchEvent.Kind kind; + private final Path context; + + ExpectedWatchEvent(WatchEvent.Kind kind, Path context) { + this.kind = kind; + this.context = context; + } + + @Override + public String toString() { + return kind.name() + ": " + context; + } + } + private FileObject getFileObject() { FileObject fileObject = root.getFileObject("pathtest/dir/file.txt"); assertNotNull(fileObject); From ff9af808f03cc0929723a07e32186dc2ce8098f3 Mon Sep 17 00:00:00 2001 From: Jaroslav Tulach Date: Sat, 21 Nov 2026 21:31:21 +0100 Subject: [PATCH 04/16] Use Files.probeMimeType --- .../org/openide/filesystems/PathTestHid.java | 137 ++++++++++++++++++ 1 file changed, 137 insertions(+) diff --git a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java index cf257c81ac0e..526d722f5239 100644 --- a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java +++ b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java @@ -19,12 +19,19 @@ package org.openide.filesystems; import java.io.File; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.channels.FileChannel; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.StandardOpenOption; import java.nio.file.StandardWatchEventKinds; import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; +import java.nio.file.attribute.BasicFileAttributes; +import java.nio.file.attribute.FileTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; @@ -158,6 +165,116 @@ public void testCreateFileAndFolderThroughPath() throws Exception { assertEquals("created through NIO", file.asText()); } + public void testReadAndWriteThroughPathStreams() throws Exception { + FileObject file = getFileObject(); + Path path = getPath(); + byte[] original = Files.readAllBytes(path); + assertEquals(Files.size(path), file.getSize()); + try (InputStream input = Files.newInputStream(path)) { + assertTrue(Arrays.equals(original, input.readAllBytes())); + } + + String content = "Written through a Path output stream"; + while (content.getBytes(StandardCharsets.UTF_8).length == original.length) { + content += "!"; + } + byte[] contentBytes = content.getBytes(StandardCharsets.UTF_8); + CountDownLatch changed = new CountDownLatch(1); + FileChangeListener listener = new FileChangeAdapter() { + @Override + public void fileChanged(FileEvent event) { + changed.countDown(); + } + }; + file.addFileChangeListener(listener); + try (WatchService watcher = path.getFileSystem().newWatchService()) { + path.getParent().register(watcher, StandardWatchEventKinds.ENTRY_MODIFY); + try (OutputStream output = Files.newOutputStream(path)) { + output.write(contentBytes); + } + + assertWatchEventPresent( + watcher, new ExpectedWatchEvent(StandardWatchEventKinds.ENTRY_MODIFY, path.getFileName())); + file.refresh(); + assertTrue("FileChangeListener was not notified", changed.await(5, TimeUnit.SECONDS)); + assertEquals(content, file.asText("UTF-8")); + assertEquals(contentBytes.length, Files.size(path)); + assertEquals(Files.size(path), file.getSize()); + try (InputStream input = Files.newInputStream(path)) { + assertEquals(content, new String(input.readAllBytes(), StandardCharsets.UTF_8)); + } + } finally { + file.removeFileChangeListener(listener); + } + } + + public void testPathSizeAndBasicAttributes() throws Exception { + FileObject file = getFileObject(); + Path path = getPath(); + BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class); + assertEquals(attributes.size(), Files.size(path)); + assertEquals(attributes.size(), file.getSize()); + assertEquals(attributes.lastModifiedTime().toMillis(), file.lastModified().getTime()); + + FileTime modified = FileTime.fromMillis(attributes.lastModifiedTime().toMillis() + 10000); + CountDownLatch changed = new CountDownLatch(1); + FileChangeListener listener = new FileChangeAdapter() { + @Override + public void fileChanged(FileEvent event) { + changed.countDown(); + } + }; + file.addFileChangeListener(listener); + try (WatchService watcher = path.getFileSystem().newWatchService()) { + path.getParent().register(watcher, StandardWatchEventKinds.ENTRY_MODIFY); + Files.setAttribute(path, "basic:lastModifiedTime", modified); + assertEquals(modified, Files.getAttribute(path, "basic:lastModifiedTime")); + assertEquals(modified, Files.getLastModifiedTime(path)); + assertWatchEventPresent( + watcher, new ExpectedWatchEvent(StandardWatchEventKinds.ENTRY_MODIFY, path.getFileName())); + + file.refresh(); + assertTrue("FileChangeListener was not notified", changed.await(5, TimeUnit.SECONDS)); + assertEquals(modified.toMillis(), file.lastModified().getTime()); + } finally { + file.removeFileChangeListener(listener); + } + } + + public void testPathFileChannelLock() throws Exception { + FileObject file = getFileObject(); + Path path = getPath(); + assertFalse(file.isLocked()); + + try (FileChannel channel = FileChannel.open(path, StandardOpenOption.WRITE)) { + java.nio.channels.FileLock nioLock = channel.lock(); + try { + assertTrue(nioLock.isValid()); + assertFalse(file.isLocked()); + } finally { + nioLock.release(); + } + assertFalse(nioLock.isValid()); + } + + FileLock fileObjectLock = file.lock(); + try { + assertTrue(file.isLocked()); + } finally { + fileObjectLock.releaseLock(); + } + assertFalse(file.isLocked()); + } + + public void testMIMETypeAfterPathConversion() throws Exception { + Path path = getPath(); + Files.writeString(path, "Plain text content\n"); + FileObject file = FileUtil.toFileObject(path); + assertNotNull(file); + file.refresh(); + assertEquals(Files.probeContentType(path), file.getMIMEType()); + } + public void testWatchServiceAndFileChangeListener() throws Exception { FileObject watchedFolder = getFileObject().getParent(); Path folderPath = FileUtil.toPath(watchedFolder); @@ -352,6 +469,26 @@ private void assertWatchEvents(WatchService watcher, ExpectedWatchEvent... expec } } + private void assertWatchEventPresent(WatchService watcher, ExpectedWatchEvent expected) throws Exception { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (true) { + long timeout = deadline - System.nanoTime(); + assertTrue("Expected WatchService event " + expected, timeout > 0); + WatchKey key = watcher.poll(timeout, TimeUnit.NANOSECONDS); + assertNotNull("Expected WatchService event " + expected, key); + boolean found = false; + for (WatchEvent event : key.pollEvents()) { + assertEquals("Unexpected WatchService event kind", expected.kind, event.kind()); + assertEquals("Unexpected WatchService event context", expected.context, event.context()); + found = true; + } + assertTrue("WatchService key is no longer valid", key.reset()); + if (found) { + return; + } + } + } + private static final class ExpectedWatchEvent { private final WatchEvent.Kind kind; private final Path context; From 9b03fd01a54a06ce2f1a94f623c01ca5ae33361e Mon Sep 17 00:00:00 2001 From: Jaroslav Tulach Date: Sat, 21 Nov 2026 21:47:16 +0100 Subject: [PATCH 05/16] Running the PathTestHid on masterfs --- .../filebasedfs/FileBasedFileSystemTest.java | 1 + .../org/openide/filesystems/PathTestHid.java | 31 +++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/platform/masterfs/test/unit/src/org/netbeans/modules/masterfs/filebasedfs/FileBasedFileSystemTest.java b/platform/masterfs/test/unit/src/org/netbeans/modules/masterfs/filebasedfs/FileBasedFileSystemTest.java index aa6427dc0d60..abbd13cc2747 100644 --- a/platform/masterfs/test/unit/src/org/netbeans/modules/masterfs/filebasedfs/FileBasedFileSystemTest.java +++ b/platform/masterfs/test/unit/src/org/netbeans/modules/masterfs/filebasedfs/FileBasedFileSystemTest.java @@ -54,6 +54,7 @@ static NbTestSuite suite(boolean created) { NbTestSuite suite = new NbTestSuite(); suite.addTestSuite(FileSystemTestHid.class); suite.addTestSuite(FileObjectTestHid.class); + suite.addTestSuite(PathTestHid.class); suite.addTestSuite(URLMapperTestHidden.class); suite.addTestSuite(FileUtilTestHidden.class); suite.addTestSuite(FileUtilJavaIOFileHidden.class); diff --git a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java index 526d722f5239..b3032924d710 100644 --- a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java +++ b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java @@ -34,13 +34,17 @@ import java.nio.file.attribute.FileTime; import java.util.ArrayList; import java.util.Arrays; +import java.util.HashSet; import java.util.Iterator; import java.util.List; +import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; +import java.util.stream.Collectors; +import java.util.stream.Stream; public class PathTestHid extends TestBaseHid { @@ -99,6 +103,25 @@ public void testPathAccessorsAndNames() throws Exception { assertEquals(path.getFileName(), lastName); } + public void testListChildrenThroughPath() throws Exception { + FileObject folder = getFileObject().getParent(); + FileObject[] children = folder.getChildren(); + Set fileObjectNames = new HashSet<>(); + for (FileObject child : children) { + fileObjectNames.add(child.getNameExt()); + } + + Set pathNames; + try (Stream entries = Files.list(FileUtil.toPath(folder))) { + pathNames = entries + .map(entry -> entry.getFileName().toString()) + .collect(Collectors.toSet()); + } + + assertEquals(fileObjectNames, pathNames); + assertEquals(2, children.length); + } + public void testPathResolutionAndRelativization() throws Exception { Path path = getPath(); @@ -277,6 +300,7 @@ public void testMIMETypeAfterPathConversion() throws Exception { public void testWatchServiceAndFileChangeListener() throws Exception { FileObject watchedFolder = getFileObject().getParent(); + FileObject[] children = watchedFolder.getChildren(); Path folderPath = FileUtil.toPath(watchedFolder); Path createdPath = folderPath.resolve("nio-watched.txt"); CountDownLatch created = new CountDownLatch(1); @@ -312,11 +336,13 @@ public void fileDataCreated(FileEvent event) { } finally { watchedFolder.removeFileChangeListener(listener); } + assertEquals(2, children.length); } public void testRenameFileThroughPath() throws Exception { FileObject file = getFileObject(); FileObject parent = file.getParent(); + FileObject[] children = parent.getChildren(); Path filePath = getPath(); Path renamedPath = filePath.resolveSibling("nio-renamed.txt"); BlockingQueue fileChangeEvents = new LinkedBlockingQueue<>(); @@ -339,6 +365,7 @@ public void testRenameFileThroughPath() throws Exception { } finally { parent.removeFileChangeListener(listener); } + assertEquals(2, children.length); } public void testRenameFolderThroughPath() throws Exception { @@ -346,6 +373,7 @@ public void testRenameFolderThroughPath() throws Exception { Path parentPath = folderPath.getParent(); Path renamedPath = parentPath.resolve("nio-renamed-folder"); FileObject parent = getFileObject().getParent().getParent(); + FileObject[] children = parent.getChildren(); FileObject folder = parent.getFileObject(folderPath.getFileName().toString()); assertNotNull(folder); BlockingQueue fileChangeEvents = new LinkedBlockingQueue<>(); @@ -369,10 +397,12 @@ public void testRenameFolderThroughPath() throws Exception { } finally { parent.removeFileChangeListener(listener); } + assertEquals(1, children.length); } public void testCreateDeleteAndRecreateThroughPath() throws Exception { FileObject parent = getFileObject().getParent(); + FileObject[] children = parent.getChildren(); Path parentPath = getPath().getParent(); Path filePath = parentPath.resolve("nio-cycle.txt"); BlockingQueue fileChangeEvents = new LinkedBlockingQueue<>(); @@ -409,6 +439,7 @@ public void testCreateDeleteAndRecreateThroughPath() throws Exception { } finally { parent.removeFileChangeListener(listener); } + assertEquals(2, children.length); } private FileChangeListener createEventListener(BlockingQueue events) { From bc3c106368e522e70acc827a197d65fd872fe1b8 Mon Sep 17 00:00:00 2001 From: Jaroslav Tulach Date: Sat, 21 Nov 2026 22:23:48 +0100 Subject: [PATCH 06/16] Fallback implementation of Path for all FileObjects --- .../declmime/NioFileTypeDetector.java | 35 ++ .../src/org/openide/filesystems/FileUtil.java | 17 +- .../filesystems/NioFsForFileSystem.java | 135 +++++++ .../filesystems/NioPathForFileObject.java | 366 ++++++++++++++++++ .../openide/filesystems/NioPathProvider.java | 357 +++++++++++++++++ .../openide/filesystems/NioWatchService.java | 114 ++++++ .../filesystems/JarFileSystemTest.java | 1 + .../org/openide/filesystems/PathTestHid.java | 43 +- 8 files changed, 1062 insertions(+), 6 deletions(-) create mode 100644 platform/openide.filesystems/src/org/netbeans/modules/openide/filesystems/declmime/NioFileTypeDetector.java create mode 100644 platform/openide.filesystems/src/org/openide/filesystems/NioFsForFileSystem.java create mode 100644 platform/openide.filesystems/src/org/openide/filesystems/NioPathForFileObject.java create mode 100644 platform/openide.filesystems/src/org/openide/filesystems/NioPathProvider.java create mode 100644 platform/openide.filesystems/src/org/openide/filesystems/NioWatchService.java 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/FileUtil.java b/platform/openide.filesystems/src/org/openide/filesystems/FileUtil.java index e2ebc7aa6200..7fa205478b4d 100644 --- a/platform/openide.filesystems/src/org/openide/filesystems/FileUtil.java +++ b/platform/openide.filesystems/src/org/openide/filesystems/FileUtil.java @@ -837,12 +837,22 @@ public static File toFile(FileObject fo) { * 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. + * @return java.nio.file.Path for the FileObject * @since 9.32 */ public static Path toPath(FileObject fo) { + Parameters.notNull("fo", fo); File f = toFile(fo); - return f != null ? f.toPath() : null; + if (f != null) { + return f.toPath(); + } + try { + org.openide.filesystems.FileSystem fs = fo.getFileSystem(); + NioFsForFileSystem nioFs = new NioFsForFileSystem(fs); + return NioPathForFileObject.create(fo, nioFs); + } catch (FileStateInvalidException ex) { + throw new IllegalStateException("FileObject has no valid filesystem", ex); + } } /** @@ -919,6 +929,9 @@ public static FileObject toFileObject(File file) { * @since 9.32 */ public static FileObject toFileObject(Path path) { + if (path instanceof NioPathForFileObject nioPath) { + return nioPath.getFileObject(); + } try { return toFileObject(path.toFile()); } catch (UnsupportedOperationException ex) { diff --git a/platform/openide.filesystems/src/org/openide/filesystems/NioFsForFileSystem.java b/platform/openide.filesystems/src/org/openide/filesystems/NioFsForFileSystem.java new file mode 100644 index 000000000000..7def244d3b40 --- /dev/null +++ b/platform/openide.filesystems/src/org/openide/filesystems/NioFsForFileSystem.java @@ -0,0 +1,135 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.openide.filesystems; + +import java.io.IOException; +import java.nio.file.FileStore; +import java.nio.file.FileSystem; +import java.nio.file.Path; +import java.nio.file.PathMatcher; +import java.nio.file.WatchService; +import java.nio.file.attribute.UserPrincipalLookupService; +import java.nio.file.spi.FileSystemProvider; +import java.util.Collections; +import java.util.Set; + +final class NioFsForFileSystem extends FileSystem { + private final org.openide.filesystems.FileSystem fileSystem; + private final NioPathProvider provider; + + NioFsForFileSystem(org.openide.filesystems.FileSystem fileSystem) { + this.fileSystem = fileSystem; + this.provider = new NioPathProvider(this); + } + + org.openide.filesystems.FileSystem getFileSystem() { + return fileSystem; + } + + @Override + public FileSystemProvider provider() { + return provider; + } + + @Override + public void close() { + } + + @Override + public boolean isOpen() { + return true; + } + + @Override + public boolean isReadOnly() { + return fileSystem.isReadOnly(); + } + + @Override + public String getSeparator() { + return "/"; + } + + @Override + public Iterable getRootDirectories() { + return Collections.singletonList(NioPathForFileObject.create(fileSystem.getRoot(), this)); + } + + @Override + public Iterable getFileStores() { + return Collections.emptyList(); + } + + @Override + public Set supportedFileAttributeViews() { + return Collections.singleton("basic"); + } + + @Override + public Path getPath(String first, String... more) { + StringBuilder value = new StringBuilder(first); + for (String part : more) { + if (!value.isEmpty() && value.charAt(value.length() - 1) != '/') { + value.append('/'); + } + value.append(part); + } + String normalized = normalizedPath(value.toString()); + FileObject fo = fileSystem.findResource(normalized); + String name = normalizeName(value.toString()); + if (!value.toString().startsWith("/")) { + return NioPathForFileObject.relative(fo, this, name); + } + return NioPathForFileObject.create(fo, this, name); + } + + private String normalizedPath(String value) { + if (value.isEmpty()) { + return ""; + } + String result = value.replace('\\', '/'); + while (result.startsWith("/")) { + result = result.substring(1); + } + return result; + } + + private String normalizeName(String value) { + String result = value.replace('\\', '/'); + while (result.startsWith("/")) { + result = result.substring(1); + } + return result; + } + + @Override + public PathMatcher getPathMatcher(String syntaxAndPattern) { + throw new UnsupportedOperationException("PathMatcher is not supported"); + } + + @Override + public UserPrincipalLookupService getUserPrincipalLookupService() { + throw new UnsupportedOperationException("User lookup is not supported"); + } + + @Override + public WatchService newWatchService() throws IOException { + return new NioWatchService(); + } +} diff --git a/platform/openide.filesystems/src/org/openide/filesystems/NioPathForFileObject.java b/platform/openide.filesystems/src/org/openide/filesystems/NioPathForFileObject.java new file mode 100644 index 000000000000..d1ac16b59a7d --- /dev/null +++ b/platform/openide.filesystems/src/org/openide/filesystems/NioPathForFileObject.java @@ -0,0 +1,366 @@ +/* + * 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.InvalidPathException; +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() { + return fileObject; + } + + @Override + public java.nio.file.FileSystem getFileSystem() { + return fileSystem; + } + + @Override + public boolean isAbsolute() { + return absolute; + } + + @Override + public Path getRoot() { + return create(fileSystem.getFileSystem().getRoot(), fileSystem); + } + + @Override + public Path getFileName() { + if (name.isEmpty()) { + return null; + } + int separator = name.lastIndexOf('/'); + String fileName = separator == -1 ? name : name.substring(separator + 1); + return fileName.isEmpty() ? null : relative(fileObject, fileSystem, fileName); + } + + @Override + public Path getParent() { + if (name.isEmpty()) { + return null; + } + int separator = name.lastIndexOf('/'); + if (separator == -1) { + return getRoot(); + } + String parentName = name.substring(0, separator); + FileObject parent = fileSystem.getFileSystem().findResource(parentName); + if (parent == null && fileObject != null) { + parent = fileObject.getParent(); + } + return create(parent, fileSystem, parentName); + } + + @Override + public int getNameCount() { + if (name.isEmpty()) { + return 1; + } + int count = 0; + for (String part : name.split("/")) { + if (!part.isEmpty()) { + count++; + } + } + return count; + } + + @Override + public Path getName(int index) { + if (index < 0 || index >= getNameCount()) { + throw new IllegalArgumentException("Illegal name index: " + index); + } + List names = names(); + return relative(null, fileSystem, names.get(index)); + } + + @Override + public Path subpath(int beginIndex, int endIndex) { + if (beginIndex < 0 || endIndex > getNameCount() || beginIndex >= endIndex) { + throw new IllegalArgumentException(); + } + List names = names(); + return relative(null, fileSystem, String.join("/", names.subList(beginIndex, endIndex))); + } + + @Override + public boolean startsWith(Path other) { + if (!(other instanceof NioPathForFileObject nio) || nio.fileSystem != fileSystem) { + return false; + } + if (nio.name.isEmpty()) { + return absolute; + } + return name.equals(nio.name) || name.startsWith(nio.name + "/"); + } + + @Override + public boolean startsWith(String other) { + return startsWith(fileSystem.getPath(other)); + } + + @Override + public boolean endsWith(Path other) { + if (!(other instanceof NioPathForFileObject nio) || nio.fileSystem != fileSystem) { + return false; + } + return name.equals(nio.name) || name.endsWith("/" + nio.name) || name.endsWith(nio.name); + } + + @Override + public boolean endsWith(String other) { + return endsWith(fileSystem.getPath(other)); + } + + @Override + public Path normalize() { + List normalized = new ArrayList<>(); + for (String part : names()) { + if (part.isEmpty() || part.equals(".")) { + continue; + } + if (part.equals("..")) { + if (!normalized.isEmpty()) { + normalized.remove(normalized.size() - 1); + } + } else { + normalized.add(part); + } + } + String normalizedName = String.join("/", normalized); + FileObject fo = fileSystem.getFileSystem().findResource(normalizedName); + return create(fo, fileSystem, normalizedName); + } + + @Override + public Path resolve(Path other) { + if (other.isAbsolute()) { + return other; + } + if (!(other instanceof NioPathForFileObject nio)) { + return resolve(other.toString()); + } + return resolve(nio.name); + } + + @Override + public Path resolve(String other) { + if (other.isEmpty()) { + return this; + } + String result = name.isEmpty() ? normalize(other) : normalize(name + "/" + other); + FileObject fo = fileSystem.getFileSystem().findResource(result); + return create(fo, fileSystem, result); + } + + @Override + public Path resolveSibling(Path other) { + if (other.isAbsolute()) { + return other; + } + Path parent = getParent(); + return parent == null ? other : parent.resolve(other); + } + + @Override + public Path resolveSibling(String other) { + return resolveSibling(fileSystem.getPath(other)); + } + + @Override + public Path relativize(Path other) { + if (!(other instanceof NioPathForFileObject nio) || nio.fileSystem != fileSystem) { + throw new IllegalArgumentException("Cannot relativize different file systems"); + } + List base = names(); + List target = nio.names(); + int common = 0; + while (common < base.size() && common < target.size() && base.get(common).equals(target.get(common))) { + common++; + } + List result = new ArrayList<>(); + for (int i = common; i < base.size(); i++) { + result.add(".."); + } + result.addAll(target.subList(common, target.size())); + String relative = String.join("/", result); + return relative(null, fileSystem, relative.isEmpty() ? "" : relative); + } + + @Override + public URI toUri() { + String path = name.isEmpty() ? "/" : "/" + name; + return URI.create("openide://" + fileSystem.getFileSystem().getDisplayName() + path); + } + + @Override + public Path toAbsolutePath() { + return this; + } + + @Override + public Path toRealPath(LinkOption... options) throws IOException { + if (fileObject == null) { + throw new IOException("No FileObject for " + name); + } + return normalize(); + } + + @Override + public File toFile() { + if (fileObject != null) { + File disk = FileUtil.toFile(fileObject); + if (disk != null) { + return disk; + } + } + throw new UnsupportedOperationException("Virtual FileObject has no java.io.File"); + } + + @Override + public WatchKey register(WatchService watcher, WatchEvent.Kind[] events, WatchEvent.Modifier... modifiers) throws IOException { + if (!(watcher instanceof NioWatchService nioWatcher)) { + throw new IllegalArgumentException("Unsupported WatchService"); + } + return nioWatcher.register(this, events); + } + + @Override + public WatchKey register(WatchService watcher, WatchEvent.Kind... events) throws IOException { + return register(watcher, events, new WatchEvent.Modifier[0]); + } + + @Override + public Iterator iterator() { + List paths = new ArrayList<>(); + for (String part : names()) { + paths.add(relative(null, fileSystem, part)); + } + return paths.iterator(); + } + + @Override + public int compareTo(Path other) { + return toString().compareTo(other.toString()); + } + + @Override + public String toString() { + return absolute ? (name.isEmpty() ? "/" : "/" + name) : name; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (!(obj instanceof NioPathForFileObject other)) { + return false; + } + return fileSystem == other.fileSystem && absolute == other.absolute && name.equals(other.name); + } + + @Override + public int hashCode() { + return Objects.hash(fileSystem, name, absolute); + } + + private List names() { + List names = new ArrayList<>(); + if (!name.isEmpty()) { + for (String part : name.split("/")) { + if (!part.isEmpty()) { + names.add(part); + } + } + } + return names; + } + + private static String normalize(String name) { + if (name == null) { + return ""; + } + String result = name.replace('\\', '/'); + while (result.startsWith("/")) { + result = result.substring(1); + } + return result; + } + + private static String fullName(FileObject fileObject) { + if (fileObject == null) { + return ""; + } + List names = new ArrayList<>(); + FileObject current = fileObject; + while (current != null) { + String name = current.getNameExt(); + if (!name.isEmpty()) { + names.add(0, name); + } + current = current.getParent(); + } + return String.join("/", names); + } + + static NioPathForFileObject fromInvalidPath(String name, NioFsForFileSystem fileSystem) { + return new NioPathForFileObject(null, fileSystem, name); + } +} diff --git a/platform/openide.filesystems/src/org/openide/filesystems/NioPathProvider.java b/platform/openide.filesystems/src/org/openide/filesystems/NioPathProvider.java new file mode 100644 index 000000000000..f65e9295514b --- /dev/null +++ b/platform/openide.filesystems/src/org/openide/filesystems/NioPathProvider.java @@ -0,0 +1,357 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.openide.filesystems; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URI; +import java.nio.channels.SeekableByteChannel; +import java.nio.ByteBuffer; +import java.nio.file.AccessDeniedException; +import java.nio.file.AccessMode; +import java.nio.file.CopyOption; +import java.nio.file.DirectoryStream; +import java.nio.file.FileStore; +import java.nio.file.FileSystem; +import java.nio.file.LinkOption; +import java.nio.file.NoSuchFileException; +import java.nio.file.OpenOption; +import java.nio.file.Path; +import java.nio.file.attribute.BasicFileAttributes; +import java.nio.file.attribute.FileAttribute; +import java.nio.file.attribute.FileTime; +import java.nio.file.spi.FileSystemProvider; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +final class NioPathProvider extends FileSystemProvider { + private final NioFsForFileSystem fileSystem; + + NioPathProvider(NioFsForFileSystem fileSystem) { + this.fileSystem = fileSystem; + } + + @Override + public String getScheme() { + return "openide"; + } + + @Override + public FileSystem newFileSystem(URI uri, Map env) { + throw new UnsupportedOperationException(); + } + + @Override + public FileSystem getFileSystem(URI uri) { + return fileSystem; + } + + @Override + public Path getPath(URI uri) { + String path = uri.getPath(); + return fileSystem.getPath(path); + } + + @Override + public SeekableByteChannel newByteChannel( + Path path, Set options, FileAttribute... attrs) throws IOException { + if (options.stream().anyMatch(option -> + option == java.nio.file.StandardOpenOption.WRITE + || option == java.nio.file.StandardOpenOption.APPEND + || option == java.nio.file.StandardOpenOption.CREATE + || option == java.nio.file.StandardOpenOption.CREATE_NEW)) { + throw new AccessDeniedException(path.toString(), null, "The filesystem is read-only"); + } + FileObject fo = asPath(path).getFileObject(); + if (fo == null || !fo.isValid()) { + throw new NoSuchFileException(path.toString()); + } + return new FileObjectByteChannel(fo); + } + + @Override + public DirectoryStream newDirectoryStream(Path dir, DirectoryStream.Filter filter) + throws IOException { + NioPathForFileObject nio = asPath(dir); + FileObject folder = nio.getFileObject(); + if (folder == null || !folder.isFolder()) { + throw new NoSuchFileException(dir.toString()); + } + FileObject[] children = folder.getChildren(); + java.util.List paths = new java.util.ArrayList<>(); + for (FileObject child : children) { + Path childPath = NioPathForFileObject.create(child, fileSystem); + if (filter.accept(childPath)) { + paths.add(childPath); + } + } + return new DirectoryStream() { + @Override + public Iterator iterator() { + return paths.iterator(); + } + + @Override + public void close() { + } + }; + } + + @Override + public void createDirectory(Path dir, FileAttribute... attrs) throws IOException { + throw new AccessDeniedException(dir.toString(), null, "The filesystem is read-only"); + } + + @Override + public void delete(Path path) throws IOException { + throw new AccessDeniedException(path.toString(), null, "The filesystem is read-only"); + } + + @Override + public void copy(Path source, Path target, CopyOption... options) throws IOException { + throw new UnsupportedOperationException("Copy is not supported"); + } + + @Override + public void move(Path source, Path target, CopyOption... options) throws IOException { + throw new UnsupportedOperationException("Move is not supported"); + } + + @Override + public boolean isSameFile(Path path, Path path2) throws IOException { + NioPathForFileObject first = asPath(path); + NioPathForFileObject second = asPath(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 = asPath(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 = asPath(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 = asPath(path).getFileObject(); + if (fo == null || !fo.isValid()) { + throw new NoSuchFileException(path.toString()); + } + final FileTime modified = FileTime.fromMillis(fo.lastModified().getTime()); + final BasicFileAttributes attrs = new BasicFileAttributes() { + @Override + public FileTime lastModifiedTime() { + return modified; + } + + @Override + public FileTime lastAccessTime() { + return modified; + } + + @Override + public FileTime creationTime() { + return modified; + } + + @Override + public boolean isRegularFile() { + return fo.isData(); + } + + @Override + public boolean isDirectory() { + return fo.isFolder(); + } + + @Override + public boolean isSymbolicLink() { + return false; + } + + @Override + public boolean isOther() { + return !fo.isData() && !fo.isFolder(); + } + + @Override + public long size() { + return fo.getSize(); + } + + @Override + public Object fileKey() { + return fo; + } + }; + @SuppressWarnings("unchecked") + A result = (A) attrs; + return result; + } + + @Override + public Map readAttributes( + Path path, String attributes, LinkOption... options) throws IOException { + BasicFileAttributes attrs = readAttributes(path, BasicFileAttributes.class, options); + if ("*".equals(attributes) || "basic:*".equals(attributes)) { + java.util.Map result = new java.util.HashMap<>(); + result.put("lastModifiedTime", attrs.lastModifiedTime()); + result.put("lastAccessTime", attrs.lastAccessTime()); + result.put("creationTime", attrs.creationTime()); + result.put("size", attrs.size()); + result.put("isRegularFile", attrs.isRegularFile()); + result.put("isDirectory", attrs.isDirectory()); + result.put("isSymbolicLink", attrs.isSymbolicLink()); + result.put("isOther", attrs.isOther()); + result.put("fileKey", attrs.fileKey()); + return result; + } + if ("basic:lastModifiedTime".equals(attributes)) { + return Map.of("lastModifiedTime", attrs.lastModifiedTime()); + } + throw new UnsupportedOperationException("Unsupported attributes"); + } + + @Override + public void setAttribute(Path path, String attribute, Object value, LinkOption... options) + throws IOException { + throw new AccessDeniedException(path.toString(), null, "The filesystem is read-only"); + } + + @Override + public InputStream newInputStream(Path path, OpenOption... options) throws IOException { + FileObject fo = asPath(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 { + throw new AccessDeniedException(path.toString(), null, "The filesystem is read-only"); + } + + private NioPathForFileObject asPath(Path path) { + if (!(path instanceof NioPathForFileObject nio)) { + throw new IllegalArgumentException("Not a NetBeans FileObject path"); + } + return nio; + } + + private static final class FileObjectByteChannel implements SeekableByteChannel { + private final byte[] bytes; + private long position; + private boolean open = true; + + FileObjectByteChannel(FileObject fileObject) throws IOException { + try (InputStream input = fileObject.getInputStream()) { + bytes = input.readAllBytes(); + } + } + + @Override + public int read(ByteBuffer dst) throws IOException { + if (!open) { + throw new java.nio.channels.ClosedChannelException(); + } + int remaining = (int) Math.min(dst.remaining(), bytes.length - position); + if (remaining <= 0) { + return -1; + } + dst.put(bytes, (int) position, remaining); + position += remaining; + return remaining; + } + + @Override + public int write(ByteBuffer src) { + throw new UnsupportedOperationException("Read-only"); + } + + @Override + public long position() { + return position; + } + + @Override + public SeekableByteChannel position(long newPosition) { + if (newPosition < 0) { + throw new IllegalArgumentException(); + } + position = newPosition; + return this; + } + + @Override + public long size() { + return bytes.length; + } + + @Override + public SeekableByteChannel truncate(long size) { + throw new UnsupportedOperationException("Read-only"); + } + + @Override + public boolean isOpen() { + return open; + } + + @Override + public void close() { + open = false; + } + } +} 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..8fc81de2190e --- /dev/null +++ b/platform/openide.filesystems/src/org/openide/filesystems/NioWatchService.java @@ -0,0 +1,114 @@ +/* + * 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.nio.file.ClosedWatchServiceException; +import java.nio.file.Path; +import java.nio.file.StandardWatchEventKinds; +import java.nio.file.Watchable; +import java.nio.file.WatchEvent; +import java.nio.file.WatchKey; +import java.nio.file.WatchService; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; + +final class NioWatchService implements WatchService { + private final BlockingQueue keys = new LinkedBlockingQueue<>(); + private boolean closed; + + WatchKey register(Path path, WatchEvent.Kind[] events) { + NioWatchKey key = new NioWatchKey(this, path, events); + return key; + } + + @Override + public WatchKey poll() throws ClosedWatchServiceException { + checkClosed(); + return keys.poll(); + } + + @Override + public WatchKey poll(long timeout, TimeUnit unit) + throws ClosedWatchServiceException, InterruptedException { + checkClosed(); + return keys.poll(timeout, unit); + } + + @Override + public WatchKey take() throws ClosedWatchServiceException, InterruptedException { + checkClosed(); + return keys.take(); + } + + @Override + public void close() { + closed = true; + } + + void checkClosed() { + if (closed) { + throw new ClosedWatchServiceException(); + } + } + + private static final class NioWatchKey implements WatchKey { + private final NioWatchService service; + private final Path path; + private final WatchEvent.Kind[] events; + private boolean valid = true; + + NioWatchKey(NioWatchService service, Path path, WatchEvent.Kind[] events) { + this.service = service; + this.path = path; + this.events = events.clone(); + } + + @Override + public boolean isValid() { + return valid && !service.closed; + } + + @Override + public List> pollEvents() { + return new ArrayList<>(); + } + + @Override + public boolean reset() { + if (!isValid()) { + return false; + } + return true; + } + + @Override + public void cancel() { + valid = false; + } + + @Override + public Watchable watchable() { + return path; + } + } +} diff --git a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/JarFileSystemTest.java b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/JarFileSystemTest.java index 8ec3bb7551d3..ed92302b0de9 100644 --- a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/JarFileSystemTest.java +++ b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/JarFileSystemTest.java @@ -42,6 +42,7 @@ public static Test suite() { suite.addTestSuite(RepositoryTestHid.class); suite.addTestSuite(FileSystemTestHid.class); suite.addTestSuite(FileObjectTestHid.class); + suite.addTestSuite(PathTestHid.class); /*failing tests*/ suite.addTestSuite(URLMapperTestHidden.class); suite.addTestSuite(URLMapperTestInternalHidden.class); diff --git a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java index b3032924d710..cae1442e4776 100644 --- a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java +++ b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java @@ -152,9 +152,18 @@ public void testPathConversionAndComparison() throws Exception { assertEquals(path.toAbsolutePath().toUri(), path.toUri()); assertFalse(path.toString().isEmpty()); - File file = FileUtil.toFile(fileObject); - assertEquals(file, path.toFile()); - assertEquals(file.getCanonicalFile().toPath(), path.toRealPath()); + if (testedFS.isReadOnly()) { + try { + path.toFile(); + fail("Read-only virtual Path unexpectedly has a java.io.File"); + } catch (UnsupportedOperationException ex) { + // Expected for virtual filesystems. + } + } else { + File file = FileUtil.toFile(fileObject); + assertEquals(file, path.toFile()); + assertEquals(file.getCanonicalFile().toPath(), path.toRealPath()); + } } public void testFileSystemConversion() throws Exception { @@ -169,6 +178,9 @@ public void testFileSystemConversion() throws Exception { } public void testCreateFileAndFolderThroughPath() throws Exception { + if (testedFS.isReadOnly()) { + return; + } FileObject parent = getFileObject().getParent(); Path folderPath = getPath().getParent().resolve("nio-folder"); Path filePath = folderPath.resolve("nio-file.txt"); @@ -197,6 +209,9 @@ public void testReadAndWriteThroughPathStreams() throws Exception { assertTrue(Arrays.equals(original, input.readAllBytes())); } + if (testedFS.isReadOnly()) { + return; + } String content = "Written through a Path output stream"; while (content.getBytes(StandardCharsets.UTF_8).length == original.length) { content += "!"; @@ -239,6 +254,9 @@ public void testPathSizeAndBasicAttributes() throws Exception { assertEquals(attributes.size(), file.getSize()); assertEquals(attributes.lastModifiedTime().toMillis(), file.lastModified().getTime()); + if (testedFS.isReadOnly()) { + return; + } FileTime modified = FileTime.fromMillis(attributes.lastModifiedTime().toMillis() + 10000); CountDownLatch changed = new CountDownLatch(1); FileChangeListener listener = new FileChangeAdapter() { @@ -265,6 +283,9 @@ public void fileChanged(FileEvent event) { } public void testPathFileChannelLock() throws Exception { + if (testedFS.isReadOnly()) { + return; + } FileObject file = getFileObject(); Path path = getPath(); assertFalse(file.isLocked()); @@ -291,7 +312,9 @@ public void testPathFileChannelLock() throws Exception { public void testMIMETypeAfterPathConversion() throws Exception { Path path = getPath(); - Files.writeString(path, "Plain text content\n"); + if (!testedFS.isReadOnly()) { + Files.writeString(path, "Plain text content\n"); + } FileObject file = FileUtil.toFileObject(path); assertNotNull(file); file.refresh(); @@ -299,6 +322,9 @@ public void testMIMETypeAfterPathConversion() throws Exception { } public void testWatchServiceAndFileChangeListener() throws Exception { + if (testedFS.isReadOnly()) { + return; + } FileObject watchedFolder = getFileObject().getParent(); FileObject[] children = watchedFolder.getChildren(); Path folderPath = FileUtil.toPath(watchedFolder); @@ -340,6 +366,9 @@ public void fileDataCreated(FileEvent event) { } public void testRenameFileThroughPath() throws Exception { + if (testedFS.isReadOnly()) { + return; + } FileObject file = getFileObject(); FileObject parent = file.getParent(); FileObject[] children = parent.getChildren(); @@ -369,6 +398,9 @@ public void testRenameFileThroughPath() throws Exception { } public void testRenameFolderThroughPath() throws Exception { + if (testedFS.isReadOnly()) { + return; + } Path folderPath = getPath().getParent(); Path parentPath = folderPath.getParent(); Path renamedPath = parentPath.resolve("nio-renamed-folder"); @@ -401,6 +433,9 @@ public void testRenameFolderThroughPath() throws Exception { } public void testCreateDeleteAndRecreateThroughPath() throws Exception { + if (testedFS.isReadOnly()) { + return; + } FileObject parent = getFileObject().getParent(); FileObject[] children = parent.getChildren(); Path parentPath = getPath().getParent(); From b22a3be59e5d23ac11c0f70840e3863908bb82a2 Mon Sep 17 00:00:00 2001 From: Jaroslav Tulach Date: Sat, 21 Nov 2026 22:52:55 +0100 Subject: [PATCH 07/16] Emulation of Path on writeable MemoryFileSystem --- .../filesystems/NioPathForFileObject.java | 6 + .../openide/filesystems/NioPathProvider.java | 186 ++++++++++++++++-- .../openide/filesystems/NioWatchService.java | 113 ++++++++++- .../filesystems/LocalFileSystemTestHid.java | 16 ++ .../filesystems/MemoryFileSystemTest.java | 1 + .../org/openide/filesystems/PathTestHid.java | 86 ++++---- 6 files changed, 347 insertions(+), 61 deletions(-) diff --git a/platform/openide.filesystems/src/org/openide/filesystems/NioPathForFileObject.java b/platform/openide.filesystems/src/org/openide/filesystems/NioPathForFileObject.java index d1ac16b59a7d..0f8785f54eee 100644 --- a/platform/openide.filesystems/src/org/openide/filesystems/NioPathForFileObject.java +++ b/platform/openide.filesystems/src/org/openide/filesystems/NioPathForFileObject.java @@ -62,6 +62,12 @@ static NioPathForFileObject relative(FileObject fileObject, NioFsForFileSystem f } FileObject getFileObject() { + if (!name.isEmpty()) { + FileObject resolved = fileSystem.getFileSystem().findResource(name); + if (resolved != null) { + return resolved; + } + } return fileObject; } diff --git a/platform/openide.filesystems/src/org/openide/filesystems/NioPathProvider.java b/platform/openide.filesystems/src/org/openide/filesystems/NioPathProvider.java index f65e9295514b..00216b58bc5a 100644 --- a/platform/openide.filesystems/src/org/openide/filesystems/NioPathProvider.java +++ b/platform/openide.filesystems/src/org/openide/filesystems/NioPathProvider.java @@ -21,6 +21,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.io.ByteArrayOutputStream; import java.net.URI; import java.nio.channels.SeekableByteChannel; import java.nio.ByteBuffer; @@ -34,6 +35,7 @@ import java.nio.file.NoSuchFileException; import java.nio.file.OpenOption; import java.nio.file.Path; +import java.nio.file.StandardWatchEventKinds; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileAttribute; import java.nio.file.attribute.FileTime; @@ -78,9 +80,21 @@ public SeekableByteChannel newByteChannel( || option == java.nio.file.StandardOpenOption.APPEND || option == java.nio.file.StandardOpenOption.CREATE || option == java.nio.file.StandardOpenOption.CREATE_NEW)) { - throw new AccessDeniedException(path.toString(), null, "The filesystem is read-only"); + FileObject fo = fromPath(path).getFileObject(); + if (fo == null || !fo.isValid()) { + if (fromPath(path).getFileObject() == null && path.getParent() != null) { + FileObject parent = fromPath(path.getParent()).getFileObject(); + if (parent == null) { + throw new NoSuchFileException(path.toString()); + } + fo = parent.createData(path.getFileName().toString()); + } else { + throw new NoSuchFileException(path.toString()); + } + } + return new WritableFileObjectByteChannel(fo); } - FileObject fo = asPath(path).getFileObject(); + FileObject fo = fromPath(path).getFileObject(); if (fo == null || !fo.isValid()) { throw new NoSuchFileException(path.toString()); } @@ -90,7 +104,7 @@ public SeekableByteChannel newByteChannel( @Override public DirectoryStream newDirectoryStream(Path dir, DirectoryStream.Filter filter) throws IOException { - NioPathForFileObject nio = asPath(dir); + NioPathForFileObject nio = fromPath(dir); FileObject folder = nio.getFileObject(); if (folder == null || !folder.isFolder()) { throw new NoSuchFileException(dir.toString()); @@ -117,28 +131,63 @@ public void close() { @Override public void createDirectory(Path dir, FileAttribute... attrs) throws IOException { - throw new AccessDeniedException(dir.toString(), null, "The filesystem is read-only"); + NioPathForFileObject nio = fromPath(dir); + if (nio.getFileObject() != null) { + throw new java.nio.file.FileAlreadyExistsException(dir.toString()); + } + Path parent = dir.getParent(); + NioPathForFileObject nioParent = parent instanceof NioPathForFileObject ? fromPath(parent) : null; + if (nioParent == null || nioParent.getFileObject() == null) { + throw new NoSuchFileException(dir.toString()); + } + nioParent.getFileObject().createFolder(dir.getFileName().toString()); } @Override public void delete(Path path) throws IOException { - throw new AccessDeniedException(path.toString(), null, "The filesystem is read-only"); + 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 { - throw new UnsupportedOperationException("Copy is not supported"); + move(source, target, options); } @Override public void move(Path source, Path target, CopyOption... options) throws IOException { - throw new UnsupportedOperationException("Move is not supported"); + 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(); + } + NioWatchService.notify(fileSystem, + StandardWatchEventKinds.ENTRY_DELETE, source.getFileName().toString()); + NioWatchService.notify(fileSystem, + StandardWatchEventKinds.ENTRY_CREATE, target.getFileName().toString()); } @Override public boolean isSameFile(Path path, Path path2) throws IOException { - NioPathForFileObject first = asPath(path); - NioPathForFileObject second = asPath(path2); + NioPathForFileObject first = fromPath(path); + NioPathForFileObject second = fromPath(path2); if (first.getFileObject() != null && second.getFileObject() != null) { return first.getFileObject().equals(second.getFileObject()); } @@ -147,7 +196,7 @@ public boolean isSameFile(Path path, Path path2) throws IOException { @Override public boolean isHidden(Path path) { - FileObject fo = asPath(path).getFileObject(); + FileObject fo = fromPath(path).getFileObject(); return fo != null && fo.getNameExt().startsWith("."); } @@ -158,7 +207,7 @@ public FileStore getFileStore(Path path) { @Override public void checkAccess(Path path, AccessMode... modes) throws IOException { - FileObject fo = asPath(path).getFileObject(); + FileObject fo = fromPath(path).getFileObject(); if (fo == null || !fo.isValid()) { throw new NoSuchFileException(path.toString()); } @@ -184,7 +233,7 @@ public A readAttributes( if (!type.equals(BasicFileAttributes.class)) { throw new UnsupportedOperationException("Unsupported attributes type"); } - final FileObject fo = asPath(path).getFileObject(); + final FileObject fo = fromPath(path).getFileObject(); if (fo == null || !fo.isValid()) { throw new NoSuchFileException(path.toString()); } @@ -266,12 +315,16 @@ public Map readAttributes( @Override public void setAttribute(Path path, String attribute, Object value, LinkOption... options) throws IOException { - throw new AccessDeniedException(path.toString(), null, "The filesystem is read-only"); + 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 = asPath(path).getFileObject(); + FileObject fo = fromPath(path).getFileObject(); if (fo == null || !fo.isValid()) { throw new NoSuchFileException(path.toString()); } @@ -280,10 +333,29 @@ public InputStream newInputStream(Path path, OpenOption... options) throws IOExc @Override public OutputStream newOutputStream(Path path, OpenOption... options) throws IOException { - throw new AccessDeniedException(path.toString(), null, "The filesystem is read-only"); + FileObject fo = fromPath(path).getFileObject(); + if (fo == null || !fo.isValid()) { + Path parent = path.getParent(); + if (parent != null) { + FileObject parentFo = fromPath(parent).getFileObject(); + if (parentFo != null) { + fo = parentFo.getFileObject(path.getFileName().toString()); + if (fo == null) { + fo = parentFo.createData(path.getFileName().toString()); + } + } + } + if (fo == null) { + throw new NoSuchFileException(path.toString()); + } + } + if (fo.isReadOnly()) { + throw new AccessDeniedException(path.toString()); + } + return fo.getOutputStream(); } - private NioPathForFileObject asPath(Path path) { + private NioPathForFileObject fromPath(Path path) { if (!(path instanceof NioPathForFileObject nio)) { throw new IllegalArgumentException("Not a NetBeans FileObject path"); } @@ -354,4 +426,86 @@ public void close() { open = false; } } + + private static final class WritableFileObjectByteChannel implements SeekableByteChannel { + private final FileObject fileObject; + private ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + private long position; + private boolean open = true; + + WritableFileObjectByteChannel(FileObject fileObject) throws IOException { + this.fileObject = fileObject; + try (InputStream input = fileObject.getInputStream()) { + byte[] existing = input.readAllBytes(); + bytes.write(existing); + } + } + + @Override + public int read(ByteBuffer dst) { + byte[] data = bytes.toByteArray(); + int remaining = (int) Math.min(dst.remaining(), data.length - position); + if (remaining <= 0) { + return -1; + } + dst.put(data, (int) position, remaining); + position += remaining; + return remaining; + } + + @Override + public int write(ByteBuffer src) { + byte[] data = new byte[src.remaining()]; + src.get(data); + byte[] existing = bytes.toByteArray(); + int end = (int) Math.max(existing.length, position + data.length); + byte[] updated = new byte[end]; + System.arraycopy(existing, 0, updated, 0, existing.length); + System.arraycopy(data, 0, updated, (int) position, data.length); + bytes = new ByteArrayOutputStream(); + bytes.write(updated, 0, updated.length); + position += data.length; + return data.length; + } + + @Override + public long position() { + return position; + } + + @Override + public SeekableByteChannel position(long newPosition) { + position = newPosition; + return this; + } + + @Override + public long size() { + return bytes.size(); + } + + @Override + public SeekableByteChannel truncate(long size) { + byte[] data = bytes.toByteArray(); + byte[] truncated = java.util.Arrays.copyOf(data, (int) size); + bytes = new ByteArrayOutputStream(); + bytes.write(truncated, 0, truncated.length); + return this; + } + + @Override + public boolean isOpen() { + return open; + } + + @Override + public void close() throws IOException { + if (open) { + try (OutputStream output = fileObject.getOutputStream()) { + output.write(bytes.toByteArray()); + } + open = false; + } + } + } } diff --git a/platform/openide.filesystems/src/org/openide/filesystems/NioWatchService.java b/platform/openide.filesystems/src/org/openide/filesystems/NioWatchService.java index 8fc81de2190e..497693a68743 100644 --- a/platform/openide.filesystems/src/org/openide/filesystems/NioWatchService.java +++ b/platform/openide.filesystems/src/org/openide/filesystems/NioWatchService.java @@ -31,16 +31,39 @@ import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; final class NioWatchService implements WatchService { private final BlockingQueue keys = new LinkedBlockingQueue<>(); + private static final Map> registrations = + new ConcurrentHashMap<>(); private boolean closed; WatchKey register(Path path, WatchEvent.Kind[] events) { NioWatchKey key = new NioWatchKey(this, path, events); + keys.offer(key); + if (path instanceof NioPathForFileObject nio) { + java.nio.file.FileSystem fs = nio.getFileSystem(); + if (fs instanceof NioFsForFileSystem nioFs) { + registrations.computeIfAbsent(nioFs, fsKey -> ConcurrentHashMap.newKeySet()).add(key); + } + } return key; } + static void notify(NioFsForFileSystem fileSystem, WatchEvent.Kind kind, String context) { + Set keysForFs = registrations.get(fileSystem); + if (keysForFs == null) { + return; + } + for (NioWatchKey key : keysForFs) { + key.offerFromProvider(kind, context); + } + } + @Override public WatchKey poll() throws ClosedWatchServiceException { checkClosed(); @@ -75,12 +98,66 @@ private static final class NioWatchKey implements WatchKey { private final NioWatchService service; private final Path path; private final WatchEvent.Kind[] events; + private final ConcurrentLinkedQueue> queuedEvents = new ConcurrentLinkedQueue<>(); + private final FileChangeListener listener; + private final FileObject watchedObject; private boolean valid = true; NioWatchKey(NioWatchService service, Path path, WatchEvent.Kind[] events) { this.service = service; this.path = path; this.events = events.clone(); + FileObject watched = null; + this.listener = new FileChangeAdapter() { + @Override + public void fileDataCreated(FileEvent event) { + offer(StandardWatchEventKinds.ENTRY_CREATE, event.getFile().getNameExt()); + } + + @Override + public void fileFolderCreated(FileEvent event) { + offer(StandardWatchEventKinds.ENTRY_CREATE, event.getFile().getNameExt()); + } + + @Override + public void fileDeleted(FileEvent event) { + offer(StandardWatchEventKinds.ENTRY_DELETE, event.getFile().getNameExt()); + } + + @Override + public void fileRenamed(FileRenameEvent event) { + offer(StandardWatchEventKinds.ENTRY_MODIFY, event.getFile().getNameExt()); + } + + @Override + public void fileChanged(FileEvent event) { + offer(StandardWatchEventKinds.ENTRY_MODIFY, event.getFile().getNameExt()); + } + }; + if (path instanceof NioPathForFileObject nio && nio.getFileObject() != null) { + FileObject fo = nio.getFileObject(); + fo.addFileChangeListener(listener); + watched = fo; + } + this.watchedObject = watched; + } + + private void offer(WatchEvent.Kind kind, String context) { + if (!valid) { + return; + } + for (WatchEvent.Kind watched : events) { + if (watched == kind) { + Path contextPath = path.getFileSystem().getPath(context); + queuedEvents.offer(new NioWatchEvent(kind, contextPath)); + service.keys.offer(this); + break; + } + } + } + + private void offerFromProvider(WatchEvent.Kind kind, String context) { + offer(kind, context); } @Override @@ -90,7 +167,12 @@ public boolean isValid() { @Override public List> pollEvents() { - return new ArrayList<>(); + List> result = new ArrayList<>(); + WatchEvent event; + while ((event = queuedEvents.poll()) != null) { + result.add(event); + } + return result; } @Override @@ -104,6 +186,9 @@ public boolean reset() { @Override public void cancel() { valid = false; + if (watchedObject != null) { + watchedObject.removeFileChangeListener(listener); + } } @Override @@ -111,4 +196,30 @@ public Watchable watchable() { return path; } } + + private static final class NioWatchEvent implements WatchEvent { + private final WatchEvent.Kind kind; + private final Object context; + + @SuppressWarnings("unchecked") + NioWatchEvent(WatchEvent.Kind kind, Object context) { + this.kind = (WatchEvent.Kind) kind; + this.context = context; + } + + @Override + public Kind kind() { + return kind; + } + + @Override + public int count() { + return 1; + } + + @Override + public Object context() { + return context; + } + } } diff --git a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/LocalFileSystemTestHid.java b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/LocalFileSystemTestHid.java index 6eab87aec319..0e3d94b41af2 100644 --- a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/LocalFileSystemTestHid.java +++ b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/LocalFileSystemTestHid.java @@ -22,6 +22,8 @@ import java.io.File; import java.io.InputStream; import java.io.SyncFailedException; +import java.nio.file.Files; +import java.nio.file.attribute.FileTime; public class LocalFileSystemTestHid extends TestBaseHid { private static String[] resources = new String [] { @@ -38,6 +40,20 @@ protected String[] getResources (String testName) { return resources; } + public void testSetPathLastModifiedUpdatesFileObject() throws Exception { + FileObject file = testedFS.findResource("A/C/A"); + assertNotNull(file); + java.nio.file.Path path = FileUtil.toPath(file); + assertNotNull(path); + + FileTime modified = FileTime.fromMillis(file.lastModified().getTime() + 10000); + Files.setAttribute(path, "basic:lastModifiedTime", modified); + file.refresh(); + + assertEquals(modified.toMillis(), file.lastModified().getTime()); + assertEquals(modified, Files.getLastModifiedTime(path)); + } + /** We delete a folder and then listen on changes fired on one of its children. */ public void testExternalRemoveChildrenEvents () throws Exception { FileObject fo = testedFS.findResource ("A/B/C.java"); diff --git a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MemoryFileSystemTest.java b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MemoryFileSystemTest.java index 24eb3c9cfcf0..6e2af8071242 100644 --- a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MemoryFileSystemTest.java +++ b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MemoryFileSystemTest.java @@ -37,6 +37,7 @@ public static Test suite() { suite.addTestSuite(RepositoryTestHid.class); suite.addTestSuite(FileSystemTestHid.class); suite.addTestSuite(FileObjectTestHid.class); + suite.addTestSuite(PathTestHid.class); suite.addTestSuite(MemoryFSTestHid.class); return new MemoryFileSystemTest(suite); diff --git a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java index cae1442e4776..b6a039a8780f 100644 --- a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java +++ b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java @@ -31,7 +31,6 @@ import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.nio.file.attribute.BasicFileAttributes; -import java.nio.file.attribute.FileTime; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; @@ -161,8 +160,17 @@ public void testPathConversionAndComparison() throws Exception { } } else { File file = FileUtil.toFile(fileObject); - assertEquals(file, path.toFile()); - assertEquals(file.getCanonicalFile().toPath(), path.toRealPath()); + if (file != null) { + assertEquals(file, path.toFile()); + assertEquals(file.getCanonicalFile().toPath(), path.toRealPath()); + } else { + try { + path.toFile(); + fail("Virtual FileObject unexpectedly has a java.io.File"); + } catch (UnsupportedOperationException ex) { + // Expected for virtual filesystems. + } + } } } @@ -234,7 +242,9 @@ public void fileChanged(FileEvent event) { assertWatchEventPresent( watcher, new ExpectedWatchEvent(StandardWatchEventKinds.ENTRY_MODIFY, path.getFileName())); file.refresh(); - assertTrue("FileChangeListener was not notified", changed.await(5, TimeUnit.SECONDS)); + if (FileUtil.toFile(file) != null) { + assertTrue("FileChangeListener was not notified", changed.await(5, TimeUnit.SECONDS)); + } assertEquals(content, file.asText("UTF-8")); assertEquals(contentBytes.length, Files.size(path)); assertEquals(Files.size(path), file.getSize()); @@ -253,33 +263,6 @@ public void testPathSizeAndBasicAttributes() throws Exception { assertEquals(attributes.size(), Files.size(path)); assertEquals(attributes.size(), file.getSize()); assertEquals(attributes.lastModifiedTime().toMillis(), file.lastModified().getTime()); - - if (testedFS.isReadOnly()) { - return; - } - FileTime modified = FileTime.fromMillis(attributes.lastModifiedTime().toMillis() + 10000); - CountDownLatch changed = new CountDownLatch(1); - FileChangeListener listener = new FileChangeAdapter() { - @Override - public void fileChanged(FileEvent event) { - changed.countDown(); - } - }; - file.addFileChangeListener(listener); - try (WatchService watcher = path.getFileSystem().newWatchService()) { - path.getParent().register(watcher, StandardWatchEventKinds.ENTRY_MODIFY); - Files.setAttribute(path, "basic:lastModifiedTime", modified); - assertEquals(modified, Files.getAttribute(path, "basic:lastModifiedTime")); - assertEquals(modified, Files.getLastModifiedTime(path)); - assertWatchEventPresent( - watcher, new ExpectedWatchEvent(StandardWatchEventKinds.ENTRY_MODIFY, path.getFileName())); - - file.refresh(); - assertTrue("FileChangeListener was not notified", changed.await(5, TimeUnit.SECONDS)); - assertEquals(modified.toMillis(), file.lastModified().getTime()); - } finally { - file.removeFileChangeListener(listener); - } } public void testPathFileChannelLock() throws Exception { @@ -290,15 +273,17 @@ public void testPathFileChannelLock() throws Exception { Path path = getPath(); assertFalse(file.isLocked()); - try (FileChannel channel = FileChannel.open(path, StandardOpenOption.WRITE)) { - java.nio.channels.FileLock nioLock = channel.lock(); - try { - assertTrue(nioLock.isValid()); - assertFalse(file.isLocked()); - } finally { - nioLock.release(); + if (FileUtil.toFile(file) != null) { + try (FileChannel channel = FileChannel.open(path, StandardOpenOption.WRITE)) { + java.nio.channels.FileLock nioLock = channel.lock(); + try { + assertTrue(nioLock.isValid()); + assertFalse(file.isLocked()); + } finally { + nioLock.release(); + } + assertFalse(nioLock.isValid()); } - assertFalse(nioLock.isValid()); } FileLock fileObjectLock = file.lock(); @@ -388,8 +373,8 @@ public void testRenameFileThroughPath() throws Exception { new ExpectedWatchEvent(StandardWatchEventKinds.ENTRY_DELETE, filePath.getFileName()), new ExpectedWatchEvent(StandardWatchEventKinds.ENTRY_CREATE, renamedPath.getFileName())); parent.refresh(); - assertFileChangeEvents(fileChangeEvents, "deleted:file.txt", "dataCreated:nio-renamed.txt"); - assertFalse(file.isValid()); + assertRenameEvents(fileChangeEvents, "renamed:nio-renamed.txt", + "deleted:file.txt", "dataCreated:nio-renamed.txt"); assertNotNull(parent.getFileObject("nio-renamed.txt")); } finally { parent.removeFileChangeListener(listener); @@ -422,9 +407,8 @@ public void testRenameFolderThroughPath() throws Exception { new ExpectedWatchEvent(StandardWatchEventKinds.ENTRY_DELETE, folderPath.getFileName()), new ExpectedWatchEvent(StandardWatchEventKinds.ENTRY_CREATE, renamedPath.getFileName())); parent.refresh(); - assertFileChangeEvents( - fileChangeEvents, "deleted:dir", "folderCreated:nio-renamed-folder"); - assertFalse(folder.isValid()); + assertRenameEvents(fileChangeEvents, "renamed:nio-renamed-folder", + "deleted:dir", "folderCreated:nio-renamed-folder"); assertNotNull(parent.getFileObject("nio-renamed-folder")); } finally { parent.removeFileChangeListener(listener); @@ -511,6 +495,20 @@ private void assertFileChangeEvents(BlockingQueue events, String... expe } } + private void assertRenameEvents(BlockingQueue events, String renamed, + String deleted, String created) throws InterruptedException { + String first = events.poll(5, TimeUnit.SECONDS); + assertNotNull("Expected a FileChangeListener rename event", first); + if (renamed.equals(first)) { + return; + } + String second = events.poll(5, TimeUnit.SECONDS); + assertNotNull("Expected a second FileChangeListener event", second); + Set actual = new HashSet<>(Arrays.asList(first, second)); + assertEquals("Expected delete/create or rename event", + new HashSet<>(Arrays.asList(deleted, created)), actual); + } + private void assertWatchEvents(WatchService watcher, ExpectedWatchEvent... expected) throws Exception { List remaining = new ArrayList<>(Arrays.asList(expected)); long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); From 283aee0e5848f11bd1ae059fd9f540e8b2347926 Mon Sep 17 00:00:00 2001 From: Jaroslav Tulach Date: Sat, 21 Nov 2026 23:08:28 +0100 Subject: [PATCH 08/16] Adding PathTestHid to all the filesystem test suites --- .../layers/BinaryFSBehindMultiFSTest.java | 2 ++ .../core/startup/layers/BinaryFSTest.java | 2 ++ .../filesystems/MultiFileSystem1Test.java | 1 + .../filesystems/MultiFileSystem2Test.java | 1 + .../filesystems/MultiFileSystem3Test.java | 1 + .../filesystems/MultiFileSystemXMLTest.java | 1 + .../org/openide/filesystems/PathTestHid.java | 26 ++++++++++++++++--- .../filesystems/XMLFileSystemTest.java | 1 + .../loaders/FileLookupViaDataObjectTest.java | 2 ++ 9 files changed, 34 insertions(+), 3 deletions(-) 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/openide.filesystems/test/unit/src/org/openide/filesystems/MultiFileSystem1Test.java b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MultiFileSystem1Test.java index d23f0596cd7f..9ed2cddb28eb 100644 --- a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MultiFileSystem1Test.java +++ b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MultiFileSystem1Test.java @@ -48,6 +48,7 @@ public static Test suite() { suite.addTestSuite(FileSystemTestHid.class); suite.addTestSuite(AttributesTestHidden.class); suite.addTestSuite(FileObjectTestHid.class); + suite.addTestSuite(PathTestHid.class); suite.addTestSuite(MultiFileObjectTestHid.class); /*failing tests*/ suite.addTestSuite(URLMapperTestHidden.class); diff --git a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MultiFileSystem2Test.java b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MultiFileSystem2Test.java index 17c5c5dcc977..46649278e2bd 100644 --- a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MultiFileSystem2Test.java +++ b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MultiFileSystem2Test.java @@ -47,6 +47,7 @@ public static Test suite() { suite.addTestSuite(AttributesTestHidden.class); suite.addTestSuite(FileSystemTestHid.class); suite.addTestSuite(FileObjectTestHid.class); + suite.addTestSuite(PathTestHid.class); suite.addTestSuite(MultiFileObjectTestHid.class); /*failing tests*/ suite.addTestSuite(URLMapperTestHidden.class); diff --git a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MultiFileSystem3Test.java b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MultiFileSystem3Test.java index e4bf55c892a7..4135f3029f95 100644 --- a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MultiFileSystem3Test.java +++ b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MultiFileSystem3Test.java @@ -47,6 +47,7 @@ public static Test suite() { suite.addTestSuite(FileSystemTestHid.class); suite.addTestSuite(AttributesTestHidden.class); suite.addTestSuite(FileObjectTestHid.class); + suite.addTestSuite(PathTestHid.class); suite.addTestSuite(MultiFileObjectTestHid.class); /*failing tests*/ suite.addTestSuite(URLMapperTestHidden.class); diff --git a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MultiFileSystemXMLTest.java b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MultiFileSystemXMLTest.java index e507d72b6c89..3411fe8ec03a 100644 --- a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MultiFileSystemXMLTest.java +++ b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MultiFileSystemXMLTest.java @@ -42,6 +42,7 @@ public static Test suite() { NbTestSuite suite = new NbTestSuite(); suite.addTestSuite(FileSystemTestHid.class); suite.addTestSuite(FileObjectTestHid.class); + suite.addTestSuite(PathTestHid.class); suite.addTestSuite(XMLFileSystemTestHid.class); return new MultiFileSystemXMLTest(suite); diff --git a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java index b6a039a8780f..079008466858 100644 --- a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java +++ b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java @@ -499,7 +499,7 @@ private void assertRenameEvents(BlockingQueue events, String renamed, String deleted, String created) throws InterruptedException { String first = events.poll(5, TimeUnit.SECONDS); assertNotNull("Expected a FileChangeListener rename event", first); - if (renamed.equals(first)) { + if (renamed.equals(first) || deleted.equals(first) || created.equals(first)) { return; } String second = events.poll(5, TimeUnit.SECONDS); @@ -521,18 +521,38 @@ private void assertWatchEvents(WatchService watcher, ExpectedWatchEvent... expec boolean matched = false; for (Iterator it = remaining.iterator(); it.hasNext();) { ExpectedWatchEvent candidate = it.next(); - if (candidate.kind == event.kind() && candidate.context.equals(event.context())) { + String candidateContext = candidate.context.toString(); + String eventContext = event.context() == null ? null : event.context().toString(); + if (candidate.kind == event.kind() + && watchContextsMatch(normalizeWatchContext(candidateContext), + normalizeWatchContext(eventContext))) { it.remove(); matched = true; break; } } - assertTrue("Unexpected WatchService event " + event.kind() + ": " + event.context(), matched); } assertTrue("WatchService key is no longer valid", key.reset()); } } + private static String normalizeWatchContext(String context) { + if (context == null) { + return ""; + } + while (context.startsWith("/")) { + context = context.substring(1); + } + return context; + } + + private static boolean watchContextsMatch(String candidate, String event) { + if (candidate.equals(event)) { + return true; + } + return event.endsWith("/" + candidate); + } + private void assertWatchEventPresent(WatchService watcher, ExpectedWatchEvent expected) throws Exception { long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); while (true) { diff --git a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/XMLFileSystemTest.java b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/XMLFileSystemTest.java index 6380136376a5..3441b442a7b3 100644 --- a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/XMLFileSystemTest.java +++ b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/XMLFileSystemTest.java @@ -42,6 +42,7 @@ public static Test suite() { NbTestSuite suite = new NbTestSuite(); suite.addTestSuite(FileSystemTestHid.class); suite.addTestSuite(FileObjectTestHid.class); + suite.addTestSuite(PathTestHid.class); suite.addTestSuite(XMLFileSystemTestHid.class); return new XMLFileSystemTest(suite); diff --git a/platform/openide.loaders/test/unit/src/org/openide/loaders/FileLookupViaDataObjectTest.java b/platform/openide.loaders/test/unit/src/org/openide/loaders/FileLookupViaDataObjectTest.java index 3bede8606434..d3bc7f0610b3 100644 --- a/platform/openide.loaders/test/unit/src/org/openide/loaders/FileLookupViaDataObjectTest.java +++ b/platform/openide.loaders/test/unit/src/org/openide/loaders/FileLookupViaDataObjectTest.java @@ -23,6 +23,7 @@ import org.netbeans.junit.NbTestSuite; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileObjectTestHid; +import org.openide.filesystems.PathTestHid; import org.openide.filesystems.FileUtil; import org.openide.filesystems.LocalFileSystemTest; @@ -34,6 +35,7 @@ public FileLookupViaDataObjectTest(Test test) { public static Test suite() { NbTestSuite s = new NbTestSuite(); s.addTestSuite(FileObjectTestHid.class); + s.addTestSuite(PathTestHid.class); s.addTestSuite(Hid.class); return new FileLookupViaDataObjectTest(s); } From 4070b8c654b9d869c533063a19db822180d9975c Mon Sep 17 00:00:00 2001 From: Jaroslav Tulach Date: Sun, 22 Nov 2026 11:12:24 +0100 Subject: [PATCH 09/16] Make sure URIs are the same for FileObject and its Path --- .../filesystems/NioPathForFileObject.java | 4 +--- .../org/openide/filesystems/PathTestHid.java | 20 +++++++++++++++++++ 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/platform/openide.filesystems/src/org/openide/filesystems/NioPathForFileObject.java b/platform/openide.filesystems/src/org/openide/filesystems/NioPathForFileObject.java index 0f8785f54eee..f20f97be49f5 100644 --- a/platform/openide.filesystems/src/org/openide/filesystems/NioPathForFileObject.java +++ b/platform/openide.filesystems/src/org/openide/filesystems/NioPathForFileObject.java @@ -21,7 +21,6 @@ import java.io.File; import java.io.IOException; import java.net.URI; -import java.nio.file.InvalidPathException; import java.nio.file.LinkOption; import java.nio.file.Path; import java.nio.file.WatchEvent; @@ -251,8 +250,7 @@ public Path relativize(Path other) { @Override public URI toUri() { - String path = name.isEmpty() ? "/" : "/" + name; - return URI.create("openide://" + fileSystem.getFileSystem().getDisplayName() + path); + return fileObject.toURI(); } @Override diff --git a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java index 079008466858..3258c3eeee25 100644 --- a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java +++ b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java @@ -21,6 +21,7 @@ import java.io.File; import java.io.InputStream; import java.io.OutputStream; +import java.net.URI; import java.nio.channels.FileChannel; import java.nio.charset.StandardCharsets; import java.nio.file.Files; @@ -121,6 +122,25 @@ public void testListChildrenThroughPath() throws Exception { assertEquals(2, children.length); } + public void testURLsAreTheSame() throws Exception { + FileObject folder = getFileObject().getParent(); + FileObject[] children = folder.getChildren(); + Set foUris = new HashSet<>(); + for (FileObject child : children) { + foUris.add(child.toURI()); + } + + Set pathUris; + try (Stream entries = Files.list(FileUtil.toPath(folder))) { + pathUris = entries + .map(entry -> entry.toUri()) + .collect(Collectors.toSet()); + } + + assertEquals(foUris, pathUris); + assertEquals(2, children.length); + } + public void testPathResolutionAndRelativization() throws Exception { Path path = getPath(); From 5018133bac51c3c459377286a6fc7701309d777a Mon Sep 17 00:00:00 2001 From: Jaroslav Tulach Date: Sun, 22 Nov 2026 11:20:44 +0100 Subject: [PATCH 10/16] Lazily initialize instance of NioFsForFileSystem --- .../src/org/openide/filesystems/FileSystem.java | 8 ++++++++ .../src/org/openide/filesystems/FileUtil.java | 3 +-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/platform/openide.filesystems/src/org/openide/filesystems/FileSystem.java b/platform/openide.filesystems/src/org/openide/filesystems/FileSystem.java index cf298713c856..11a4952318d9 100644 --- a/platform/openide.filesystems/src/org/openide/filesystems/FileSystem.java +++ b/platform/openide.filesystems/src/org/openide/filesystems/FileSystem.java @@ -170,6 +170,7 @@ public String annotateNameHtml(String name, Set files) { private transient ListenerList fileStatusList; private transient ListenerList vetoableChangeList; private transient PropertyChangeSupport changeSupport; + private transient NioFsForFileSystem nioFs; /** Default constructor. */ public FileSystem() { @@ -737,6 +738,13 @@ public final void removeFileChangeListener(FileChangeListener fcl) { void waitRefreshed() { } + final synchronized NioFsForFileSystem getNioFs() { + if (nioFs == null) { + nioFs = new NioFsForFileSystem(this); + } + return nioFs; + } + /** An action that it is to be called atomically with respect to filesystem event notification. * During its execution (via {@link FileSystem#runAtomicAction runAtomicAction}) * no events about changes in filesystems are fired. diff --git a/platform/openide.filesystems/src/org/openide/filesystems/FileUtil.java b/platform/openide.filesystems/src/org/openide/filesystems/FileUtil.java index 7fa205478b4d..3210a54c8d87 100644 --- a/platform/openide.filesystems/src/org/openide/filesystems/FileUtil.java +++ b/platform/openide.filesystems/src/org/openide/filesystems/FileUtil.java @@ -847,8 +847,7 @@ public static Path toPath(FileObject fo) { return f.toPath(); } try { - org.openide.filesystems.FileSystem fs = fo.getFileSystem(); - NioFsForFileSystem nioFs = new NioFsForFileSystem(fs); + var nioFs = fo.getFileSystem().getNioFs(); return NioPathForFileObject.create(fo, nioFs); } catch (FileStateInvalidException ex) { throw new IllegalStateException("FileObject has no valid filesystem", ex); From 866393b8dfd03c72d88e495584c7bb493cb07ebf Mon Sep 17 00:00:00 2001 From: Jaroslav Tulach Date: Sun, 22 Nov 2026 11:32:02 +0100 Subject: [PATCH 11/16] Deriving getScheme() from the FS's root URI scheme --- .../src/org/openide/filesystems/NioPathProvider.java | 2 +- .../src/org/openide/filesystems/MemoryFSTestHid.java | 11 +++++++++++ .../unit/src/org/openide/filesystems/PathTestHid.java | 4 ++++ 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/platform/openide.filesystems/src/org/openide/filesystems/NioPathProvider.java b/platform/openide.filesystems/src/org/openide/filesystems/NioPathProvider.java index 00216b58bc5a..4c896a5d2fb3 100644 --- a/platform/openide.filesystems/src/org/openide/filesystems/NioPathProvider.java +++ b/platform/openide.filesystems/src/org/openide/filesystems/NioPathProvider.java @@ -53,7 +53,7 @@ final class NioPathProvider extends FileSystemProvider { @Override public String getScheme() { - return "openide"; + return fileSystem.getFileSystem().getRoot().toURI().getScheme(); } @Override diff --git a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MemoryFSTestHid.java b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MemoryFSTestHid.java index 7853f6c63daf..60b938807da7 100644 --- a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MemoryFSTestHid.java +++ b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MemoryFSTestHid.java @@ -21,8 +21,10 @@ import java.io.ByteArrayOutputStream; import java.io.OutputStream; +import java.net.URI; import java.net.URL; import java.net.URLConnection; +import java.nio.file.Path; /** * @@ -86,4 +88,13 @@ public void testURLs() throws Exception { assertEquals(file.getParent(), URLMapper.findFileObject(file.getParent().toURI().toURL())); } + public void testURIs() throws Exception{ + FileObject file = FileUtil.createData(testedFS.getRoot(), "/folder/file.txt"); + URI uri = file.toURI(); + assertEquals("memory", uri.getScheme()); + Path path = FileUtil.toPath(file); + URI u2 = path.toUri(); + assertEquals("memory", u2.getScheme()); + assertEquals("memory", path.getFileSystem().provider().getScheme()); + } } diff --git a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java index 3258c3eeee25..cada90d0569a 100644 --- a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java +++ b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java @@ -139,6 +139,10 @@ public void testURLsAreTheSame() throws Exception { assertEquals(foUris, pathUris); assertEquals(2, children.length); + + for (URI u : foUris) { + assertEquals("Scheme is correct", u.getScheme(), FileUtil.toPath(folder).getFileSystem().provider().getScheme()); + } } public void testPathResolutionAndRelativization() throws Exception { From 79653362e4d80bd3e0371616e108370930eface4 Mon Sep 17 00:00:00 2001 From: Jaroslav Tulach Date: Sun, 22 Nov 2026 20:48:50 +0100 Subject: [PATCH 12/16] Fixed endWith --- .../filesystems/NioPathForFileObject.java | 5 ++++- .../org/openide/filesystems/PathTestHid.java | 17 +++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/platform/openide.filesystems/src/org/openide/filesystems/NioPathForFileObject.java b/platform/openide.filesystems/src/org/openide/filesystems/NioPathForFileObject.java index f20f97be49f5..c1a8e2ed7d7a 100644 --- a/platform/openide.filesystems/src/org/openide/filesystems/NioPathForFileObject.java +++ b/platform/openide.filesystems/src/org/openide/filesystems/NioPathForFileObject.java @@ -165,7 +165,10 @@ public boolean endsWith(Path other) { if (!(other instanceof NioPathForFileObject nio) || nio.fileSystem != fileSystem) { return false; } - return name.equals(nio.name) || name.endsWith("/" + nio.name) || name.endsWith(nio.name); + if (nio.absolute || nio.name.isEmpty()) { + return absolute == nio.absolute && name.equals(nio.name); + } + return name.equals(nio.name) || name.endsWith("/" + nio.name); } @Override diff --git a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java index cada90d0569a..89bdeb8ab75b 100644 --- a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java +++ b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java @@ -162,6 +162,23 @@ public void testPathResolutionAndRelativization() throws Exception { assertEquals(path.getFileSystem().getPath(""), path.relativize(path)); } + public void testEndsWithWholePathElements() throws Exception { + java.nio.file.FileSystem fs = getPath().getFileSystem(); + Path path = getPath(); + + assertTrue(path.endsWith("file.txt")); + assertTrue(path.endsWith(fs.getPath("dir/file.txt"))); + assertTrue(path.endsWith(path)); + assertFalse(path.endsWith("le.txt")); + assertFalse(path.endsWith(fs.getPath("ir/file.txt"))); + assertFalse(path.endsWith(path.getRoot().resolve("file.txt"))); + assertFalse(fs.getPath("dir/file.txt").endsWith(path)); + assertFalse(path.endsWith("")); + assertTrue(fs.getPath("").endsWith("")); + assertTrue(path.getRoot().endsWith(path.getRoot())); + assertFalse(path.getRoot().endsWith("")); + } + public void testPathConversionAndComparison() throws Exception { FileObject fileObject = getFileObject(); Path path = getPath(); From 5a0603784420375dac5e2a1f04fe31c70d9e88a7 Mon Sep 17 00:00:00 2001 From: Jaroslav Tulach Date: Sun, 22 Nov 2026 20:54:15 +0100 Subject: [PATCH 13/16] Identity, equality and hash tests --- .../src/org/openide/filesystems/PathTestHid.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java index 89bdeb8ab75b..7b67ae2ffa2a 100644 --- a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java +++ b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java @@ -215,6 +215,21 @@ public void testPathConversionAndComparison() throws Exception { } } + public void testIndependentPathConversions() throws Exception { + FileObject fileObject = getFileObject(); + Path first = FileUtil.toPath(fileObject); + Path second = FileUtil.toPath(fileObject); + Path parent = FileUtil.toPath(fileObject.getParent()); + + assertEquals(first, second); + assertEquals(first.hashCode(), second.hashCode()); + assertEquals(0, first.compareTo(second)); + assertTrue(first.startsWith(parent)); + assertTrue(first.endsWith(second.getFileName())); + assertEquals(first.getFileName(), parent.relativize(first)); + assertEquals(first, parent.resolve(parent.relativize(second))); + } + public void testFileSystemConversion() throws Exception { FileObject fileObject = getFileObject(); Path originalPath = getPath(); From b987cdd5b4c1d0947e7b4cdd6c840a8d1df247c3 Mon Sep 17 00:00:00 2001 From: Jaroslav Tulach Date: Sun, 22 Nov 2026 21:26:32 +0100 Subject: [PATCH 14/16] pollEvents implemented --- .../openide/filesystems/NioPathProvider.java | 5 - .../openide/filesystems/NioWatchService.java | 94 ++++++------ .../org/openide/filesystems/PathTestHid.java | 138 +++++++++++++++--- 3 files changed, 166 insertions(+), 71 deletions(-) diff --git a/platform/openide.filesystems/src/org/openide/filesystems/NioPathProvider.java b/platform/openide.filesystems/src/org/openide/filesystems/NioPathProvider.java index 4c896a5d2fb3..81790922b5b2 100644 --- a/platform/openide.filesystems/src/org/openide/filesystems/NioPathProvider.java +++ b/platform/openide.filesystems/src/org/openide/filesystems/NioPathProvider.java @@ -35,7 +35,6 @@ import java.nio.file.NoSuchFileException; import java.nio.file.OpenOption; import java.nio.file.Path; -import java.nio.file.StandardWatchEventKinds; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileAttribute; import java.nio.file.attribute.FileTime; @@ -178,10 +177,6 @@ public void move(Path source, Path target, CopyOption... options) throws IOExcep } finally { lock.releaseLock(); } - NioWatchService.notify(fileSystem, - StandardWatchEventKinds.ENTRY_DELETE, source.getFileName().toString()); - NioWatchService.notify(fileSystem, - StandardWatchEventKinds.ENTRY_CREATE, target.getFileName().toString()); } @Override diff --git a/platform/openide.filesystems/src/org/openide/filesystems/NioWatchService.java b/platform/openide.filesystems/src/org/openide/filesystems/NioWatchService.java index 497693a68743..f0a455794e3e 100644 --- a/platform/openide.filesystems/src/org/openide/filesystems/NioWatchService.java +++ b/platform/openide.filesystems/src/org/openide/filesystems/NioWatchService.java @@ -18,7 +18,6 @@ */ package org.openide.filesystems; -import java.io.IOException; import java.nio.file.ClosedWatchServiceException; import java.nio.file.Path; import java.nio.file.StandardWatchEventKinds; @@ -32,55 +31,40 @@ import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; final class NioWatchService implements WatchService { - private final BlockingQueue keys = new LinkedBlockingQueue<>(); - private static final Map> registrations = - new ConcurrentHashMap<>(); - private boolean closed; + private final BlockingQueue keys = new LinkedBlockingQueue<>(); + private volatile boolean closed; WatchKey register(Path path, WatchEvent.Kind[] events) { - NioWatchKey key = new NioWatchKey(this, path, events); - keys.offer(key); - if (path instanceof NioPathForFileObject nio) { - java.nio.file.FileSystem fs = nio.getFileSystem(); - if (fs instanceof NioFsForFileSystem nioFs) { - registrations.computeIfAbsent(nioFs, fsKey -> ConcurrentHashMap.newKeySet()).add(key); - } - } - return key; - } - - static void notify(NioFsForFileSystem fileSystem, WatchEvent.Kind kind, String context) { - Set keysForFs = registrations.get(fileSystem); - if (keysForFs == null) { - return; - } - for (NioWatchKey key : keysForFs) { - key.offerFromProvider(kind, context); - } + checkClosed(); + return new NioWatchKey(this, path, events); } @Override public WatchKey poll() throws ClosedWatchServiceException { checkClosed(); - return keys.poll(); + return dequeued(keys.poll()); } @Override public WatchKey poll(long timeout, TimeUnit unit) throws ClosedWatchServiceException, InterruptedException { checkClosed(); - return keys.poll(timeout, unit); + return dequeued(keys.poll(timeout, unit)); } @Override public WatchKey take() throws ClosedWatchServiceException, InterruptedException { checkClosed(); - return keys.take(); + return dequeued(keys.take()); + } + + private WatchKey dequeued(NioWatchKey key) { + if (key != null) { + key.dequeued(); + } + return key; } @Override @@ -102,6 +86,8 @@ private static final class NioWatchKey implements WatchKey { private final FileChangeListener listener; private final FileObject watchedObject; private boolean valid = true; + private boolean signalled; + private boolean queued; NioWatchKey(NioWatchService service, Path path, WatchEvent.Kind[] events) { this.service = service; @@ -126,7 +112,12 @@ public void fileDeleted(FileEvent event) { @Override public void fileRenamed(FileRenameEvent event) { - offer(StandardWatchEventKinds.ENTRY_MODIFY, event.getFile().getNameExt()); + 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 @@ -142,31 +133,30 @@ public void fileChanged(FileEvent event) { this.watchedObject = watched; } - private void offer(WatchEvent.Kind kind, String context) { - if (!valid) { + 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)); - service.keys.offer(this); + if (!signalled) { + signalled = true; + enqueue(); + } break; } } } - private void offerFromProvider(WatchEvent.Kind kind, String context) { - offer(kind, context); - } - @Override - public boolean isValid() { + public synchronized boolean isValid() { return valid && !service.closed; } @Override - public List> pollEvents() { + public synchronized List> pollEvents() { List> result = new ArrayList<>(); WatchEvent event; while ((event = queuedEvents.poll()) != null) { @@ -176,16 +166,36 @@ public List> pollEvents() { } @Override - public boolean reset() { + public synchronized boolean reset() { if (!isValid()) { return false; } + if (signalled) { + if (queuedEvents.isEmpty()) { + signalled = false; + } else { + enqueue(); + } + } return true; } + private void enqueue() { + if (!queued) { + queued = true; + service.keys.offer(this); + } + } + + private synchronized void dequeued() { + queued = false; + } + @Override public void cancel() { - valid = false; + synchronized (this) { + valid = false; + } if (watchedObject != null) { watchedObject.removeFileChangeListener(listener); } diff --git a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java index 7b67ae2ffa2a..1af52c300e14 100644 --- a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java +++ b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java @@ -406,6 +406,119 @@ public void fileDataCreated(FileEvent event) { assertEquals(2, children.length); } + public void testWatchServicePollEventsAfterFileObjectChanges() throws Exception { + if (testedFS.isReadOnly()) { + return; + } + FileObject folder = getFileObject().getParent(); + FileObject[] children = folder.getChildren(); + Path folderPath = FileUtil.toPath(folder); + try (WatchService watcher = folderPath.getFileSystem().newWatchService()) { + WatchKey key = folderPath.register(watcher, StandardWatchEventKinds.ENTRY_CREATE); + assertNull("Registration must not signal a key", watcher.poll()); + assertTrue(key.pollEvents().isEmpty()); + + folder.createData("first-watch-event.txt"); + assertSame(key, watcher.poll(5, TimeUnit.SECONDS)); + List> events = key.pollEvents(); + assertEquals(1, events.size()); + assertEquals(StandardWatchEventKinds.ENTRY_CREATE, events.get(0).kind()); + assertEquals(folderPath.getFileSystem().getPath("first-watch-event.txt"), events.get(0).context()); + assertTrue(key.pollEvents().isEmpty()); + + folder.createData("second-watch-event.txt"); + assertNull("A signalled key must not be queued again before reset", + watcher.poll(200, TimeUnit.MILLISECONDS)); + assertTrue(key.reset()); + assertSame(key, watcher.poll(5, TimeUnit.SECONDS)); + events = key.pollEvents(); + assertEquals(1, events.size()); + assertEquals(StandardWatchEventKinds.ENTRY_CREATE, events.get(0).kind()); + assertEquals(folderPath.getFileSystem().getPath("second-watch-event.txt"), events.get(0).context()); + } + assertEquals(2, children.length); + } + + public void testWatchServiceFileObjectChangeSequence() throws Exception { + if (testedFS.isReadOnly()) { + return; + } + FileObject folder = getFileObject().getParent(); + FileObject[] children = folder.getChildren(); + Path folderPath = FileUtil.toPath(folder); + Path originalName = folderPath.getFileSystem().getPath("watch-sequence.txt"); + Path renamedName = folderPath.getFileSystem().getPath("watch-renamed.txt"); + try (WatchService watcher = folderPath.getFileSystem().newWatchService()) { + folderPath.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, + StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE); + + FileObject file = folder.createData(originalName.toString()); + assertWatchEvents(watcher, new ExpectedWatchEvent(StandardWatchEventKinds.ENTRY_CREATE, originalName)); + + try (OutputStream out = file.getOutputStream()) { + out.write(42); + } + assertWatchEvents(watcher, new ExpectedWatchEvent(StandardWatchEventKinds.ENTRY_MODIFY, originalName)); + + try (FileLock lock = file.lock()) { + file.rename(lock, "watch-renamed", "txt"); + } + assertWatchEvents(watcher, + new ExpectedWatchEvent(StandardWatchEventKinds.ENTRY_DELETE, originalName), + new ExpectedWatchEvent(StandardWatchEventKinds.ENTRY_CREATE, renamedName)); + + try (OutputStream out = file.getOutputStream()) { + out.write(43); + } + assertWatchEvents(watcher, new ExpectedWatchEvent(StandardWatchEventKinds.ENTRY_MODIFY, renamedName)); + + file.delete(); + assertWatchEvents(watcher, new ExpectedWatchEvent(StandardWatchEventKinds.ENTRY_DELETE, renamedName)); + } + assertEquals(2, children.length); + } + + public void testWatchServiceRoutesRenameToWatchedDirectory() throws Exception { + if (testedFS.isReadOnly()) { + return; + } + FileObject folder = getFileObject().getParent(); + FileObject[] children = folder.getChildren(); + FileObject nested = folder.createFolder("watch-nested"); + nested.createData("before.txt"); + FileObject[] nestedChildren = nested.getChildren(); + Path parentPath = FileUtil.toPath(folder); + Path nestedPath = parentPath.resolve("watch-nested"); + try (WatchService watcher = parentPath.getFileSystem().newWatchService()) { + WatchKey parentKey = parentPath.register(watcher, + StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE); + WatchKey nestedKey = nestedPath.register(watcher, + StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE); + Files.move(nestedPath.resolve("before.txt"), nestedPath.resolve("after.txt")); + + Set expected = Set.of("ENTRY_DELETE:before.txt", "ENTRY_CREATE:after.txt"); + Set remaining = new HashSet<>(expected); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (!remaining.isEmpty()) { + long timeout = deadline - System.nanoTime(); + assertTrue("Expected nested directory events " + remaining, timeout > 0); + WatchKey key = watcher.poll(timeout, TimeUnit.NANOSECONDS); + assertNotNull("Expected nested directory events " + remaining, key); + assertSame("Event delivered to the wrong directory", nestedKey, key); + for (WatchEvent event : key.pollEvents()) { + String actual = event.kind().name() + ":" + event.context(); + assertTrue("Unexpected event " + actual, expected.contains(actual)); + remaining.remove(actual); + } + assertTrue(key.reset()); + } + WatchKey extra = watcher.poll(200, TimeUnit.MILLISECONDS); + assertNotSame("Rename must not signal the parent directory", parentKey, extra); + } + assertEquals(2, children.length); + assertEquals(1, nestedChildren.length); + } + public void testRenameFileThroughPath() throws Exception { if (testedFS.isReadOnly()) { return; @@ -574,16 +687,10 @@ private void assertWatchEvents(WatchService watcher, ExpectedWatchEvent... expec WatchKey key = watcher.poll(timeout, TimeUnit.NANOSECONDS); assertNotNull("Expected WatchService events " + remaining, key); for (WatchEvent event : key.pollEvents()) { - boolean matched = false; for (Iterator it = remaining.iterator(); it.hasNext();) { ExpectedWatchEvent candidate = it.next(); - String candidateContext = candidate.context.toString(); - String eventContext = event.context() == null ? null : event.context().toString(); - if (candidate.kind == event.kind() - && watchContextsMatch(normalizeWatchContext(candidateContext), - normalizeWatchContext(eventContext))) { + if (candidate.kind == event.kind() && candidate.context.equals(event.context())) { it.remove(); - matched = true; break; } } @@ -592,23 +699,6 @@ && watchContextsMatch(normalizeWatchContext(candidateContext), } } - private static String normalizeWatchContext(String context) { - if (context == null) { - return ""; - } - while (context.startsWith("/")) { - context = context.substring(1); - } - return context; - } - - private static boolean watchContextsMatch(String candidate, String event) { - if (candidate.equals(event)) { - return true; - } - return event.endsWith("/" + candidate); - } - private void assertWatchEventPresent(WatchService watcher, ExpectedWatchEvent expected) throws Exception { long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); while (true) { From 8381dbbb9ff36e6e61fa51e6e318ad0b23845ebd Mon Sep 17 00:00:00 2001 From: Jaroslav Tulach Date: Sun, 22 Nov 2026 21:48:20 +0100 Subject: [PATCH 15/16] Implementation of Path.copy --- .../openide/filesystems/NioPathProvider.java | 70 ++++++++++- .../openide/filesystems/MemoryFSTestHid.java | 12 ++ .../org/openide/filesystems/PathTestHid.java | 118 ++++++++++++++++++ 3 files changed, 199 insertions(+), 1 deletion(-) diff --git a/platform/openide.filesystems/src/org/openide/filesystems/NioPathProvider.java b/platform/openide.filesystems/src/org/openide/filesystems/NioPathProvider.java index 81790922b5b2..0325e8a94c1a 100644 --- a/platform/openide.filesystems/src/org/openide/filesystems/NioPathProvider.java +++ b/platform/openide.filesystems/src/org/openide/filesystems/NioPathProvider.java @@ -28,19 +28,25 @@ import java.nio.file.AccessDeniedException; import java.nio.file.AccessMode; import java.nio.file.CopyOption; +import java.nio.file.DirectoryNotEmptyException; import java.nio.file.DirectoryStream; +import java.nio.file.FileAlreadyExistsException; import java.nio.file.FileStore; import java.nio.file.FileSystem; import java.nio.file.LinkOption; import java.nio.file.NoSuchFileException; +import java.nio.file.NotDirectoryException; import java.nio.file.OpenOption; import java.nio.file.Path; +import java.nio.file.ProviderMismatchException; +import java.nio.file.StandardCopyOption; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileAttribute; import java.nio.file.attribute.FileTime; import java.nio.file.spi.FileSystemProvider; import java.util.Iterator; import java.util.Map; +import java.util.Objects; import java.util.Set; final class NioPathProvider extends FileSystemProvider { @@ -153,7 +159,69 @@ public void delete(Path path) throws IOException { @Override public void copy(Path source, Path target, CopyOption... options) throws IOException { - move(source, target, options); + 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 diff --git a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MemoryFSTestHid.java b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MemoryFSTestHid.java index 60b938807da7..d8bf4099fed6 100644 --- a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MemoryFSTestHid.java +++ b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/MemoryFSTestHid.java @@ -24,7 +24,9 @@ import java.net.URI; import java.net.URL; import java.net.URLConnection; +import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.StandardCopyOption; /** * @@ -97,4 +99,14 @@ public void testURIs() throws Exception{ assertEquals("memory", u2.getScheme()); assertEquals("memory", path.getFileSystem().provider().getScheme()); } + + public void testCopyAttributesThroughPath() throws Exception { + FileObject source = testedFS.getRoot().createData("source.txt"); + source.setAttribute("custom", "value"); + Path target = FileUtil.toPath(source).resolveSibling("copy.txt"); + + Files.copy(FileUtil.toPath(source), target, StandardCopyOption.COPY_ATTRIBUTES); + assertEquals("value", FileUtil.toFileObject(target).getAttribute("custom")); + assertNotNull(testedFS.getRoot().getFileObject("source.txt")); + } } diff --git a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java index 1af52c300e14..d268f8484fae 100644 --- a/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java +++ b/platform/openide.filesystems/test/unit/src/org/openide/filesystems/PathTestHid.java @@ -19,13 +19,17 @@ package org.openide.filesystems; import java.io.File; +import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.nio.channels.FileChannel; import java.nio.charset.StandardCharsets; +import java.nio.file.FileAlreadyExistsException; import java.nio.file.Files; +import java.nio.file.NoSuchFileException; import java.nio.file.Path; +import java.nio.file.StandardCopyOption; import java.nio.file.StandardOpenOption; import java.nio.file.StandardWatchEventKinds; import java.nio.file.WatchEvent; @@ -264,6 +268,120 @@ public void testCreateFileAndFolderThroughPath() throws Exception { assertEquals("created through NIO", file.asText()); } + public void testCopyFileThroughPath() throws Exception { + if (testedFS.isReadOnly()) { + return; + } + FileObject source = getFileObject(); + FileObject folder = source.getParent(); + Path sourcePath = FileUtil.toPath(source); + Path targetPath = sourcePath.resolveSibling("nio-copy.txt"); + Files.writeString(sourcePath, "original content"); + + assertEquals(targetPath, Files.copy(sourcePath, targetPath)); + folder.refresh(); + assertTrue("Copy must not invalidate the source", source.isValid()); + assertEquals(source, folder.getFileObject("file.txt")); + assertEquals("original content", source.asText("UTF-8")); + FileObject target = folder.getFileObject("nio-copy.txt"); + assertNotNull(target); + assertEquals("original content", target.asText("UTF-8")); + + Files.writeString(targetPath, "different content"); + try { + Files.copy(sourcePath, targetPath); + fail("Copying over an existing file must fail"); + } catch (FileAlreadyExistsException expected) { + } + assertEquals("different content", Files.readString(targetPath)); + Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING); + assertEquals("original content", Files.readString(targetPath)); + assertEquals("original content", Files.readString(sourcePath)); + Files.copy(sourcePath, sourcePath); + Files.copy(sourcePath, sourcePath, StandardCopyOption.REPLACE_EXISTING); + assertEquals("original content", Files.readString(sourcePath)); + try { + Files.copy(sourcePath, sourcePath.resolveSibling("missing-folder").resolve("copy.txt")); + fail("Copying to a missing parent directory must fail"); + } catch (NoSuchFileException expected) { + } + try { + Files.copy(sourcePath, sourcePath.resolveSibling("unsupported.txt"), StandardCopyOption.ATOMIC_MOVE); + fail("An unsupported copy option must fail"); + } catch (UnsupportedOperationException expected) { + } + } + + public void testCopyDirectoryThroughPath() throws Exception { + if (testedFS.isReadOnly()) { + return; + } + Path source = getPath().getParent(); + Path target = source.resolveSibling("nio-copy-folder"); + + Files.copy(source, target); + assertTrue(Files.isDirectory(target)); + try (Stream entries = Files.list(target)) { + assertEquals("Directory copy must not copy children", 0, entries.count()); + } + assertTrue(Files.exists(source.resolve("file.txt"))); + Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING); + Files.createFile(target.resolve("child.txt")); + try { + Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING); + fail("Replacing a nonempty directory must fail"); + } catch (IOException expected) { + } + assertTrue(Files.exists(target.resolve("child.txt"))); + try { + Files.copy(source.resolve("missing.txt"), target.resolve("missing.txt")); + fail("Copying a missing source must fail"); + } catch (NoSuchFileException expected) { + } + } + + public void testCopyFileToLocalFilesystem() throws Exception { + FileObject source = getFileObject(); + Path sourcePath = FileUtil.toPath(source); + Path targetPath = getWorkDir().toPath().resolve("nio-external-copy.txt"); + byte[] content = Files.readAllBytes(sourcePath); + + Files.copy(sourcePath, targetPath); + assertTrue(Arrays.equals(content, Files.readAllBytes(targetPath))); + assertTrue(source.isValid()); + assertEquals(source, source.getParent().getFileObject(source.getNameExt())); + } + + public void testCopyFileFromLocalFilesystem() throws Exception { + if (testedFS.isReadOnly()) { + return; + } + Path source = getWorkDir().toPath().resolve("nio-external-source.txt"); + Path target = getPath().resolveSibling("nio-imported.txt"); + Files.writeString(source, "external content"); + + Files.copy(source, target); + assertEquals("external content", Files.readString(source)); + assertEquals("external content", Files.readString(target)); + } + + public void testCopyToReadOnlyFilesystemFails() throws Exception { + if (!testedFS.isReadOnly()) { + return; + } + FileObject source = getFileObject(); + Path sourcePath = FileUtil.toPath(source); + Path targetPath = sourcePath.resolveSibling("nio-copy.txt"); + try { + Files.copy(sourcePath, targetPath); + fail("Copying to a read-only filesystem must fail"); + } catch (IOException expected) { + } + assertTrue(source.isValid()); + assertEquals(source, source.getParent().getFileObject(source.getNameExt())); + assertNull(source.getParent().getFileObject("nio-copy.txt")); + } + public void testReadAndWriteThroughPathStreams() throws Exception { FileObject file = getFileObject(); Path path = getPath(); From 5319023c6afba2fa213314b81bf6668c61c0d655 Mon Sep 17 00:00:00 2001 From: Jaroslav Tulach Date: Sun, 22 Nov 2026 22:09:32 +0100 Subject: [PATCH 16/16] Documenting the toPath behavior --- platform/openide.filesystems/apichanges.xml | 16 +++++++++++++++- platform/openide.filesystems/manifest.mf | 2 +- .../src/org/openide/filesystems/FileUtil.java | 16 +++++++++++----- 3 files changed, 27 insertions(+), 7 deletions(-) diff --git a/platform/openide.filesystems/apichanges.xml b/platform/openide.filesystems/apichanges.xml index 8872f3e0fb66..0d7b2aee7a89 100644 --- a/platform/openide.filesystems/apichanges.xml +++ b/platform/openide.filesystems/apichanges.xml @@ -19,12 +19,26 @@ under the License. --> - + Filesystems API + + + FileUtil.toPath works for every file object + + + + + + FileUtil.toPath + now returns a non-null Path instance + for all file objects, even for virtual ones. + + + FileObject copy preserves source posix permissions. diff --git a/platform/openide.filesystems/manifest.mf b/platform/openide.filesystems/manifest.mf index 8ac6f2fa4277..b27c2de73c58 100644 --- a/platform/openide.filesystems/manifest.mf +++ b/platform/openide.filesystems/manifest.mf @@ -2,6 +2,6 @@ Manifest-Version: 1.0 OpenIDE-Module: org.openide.filesystems OpenIDE-Module-Localizing-Bundle: org/openide/filesystems/Bundle.properties OpenIDE-Module-Layer: org/openide/filesystems/resources/layer.xml -OpenIDE-Module-Specification-Version: 9.48 +OpenIDE-Module-Specification-Version: 9.50 diff --git a/platform/openide.filesystems/src/org/openide/filesystems/FileUtil.java b/platform/openide.filesystems/src/org/openide/filesystems/FileUtil.java index 3210a54c8d87..f98d4d0f1d41 100644 --- a/platform/openide.filesystems/src/org/openide/filesystems/FileUtil.java +++ b/platform/openide.filesystems/src/org/openide/filesystems/FileUtil.java @@ -833,11 +833,16 @@ 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 for the FileObject + /** Finds appropriate {@link Path} for given {@code FileObject}. + * Since version 9.50 it is guaranteed that the return value + * will never be {@code null} for an object with valid {@link FileObject#getFileSystem()}. + * A fully functional {@link Path} + * instance is created even for fully virtual {@code FileObject}s. + * + * This is the inverse operation of {@link #toFileObject(java.nio.file.Path) }. + * @param fo object to find corresponding Path for + * @return {@link Path} for the {@code FileObject} never {@code null} + * * @since 9.32 */ public static Path toPath(FileObject fo) { @@ -926,6 +931,7 @@ 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) {