-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathFilesystemStore.java
More file actions
268 lines (242 loc) · 9.56 KB
/
FilesystemStore.java
File metadata and controls
268 lines (242 loc) · 9.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
package dev.zarr.zarrjava.store;
import dev.zarr.zarrjava.utils.Utils;
import org.apache.commons.io.input.BoundedInputStream;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.*;
import java.util.stream.Stream;
import java.io.File;
import java.util.stream.Collectors;
import java.util.stream.Stream.Builder;
import java.nio.file.attribute.BasicFileAttributes;
// Java logging
import java.util.logging.Logger;
import java.util.logging.Level;
public class FilesystemStore implements Store, Store.ListableStore {
private static final Logger logger = Logger.getLogger(FilesystemStore.class.getName());
@Nonnull
private final Path path;
public FilesystemStore(@Nonnull Path path) {
this.path = path;
}
public FilesystemStore(@Nonnull String path) {
this.path = Paths.get(path);
}
Path resolveKeys(String[] keys) {
Path newPath = path;
for (String key : keys) {
newPath = newPath.resolve(key);
}
Path absRoot = path.toAbsolutePath().normalize();
Path absTarget = newPath.toAbsolutePath().normalize();
if (!absTarget.startsWith(absRoot)) {
throw new IllegalArgumentException("Key resolves outside of store root: " + absTarget);
}
return newPath.normalize();
}
@Override
public boolean exists(String[] keys) {
return Files.isRegularFile(resolveKeys(keys));
}
@Nullable
@Override
public ByteBuffer get(String[] keys) {
try {
return ByteBuffer.wrap(Files.readAllBytes(resolveKeys(keys)));
} catch (NoSuchFileException e) {
return null;
} catch (IOException e) {
throw StoreException.readFailed(this.toString(), keys, e);
}
}
@Nullable
@Override
public ByteBuffer get(String[] keys, long start) {
try (SeekableByteChannel byteChannel = Files.newByteChannel(resolveKeys(keys))) {
long startOffset = 0;
if (start >= 0) {
startOffset = start;
} else {
startOffset = byteChannel.size() + start;
}
long endOffset = byteChannel.size();
ByteBuffer bytes = Utils.allocateNative((int) (endOffset - startOffset));
byteChannel.position(startOffset);
byteChannel.read(bytes);
bytes.rewind();
return bytes;
} catch (NoSuchFileException e) {
return null;
} catch (IOException e) {
throw StoreException.readFailed(this.toString(), keys, e);
}
}
@Nullable
@Override
public ByteBuffer get(String[] keys, long start, long end) {
try (SeekableByteChannel byteChannel = Files.newByteChannel(resolveKeys(keys))) {
long startOffset = 0;
if (start >= 0) {
startOffset = start;
} else {
startOffset = byteChannel.size() + start;
}
ByteBuffer bytes = Utils.allocateNative((int) (end - startOffset));
byteChannel.position(startOffset);
byteChannel.read(bytes);
bytes.rewind();
return bytes;
} catch (NoSuchFileException e) {
return null;
} catch (IOException e) {
throw StoreException.readFailed(this.toString(), keys, e);
}
}
@Override
public void set(String[] keys, ByteBuffer bytes) {
Path keyPath = resolveKeys(keys);
try {
Files.createDirectories(keyPath.getParent());
} catch (IOException e) {
throw StoreException.writeFailed(
this.toString(),
keys,
new IOException("Failed to create parent directories for path: " + keyPath.getParent(), e));
}
try (SeekableByteChannel channel = Files.newByteChannel(keyPath.toAbsolutePath(),
StandardOpenOption.CREATE,
StandardOpenOption.TRUNCATE_EXISTING,
StandardOpenOption.WRITE
)) {
channel.write(bytes);
} catch (IOException e) {
throw StoreException.writeFailed(
this.toString(),
keys,
new IOException("Failed to write " + bytes.remaining() + " bytes to file: " + keyPath, e));
}
}
@Override
public void delete(String[] keys) {
Path keyPath = resolveKeys(keys);
try {
Files.delete(keyPath);
} catch (NoSuchFileException e) {
// ignore - file doesn't exist, which is the desired outcome
} catch (IOException e) {
throw StoreException.deleteFailed(
this.toString(),
keys,
new IOException("Failed to delete file: " + keyPath, e));
}
}
@Override
public Stream<String[]> list(String[] prefix) {
Path rootPath = resolveKeys(prefix);
try {
Builder<String[]> builder = Stream.builder(); // Create a Stream.Builder to collect results
// Walk the directory tree using walkFileTree
Files.walkFileTree(rootPath, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
// Only process regular files avoids Files::isRegularFile additional IO calls
if (attrs.isRegularFile()) {
String[] keys = rootPath.relativize(path).toString().split(File.separator);
builder.add(keys); // Add the keys to the stream builder
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
// Called when a file could not be visited
String msg = "Failed to visit file: " + file + " due to: " + exc.getMessage();
logger.log(Level.WARNING, msg, exc);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
});
return builder.build(); // Build the stream and return it
//return Files.walk(rootPath).parallel().filter(Files::isRegularFile) // Filter only regular files (not directories)
// .map(path -> rootPath.relativize(path).toString().split(File.separator)); // Get relative path and split into keys
} catch (IOException e) {
throw StoreException.listFailed(
this.toString(),
prefix,
new IOException("Failed to walk directory tree at: " + rootPath, e));
}
}
@Override
public Stream<String> listChildren(String[] prefix) {
Path rootPath = resolveKeys(prefix);
if (!Files.exists(rootPath) || !Files.isDirectory(rootPath)) {
return Stream.empty();
}
try {
return Files.list(rootPath).map(path -> path.getFileName().toString());
} catch (IOException e) {
throw StoreException.listFailed(
this.toString(),
prefix,
new IOException("Failed to list directory contents at: " + rootPath, e));
}
}
@Nonnull
@Override
public StoreHandle resolve(String... keys) {
return new StoreHandle(this, keys);
}
@Override
public String toString() {
return this.path.toUri().toString().replaceAll("\\/$", "");
}
@Override
public InputStream getInputStream(String[] keys, long start, long end) {
Path keyPath = resolveKeys(keys);
try {
InputStream inputStream = Files.newInputStream(keyPath);
if (start > 0) {
long skipped = inputStream.skip(start);
if (skipped < start) {
throw new IOException("Unable to skip to position " + start + ", only skipped " + skipped + " bytes in file: " + keyPath);
}
}
if (end != -1) {
long bytesToRead = end - start;
return new BoundedInputStream(inputStream, bytesToRead);
} else {
return inputStream;
}
} catch (NoSuchFileException e) {
return null;
} catch (IOException e) {
throw StoreException.readFailed(
this.toString(),
keys,
new IOException("Failed to open input stream for file: " + keyPath + " (start: " + start + ", end: " + end + ")", e));
}
}
public long getSize(String[] keys) {
Path keyPath = resolveKeys(keys);
try {
return Files.size(keyPath);
} catch (NoSuchFileException e) {
return -1;
} catch (IOException e) {
throw StoreException.readFailed(
this.toString(),
keys,
new IOException("Failed to get file size for: " + keyPath, e));
}
}
}