jtulach commented on code in PR #9820: URL: https://github.com/apache/netbeans/pull/9820#discussion_r4704846995
########## platform/openide.filesystems/src/org/openide/filesystems/NioFileObjectChannel.java: ########## @@ -0,0 +1,551 @@ +/* + * 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.nio.ByteBuffer; +import java.nio.MappedByteBuffer; +import java.nio.channels.ClosedChannelException; +import java.nio.channels.ClosedByInterruptException; +import java.nio.channels.FileChannel; +import java.nio.channels.NonReadableChannelException; +import java.nio.channels.NonWritableChannelException; +import java.nio.channels.ReadableByteChannel; +import java.nio.channels.WritableByteChannel; +import java.nio.file.FileAlreadyExistsException; +import java.nio.file.NoSuchFileException; +import java.nio.file.OpenOption; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.FileAttribute; +import java.util.Arrays; +import java.util.Objects; +import java.util.Set; + +final class NioFileObjectChannel extends FileChannel { + /* + * State.class guards channel state. A writable channel owns its FileObject lock + * until close, even if an operation is still running. + * Reads compare state snapshots by identity to retry after any state change. + * Position-changing operations and writes reserve their channel until they + * complete; a reentrant operation cannot safely wait for its own reservation. + */ + private final FileObject file; + private final FileLock fileLock; + private final NioLock nioLock; + private final boolean readable; + private final boolean append; + // @GuardedBy("State.class") Every transition creates a fresh snapshot. + // all methods manipulating this field should be inside of {@link State} class + private State state; + private NioFileObjectChannel(FileObject file, FileLock fileLock, boolean readable, boolean append) { + this.file = file; + this.fileLock = fileLock; + this.nioLock = fileLock == null ? null : new NioLock(this); + this.readable = readable; + this.append = append; + this.state = new State(append ? file.getSize() : 0, null); + } + + static FileChannel open(NioPathForFileObject path, Set<? extends OpenOption> options, + FileAttribute<?>... attrs) throws IOException { + boolean read = options.contains(StandardOpenOption.READ); + boolean write = options.contains(StandardOpenOption.WRITE); + boolean append = options.contains(StandardOpenOption.APPEND); + if (append && read || append && options.contains(StandardOpenOption.TRUNCATE_EXISTING)) { + throw new IllegalArgumentException("Invalid append options"); + } + write |= append; + if (!read && !write) { + read = true; + } + for (OpenOption option : options) { + Objects.requireNonNull(option, "option"); + if (option != StandardOpenOption.READ && option != StandardOpenOption.WRITE + && option != StandardOpenOption.APPEND && option != StandardOpenOption.CREATE + && option != StandardOpenOption.CREATE_NEW && option != StandardOpenOption.TRUNCATE_EXISTING) { + throw new UnsupportedOperationException("Unsupported open option: " + option); + } + } + if (attrs.length != 0) { + throw new UnsupportedOperationException("Initial attributes are not supported"); + } + FileObject file = path.getFileObject(); + if (file != null && file.isValid() && write && options.contains(StandardOpenOption.CREATE_NEW)) { + throw new FileAlreadyExistsException(path.toString()); + } + if (file == null || !file.isValid()) { + if (!write || !(options.contains(StandardOpenOption.CREATE) || options.contains(StandardOpenOption.CREATE_NEW))) { + throw new NoSuchFileException(path.toString()); + } + NioPathForFileObject parent = (NioPathForFileObject) path.getParent(); + FileObject folder = parent == null ? null : parent.getFileObject(); + if (folder == null || !folder.isValid()) { + throw new NoSuchFileException(path.toString()); + } + file = folder.createData(path.getFileName().toString()); + } + if (!file.isData()) { + throw new IOException("Not a regular file: " + path); + } + if (write && file.isReadOnly()) { + throw new java.nio.file.AccessDeniedException(path.toString()); + } + FileLock token = write ? file.lock() : null; + NioFileObjectChannel channel = null; + try { + if (token != null && !token.isValid()) { + throw new IOException("FileObject does not support locking: " + file); + } + channel = new NioFileObjectChannel(file, token, read, append); + if (write && options.contains(StandardOpenOption.TRUNCATE_EXISTING)) { + channel.truncate(0); + } + return channel; + } catch (IOException | RuntimeException | Error ex) { + try { + if (channel != null) { + channel.close(); + } else if (token != null) { + token.releaseLock(); + } + } catch (IOException | RuntimeException | Error closeException) { + ex.addSuppressed(closeException); + } + throw ex; + } + } + + private void checkOpen() throws ClosedChannelException { + if (!isOpen()) { + throw new ClosedChannelException(); + } + } + + private ClosedByInterruptException interruptedOperation() throws IOException { + try { + close(); + } finally { + Thread.currentThread().interrupt(); + } + return new ClosedByInterruptException(); + } + + @Override + public int read(ByteBuffer dst) throws IOException { + checkReadable(dst); + if (!dst.hasRemaining()) { + return 0; + } + byte[] data = readAtCurrentPosition(dst.remaining()); + if (data == null) { + return -1; + } + dst.put(data); + return data.length; + } + + @Override + public int read(ByteBuffer dst, long at) throws IOException { + checkReadable(dst); + if (at < 0) { + throw new IllegalArgumentException("Negative position"); + } + if (!dst.hasRemaining()) { + return 0; + } + byte[] data = readImpl(at, dst.remaining()); + if (data == null) { + return -1; + } + dst.put(data); + return data.length; + } + + private void checkReadable(ByteBuffer dst) throws IOException { + checkOpen(); + if (!readable) { + throw new NonReadableChannelException(); + } + if (dst.isReadOnly()) { + throw new IllegalArgumentException("Read-only buffer"); + } + } + + private byte[] readImpl(long at, int maximum) throws IOException { + try (InputStream input = file.getInputStream()) { + input.skipNBytes(Math.min(at, file.getSize())); + byte[] buffer = new byte[Math.min(maximum, 8192)]; + int n = input.read(buffer); + return n < 0 ? null : Arrays.copyOf(buffer, n); + } + } + + private byte[] readAtCurrentPosition(int maximum) throws IOException { + try { + for (;;) { + State snapshot = State.awaitOperation(this); + byte[] data = readImpl(snapshot.position(), maximum); + int count = data == null ? 0 : data.length; + if (!State.completeRead(this, snapshot, count)) { + continue; + } + return data; + } + } catch (InterruptedException ex) { + throw interruptedOperation(); + } + } + + @Override + public long read(ByteBuffer[] dsts, int offset, int length) throws IOException { + checkOpen(); + if (!readable) { + throw new NonReadableChannelException(); + } + Objects.checkFromIndexSize(offset, length, dsts.length); + int maximum = 0; + for (int i = offset; i < offset + length; i++) { + checkReadable(dsts[i]); + maximum += Math.min(dsts[i].remaining(), 8192 - maximum); + } + if (maximum == 0) { + return 0; + } + byte[] data = readAtCurrentPosition(maximum); + if (data == null) { + return -1; + } + int copied = 0; + for (int i = offset; i < offset + length && copied < data.length; i++) { + int count = Math.min(dsts[i].remaining(), data.length - copied); + dsts[i].put(data, copied, count); + copied += count; + } + return copied; + } + + @Override + public int write(ByteBuffer src) throws IOException { + State previous = State.beginOperation(this); + State next = previous; + try { + long at = append ? size() : previous.position(); + int n = writeImpl(src, at); + next = previous.withPosition(at + n); + return n; + } finally { + State.endOperation(this, previous, next); + } + } + + @Override + public int write(ByteBuffer src, long at) throws IOException { + State previous = State.beginOperation(this); + try { + return writeImpl(src, at); + } finally { + State.endOperation(this, previous, previous); + } + } + + private int writeImpl(ByteBuffer src, long at) throws IOException { + if (fileLock == null) { + throw new NonWritableChannelException(); + } + if (at < 0) { + throw new IllegalArgumentException("Negative position"); + } + int start = src.position(); + int count = src.remaining(); + if (count == 0) { + return 0; + } + if (at > Integer.MAX_VALUE - count) { + throw new IOException("File is too large for virtual channel"); + } + update(at, src, -1); + src.position(start + count); + return count; + } + + private void update(long at, ByteBuffer src, long truncate) throws IOException { + checkOpen(); + byte[] data = file.asBytes(); + int size = truncate >= 0 ? (int) Math.min(truncate, data.length) + : Math.max(data.length, (int) at + src.remaining()); + data = Arrays.copyOf(data, size); + if (src != null) { + src.get(src.position(), data, (int) at, src.remaining()); + } + try (OutputStream output = file.getOutputStream(fileLock)) { + output.write(data); + } + } + + @Override + public long write(ByteBuffer[] srcs, int offset, int length) throws IOException { + State previous = State.beginOperation(this); + State next = previous; + try { + if (fileLock == null) { + throw new NonWritableChannelException(); + } + Objects.checkFromIndexSize(offset, length, srcs.length); + long total = 0; + for (int i = offset; i < offset + length; i++) { + long at = append ? size() : next.position(); + int n = writeImpl(srcs[i], at); + next = next.withPosition(at + n); + total += n; + } + return total; + } finally { + State.endOperation(this, previous, next); + } + } + + @Override + public long position() throws IOException { + checkOpen(); + return State.snapshot(this).position(); + } + + @Override + public FileChannel position(long newPosition) throws IOException { + State previous = State.beginOperation(this); + State next = previous; + try { + if (newPosition < 0) { + throw new IllegalArgumentException("Negative position"); + } + next = previous.withPosition(newPosition); + return this; + } finally { + State.endOperation(this, previous, next); + } + } + + @Override + public long size() throws IOException { + checkOpen(); + return file.getSize(); + } + + @Override + public FileChannel truncate(long size) throws IOException { + State previous = State.beginOperation(this); + State next = previous; + try { + if (fileLock == null) { + throw new NonWritableChannelException(); + } + if (size < 0) { + throw new IllegalArgumentException("Negative size"); + } + if (size < file.getSize()) { + update(0, null, size); + } + next = previous.withPosition(Math.min(previous.position(), size)); + return this; + } finally { + State.endOperation(this, previous, next); + } + } + + @Override + public void force(boolean metaData) throws IOException { + checkOpen(); + throw new UnsupportedOperationException("Forcing virtual files to storage is not supported"); Review Comment: The comment is addressed. force now writes buffered changes to the `FileObject` for either argument, rather than throwing `UnsupportedOperationException`. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected] For further information about the NetBeans mailing lists, visit: https://cwiki.apache.org/confluence/display/NETBEANS/Mailing+lists
