-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathFileSystemLike.java
More file actions
303 lines (265 loc) · 10.3 KB
/
FileSystemLike.java
File metadata and controls
303 lines (265 loc) · 10.3 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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
package org.labkey.vfs;
import org.labkey.api.collections.CaseInsensitiveHashMap;
import org.labkey.api.util.FileUtil;
import org.labkey.api.util.MemTracker;
import org.labkey.api.util.Path;
import org.labkey.api.util.URIUtil;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.apache.commons.lang3.StringUtils.defaultIfBlank;
import static org.labkey.api.util.FileUtil.FILE_SCHEME;
/**
* In LabKey most files are accessed within a directory with a particular role. For instance, a directory might be:
* <br>
* - a pipeline root used for storing assay files
* <br>
* - a temporary working directory used for assay import or a report
* <br>
* - a directory with configuration files
* <p/>
* In any of these scenarios the code using that directory usually does not need access to files _outside_ that directory.
* Using java.io.File makes it difficult to enforce this. Instead of this common pattern
* <pre>
* File workingdir = new File("tempdir");
* File file = new File(workingdir, anypath))
* </pre>
* We can now follow this pattern, which validates the scope of the resolved path.
* <pre>
* FileLike workingdir = new FileSystemLike.Builder("tempdir").readwrite().root();
* FileLike file = workingdir.resolveFile(anypath);
* </pre>
*
* <p/>
* implementation notes:
* - This is meant to be a wrapper over java.nio.file.Path, java.io.File or org.apache.commons.vfs2.FileObject or other implementaions.
* However, it is still lower level than Resource. For instance, it does not know about Permissions or ContentType, etc.
* <br>
* - FileLike objects always present String path and util.Path relative to the FileSystemLike root.
* If the FileLike wraps a local path, toNioPath() can be used.
* <br>
* - These classes generally do not cache metadata, but the wrapped impl might. This is why FileLike has a reset() method.
* - Caching versions can be explicitly requested.
*/
public interface FileSystemLike
{
// NOTE: a full webdav path consist of case-sensitive and case-insensitive parts
// However, the relative part of the path into a file system will be consistently sensitive or not
// These helpers can be used to make the correct Path for this VFS
org.labkey.api.util.Path parsePath(String str);
org.labkey.api.util.Path pathOf(org.labkey.api.util.Path path);
/*
* Create a file system that return FileLike objects that cache basic file meta-data such as type (file/directory)
* and direct children. refresh() can be used to force reload of metadata.
* TODO See PipelineDirectoryImpl for code that currently does its own caching for performance
* reasons.
* FileSystemResource has already been converted to use getCachingFileSystem().
*/
FileSystemLike getCachingFileSystem();
default String getScheme()
{
return getURI().getScheme();
}
URI getURI();
URI getURI(FileLike fo);
java.nio.file.Path getNioPath(FileLike fo);
FileLike getRoot();
FileLike resolveFile(Path path); // same as getRoot().resolveFile(path)
// these methods do not represent permission or specific underlying capability
// This is requested behavior
boolean canList();
boolean canReadFiles();
boolean canWriteFiles();
boolean canDeleteRoot();
default boolean isDescendant(FileLike base, URI uri)
{
// handle common case
if (null == base || getRoot() == base)
return URIUtil.isDescendant(getURI(), uri);
if (base.getFileSystem() != this)
throw new IllegalArgumentException();
return URIUtil.isDescendant(getURI(base), uri);
}
/** BasicFileAttributes uses more memory than we really need, so this is the basics */
record MinimalFileAttributes(boolean exists, boolean file, boolean directory, long size, long lastModified, long created) {}
MinimalFileAttributes NULL_ATTRIBUTES = new MinimalFileAttributes(false, false, false, 0, 0, 0);
class Builder
{
URI uri;
boolean defaultVfs = false; // for testing
boolean canList = true;
boolean canReadFiles = true;
boolean canWriteFiles = true;
boolean canDeleteRoot = false;
boolean memCheck = true;
boolean caching = false;
public Builder(URI uri)
{
this.uri = uri;
}
public Builder(File f)
{
this.uri = f.toURI();
}
public Builder(java.nio.file.Path path)
{
this.uri = path.toUri();
}
public Builder caching()
{
caching = true;
return this;
}
public Builder readonly()
{
canReadFiles = true;
canWriteFiles = false;
return this;
}
public Builder readwrite()
{
canReadFiles = true;
canWriteFiles = true;
return this;
}
public Builder tempDir()
{
canDeleteRoot = true;
return readwrite();
}
public Builder vfs()
{
defaultVfs = true;
return this;
}
public Builder noMemCheck()
{
memCheck = false;
return this;
}
public FileSystemLike build()
{
var scheme = defaultIfBlank(uri.getScheme(), FILE_SCHEME);
FileSystemLike ret;
if (defaultVfs || !FILE_SCHEME.equals(scheme))
ret = new FileSystemVFS(uri, canReadFiles, canWriteFiles, canDeleteRoot);
else
ret = new FileSystemLocal(uri, canReadFiles, canWriteFiles, canDeleteRoot);
if (caching)
ret = ret.getCachingFileSystem();
if (!memCheck)
{
MemTracker.get().remove(ret);
MemTracker.get().remove(ret.getRoot());
}
return ret;
}
public FileLike root()
{
return build().getRoot();
}
}
/** Helper for partially converted code. Parent dir must exist. */
static FileLike wrapFile(File f)
{
FileLike p = new Builder(f.getParentFile()).root();
return p.resolveChild(f.getName());
}
static FileLike wrapFile(java.nio.file.Path p)
{
if (null == p)
return null;
return wrapFile(p.toFile());
}
/** Helper for partially converted code. root must exist. */
static FileLike wrapFile(File root, File f) throws IOException
{
if (!root.isDirectory())
throw new FileNotFoundException(root.getPath());
FileSystemLike fs = new Builder(root.toURI()).build();
String rel = FileUtil.relativize(root, f, true);
return fs.getRoot().resolveFile(Path.parse(rel));
}
/** Helper for partially converted code. May throw if the FileLike does not wrap a local file system. */
static File toFile(FileLike f)
{
if (null == f)
return null;
java.nio.file.Path p = f.getFileSystem().getNioPath(f);
return p.toFile();
}
// Converts an absolute URI to a relative one if it's within the base URI.
// If fileURI is outside rootURI, the result remains fileURI/unchanged.
// Examples:
// root "/a/b/c/", file "/x/y/z.txt" -> "/x/y/z.txt"
// root "/a/b/c/", file "/a/b/c/d.txt" -> "d.txt"
static URI getRelativeURI(URI rootURI, URI fileURI)
{
return rootURI.relativize(fileURI);
}
static FileLike resolveChildWithRelativeURI(URI rootURI, URI fileURI)
{
URI relativeURI = getRelativeURI(rootURI, fileURI);
// If the relative URI is absolute or remains unchanged, it means relativize failed and the file is outside the root directory.
if (relativeURI.isAbsolute() || relativeURI.equals(fileURI))
{
throw new IllegalArgumentException("File '" + fileURI.getPath() + "' is outside the root '" + rootURI.getPath() + "'");
}
FileLike allowedRoot = new FileSystemLike.Builder(rootURI).root();
//explicitly check whether the given file path is within the allowed root directory
if (allowedRoot.getFileSystem().isDescendant(allowedRoot, fileURI))
{
return allowedRoot.resolveChild(relativeURI.getPath());
}
else
{
throw new IllegalArgumentException("File '" + relativeURI.getPath() + "' is not a descendant of '" + rootURI.getPath() + "'");
}
}
/* More efficient version of wrap when many files may be from the same directory */
static List<FileLike> wrapFiles(List<File> files)
{
Map<File, FileSystemLike> map = new HashMap<>();
List<FileLike> ret = new ArrayList<>(files.size());
for (File file : files)
{
File parent = file.getParentFile();
FileSystemLike fs = map.computeIfAbsent(parent, key -> new FileSystemLike.Builder(parent).readwrite().build());
ret.add(fs.resolveFile(new Path(file.getName())));
}
return ret;
}
static List<FileLike> wrapPaths(List<java.nio.file.Path> paths)
{
Map<File, FileSystemLike> map = new HashMap<>();
List<FileLike> ret = new ArrayList<>(paths.size());
for (var path : paths)
{
var file = path.toFile();
File parent = file.getParentFile();
FileSystemLike fs = map.computeIfAbsent(parent, key -> new FileSystemLike.Builder(parent).readwrite().build());
ret.add(fs.resolveFile(new Path(file.getName())));
}
return ret;
}
static Map<String, FileLike> wrapFiles(Map<String, File> files)
{
Map<File, FileSystemLike> map = new HashMap<>();
Map<String, FileLike> ret = files instanceof CaseInsensitiveHashMap<File> ?
new CaseInsensitiveHashMap<>() :
new HashMap<>(files.size());
for (var e : files.entrySet())
{
var file = e.getValue();
File parent = file.getParentFile();
FileSystemLike fs = map.computeIfAbsent(parent, key -> new FileSystemLike.Builder(parent).readwrite().build());
ret.put(e.getKey(), fs.resolveFile(new Path(file.getName())));
}
return ret;
}
}