import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SeekableByteChannel;
import java.nio.channels.NonWritableChannelException;
import java.nio.channels.NonReadableChannelException;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class FileObject extends FileSystemObject {
// In-memory content storage
private byte[] content;
private final ReentrantReadWriteLock contentLock = new ReentrantReadWriteLock();
public FileObject() {
super(FileSystemObjectType.FILE);
this.content = new byte[0];
}
/**
* Read content bytes (thread-safe).
*/
public byte[] readContent() {
contentLock.readLock().lock();
try {
updateLastAccessTime();
return content.clone();
} finally {
contentLock.readLock().unlock();
}
}
/**
* Write content bytes (thread-safe).
*/
public void writeContent(byte[] newContent) {
contentLock.writeLock().lock();
try {
this.content = newContent.clone();
updateLastModifiedTime();
} finally {
contentLock.writeLock().unlock();
}
}
/**
* Append content bytes (thread-safe).
*/
public void appendContent(byte[] moreContent) {
contentLock.writeLock().lock();
try {
byte[] newContent = new byte[content.length + moreContent.length];
System.arraycopy(content, 0, newContent, 0, content.length);
System.arraycopy(moreContent, 0, newContent, content.length, moreContent.length);
this.content = newContent;
updateLastModifiedTime();
} finally {
contentLock.writeLock().unlock();
}
}
/**
* Open a FileChannel for this file.
* This is a simplified in-memory FileChannel implementation.
*/
public FileChannel openFileChannel() {
return new InMemoryFileChannel(this);
}
// Inner class for in-memory FileChannel
private static class InMemoryFileChannel extends FileChannel {
private final FileObject fileObject;
private int position = 0;
private boolean open = true;
public InMemoryFileChannel(FileObject fileObject) {
this.fileObject = fileObject;
}
@Override
public int read(ByteBuffer dst) throws IOException {
ensureOpen();
fileObject.contentLock.readLock().lock();
try {
byte[] content = fileObject.content;
if (position >= content.length) {
return -1; // EOF
}
int bytesToRead = Math.min(dst.remaining(), content.length - position);
dst.put(content, position, bytesToRead);
position += bytesToRead;
fileObject.updateLastAccessTime();
return bytesToRead;
} finally {
fileObject.contentLock.readLock().unlock();
}
}
@Override
public int write(ByteBuffer src) throws IOException {
ensureOpen();
fileObject.contentLock.writeLock().lock();
try {
int bytesToWrite = src.remaining();
byte[] oldContent = fileObject.content;
int newLength = Math.max(oldContent.length, position + bytesToWrite);
byte[] newContent = new byte[newLength];
System.arraycopy(oldContent, 0, newContent, 0, oldContent.length);
src.get(newContent, position, bytesToWrite);
position += bytesToWrite;
fileObject.content = newContent;
fileObject.updateLastModifiedTime();
return bytesToWrite;
} finally {
fileObject.contentLock.writeLock().unlock();
}
}
@Override
public long position() throws IOException {
ensureOpen();
return position;
}
@Override
public FileChannel position(long newPosition) throws IOException {
ensureOpen();
if (newPosition < 0 || newPosition > Integer.MAX_VALUE) {
throw new IllegalArgumentException("Position out of range");
}
this.position = (int) newPosition;
return this;
}
@Override
public long size() throws IOException {
ensureOpen();
fileObject.contentLock.readLock().lock();
try {
return fileObject.content.length;
} finally {
fileObject.contentLock.readLock().unlock();
}
}
@Override
public FileChannel truncate(long size) throws IOException {
ensureOpen();
if (size < 0 || size > Integer.MAX_VALUE) {
throw new IllegalArgumentException("Size out of range");
}
fileObject.contentLock.writeLock().lock();
try {
int newSize = (int) size;
if (newSize < fileObject.content.length) {
byte[] newContent = new byte[newSize];
System.arraycopy(fileObject.content, 0, newContent, 0, newSize);
fileObject.content = newContent;
if (position > newSize) {
position = newSize;
}
fileObject.updateLastModifiedTime();
}
return this;
} finally {
fileObject.contentLock.writeLock().unlock();
}
}
@Override
protected void implCloseChannel() throws IOException {
open = false;
}
private void ensureOpen() throws IOException {
if (!open) throw new IOException("Channel is closed");
}
// Other FileChannel methods can throw UnsupportedOperationException for simplicity
@Override
public long read(ByteBuffer[] dsts, int offset, int length) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public long write(ByteBuffer[] srcs, int offset, int length) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public long transferTo(long position, long count, java.nio.channels.WritableByteChannel target) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public long transferFrom(java.nio.channels.ReadableByteChannel src, long position, long count) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public int read(ByteBuffer dst, long position) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public int write(ByteBuffer src, long position) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public java.nio.MappedByteBuffer map(MapMode mode, long position, long size) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public java.nio.channels.FileLock lock(long position, long size, boolean shared) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public java.nio.channels.FileLock tryLock(long position, long size, boolean shared) throws IOException {
throw new UnsupportedOperationException();
}
}
}
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class FileSystemStorage {
// Map root namespace -> (Path -> FileSystemObject)
private final Map<String, Map<Path, FileSystemObject>> roots = new ConcurrentHashMap<>();
// Lock for hierarchy modifications (create/delete/move)
private final ReentrantReadWriteLock hierarchyLock = new ReentrantReadWriteLock();
/**
* Initialize a root namespace.
*/
public void createRoot(String rootName) {
roots.putIfAbsent(rootName, new ConcurrentHashMap<>());
}
/**
* Get the map for a root namespace.
*/
private Map<Path, FileSystemObject> getRootMap(String rootName) {
Map<Path, FileSystemObject> map = roots.get(rootName);
if (map == null) {
throw new IllegalArgumentException("Root namespace does not exist: " + rootName);
}
return map;
}
/**
* Check if an object exists at the given path in the root.
*/
public boolean exists(String rootName, Path path) {
Map<Path, FileSystemObject> rootMap = getRootMap(rootName);
hierarchyLock.readLock().lock();
try {
return rootMap.containsKey(path);
} finally {
hierarchyLock.readLock().unlock();
}
}
/**
* Get the FileSystemObject at the given path.
*/
public FileSystemObject getObject(String rootName, Path path) {
Map<Path, FileSystemObject> rootMap = getRootMap(rootName);
hierarchyLock.readLock().lock();
try {
return rootMap.get(path);
} finally {
hierarchyLock.readLock().unlock();
}
}
/**
* Create a new FileSystemObject at the given path.
* Throws if already exists.
*/
public void createObject(String rootName, Path path, FileSystemObject obj) {
Map<Path, FileSystemObject> rootMap = getRootMap(rootName);
hierarchyLock.writeLock().lock();
try {
if (rootMap.containsKey(path)) {
throw new IllegalStateException("Object already exists at path: " + path);
}
// Add to map
rootMap.put(path, obj);
// Add to parent's children if parent exists
Path parent = path.getParent();
if (parent != null) {
FileSystemObject parentObj = rootMap.get(parent);
if (!(parentObj instanceof DirectoryObject)) {
throw new IllegalStateException("Parent is not a directory: " + parent);
}
((DirectoryObject) parentObj).addChild(path);
}
} finally {
hierarchyLock.writeLock().unlock();
}
}
/**
* Delete an object at the given path.
* If directory, must be empty.
*/
public void deleteObject(String rootName, Path path) {
Map<Path, FileSystemObject> rootMap = getRootMap(rootName);
hierarchyLock.writeLock().lock();
try {
FileSystemObject obj = rootMap.get(path);
if (obj == null) {
throw new IllegalStateException("No object at path: " + path);
}
if (obj instanceof DirectoryObject) {
DirectoryObject dir = (DirectoryObject) obj;
if (!dir.getChildren().isEmpty()) {
throw new IllegalStateException("Directory not empty: " + path);
}
}
// Remove from parent's children
Path parent = path.getParent();
if (parent != null) {
FileSystemObject parentObj = rootMap.get(parent);
if (parentObj instanceof DirectoryObject) {
((DirectoryObject) parentObj).removeChild(path);
}
}
// Remove from map
rootMap.remove(path);
} finally {
hierarchyLock.writeLock().unlock();
}
}
/**
* Move an object from sourcePath to destPath.
* Both paths must be in the same root.
*/
public void moveObject(String rootName, Path sourcePath, Path destPath) {
Map<Path, FileSystemObject> rootMap = getRootMap(rootName);
hierarchyLock.writeLock().lock();
try {
if (!rootMap.containsKey(sourcePath)) {
throw new IllegalStateException("Source path does not exist: " + sourcePath);
}
if (rootMap.containsKey(destPath)) {
throw new IllegalStateException("Destination path already exists: " + destPath);
}
FileSystemObject obj = rootMap.remove(sourcePath);
// Remove from old parent's children
Path oldParent = sourcePath.getParent();
if (oldParent != null) {
FileSystemObject oldParentObj = rootMap.get(oldParent);
if (oldParentObj instanceof DirectoryObject) {
((DirectoryObject) oldParentObj).removeChild(sourcePath);
}
}
// Add to new parent's children
Path newParent = destPath.getParent();
if (newParent != null) {
FileSystemObject newParentObj = rootMap.get(newParent);
if (!(newParentObj instanceof DirectoryObject)) {
throw new IllegalStateException("New parent is not a directory: " + newParent);
}
((DirectoryObject) newParentObj).addChild(destPath);
}
// Put object at new path
rootMap.put(destPath, obj);
} finally {
hierarchyLock.writeLock().unlock();
}
}
}