-
Notifications
You must be signed in to change notification settings - Fork 874
/
Copy pathMemoryFileSystem.java
506 lines (423 loc) · 15.8 KB
/
MemoryFileSystem.java
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
/*
* 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.beans.PropertyVetoException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.openide.util.URLStreamHandlerRegistration;
import org.openide.util.lookup.ServiceProvider;
/**
* Simple implementation of memory file system.
* @author Jaroslav Tulach
*/
final class MemoryFileSystem extends AbstractFileSystem implements AbstractFileSystem.Info, AbstractFileSystem.Change, AbstractFileSystem.List, AbstractFileSystem.Attr {
private static final Logger ERR = Logger.getLogger(MemoryFileSystem.class.getName());
private static final AtomicLong COUNT = new AtomicLong();
private final long id = COUNT.incrementAndGet();
/** time when the filesystem was created. It is supposed to be the default
* time of modification for all resources that has not been modified yet
*/
private java.util.Date created = new java.util.Date();
/** maps String to Entry */
private final Map<String, Entry> entries = initEntry();
@SuppressWarnings("deprecation") // need to set it for compat
private void _setSystemName(String s) throws PropertyVetoException {
setSystemName(s);
}
/** Creates new MemoryFS */
public MemoryFileSystem() {
attr = this;
list = this;
change = this;
info = this;
try {
_setSystemName("MemoryFileSystem" + String.valueOf(id));
} catch (PropertyVetoException ex) {
ex.printStackTrace();
}
}
/** Creates MemoryFS with data */
public MemoryFileSystem(String[] resources) {
this();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < resources.length; i++) {
sb.append(resources[i]);
if (resources[i].endsWith("/")) {
// folder
getOrCreateEntry(resources[i]).data = null;
} else {
getOrCreateEntry(resources[i]).data = new byte[0];
}
}
}
/** finds entry for given name */
private Entry getOrCreateEntry(String n) {
if ((n.length() > 0) && (n.charAt(0) == '/')) {
n = n.substring(1);
}
boolean isValidEntry = isValidEntry(n);
synchronized(entries) {
Entry x = entries.get(n);
if (x == null || !isValidEntry) {
x = new Entry(n);
entries.put(n, x);
}
return x;
}
}
private boolean isValidEntry(String n) {
return isValidEntry(n, null);
}
/** finds whether there already is this name */
private boolean isValidEntry(String n, Boolean expectedResult) {
boolean retval = (n.length() == 0) ? true : false;
if ((n.length() > 0) && (n.charAt(0) == '/')) {
n = n.substring(1);
}
Entry x = entries.get(n);
FileObject fo = null;
if (x != null) {
Reference<? extends FileObject> ref = findReference(n);
if (ref != null) {
fo = ref.get();
retval = (fo != null) ? fo.isValid() : true;
}
}
if (ERR.isLoggable(Level.FINE) && expectedResult != null && retval != expectedResult.booleanValue()) {
logMessage("entry: " + x + " isValidReference.fo: " + ((fo == null) ? "null" : //NOI18N
(fo.isValid() ? "valid" : "invalid")));//NOI18N
}
return (retval);
}
public String getDisplayName() {
return "MemoryFileSystem";
}
public boolean isReadOnly() {
return false;
}
public Enumeration<String> attributes(String name) {
if (!isValidEntry(name)) {
return org.openide.util.Enumerations.empty();
}
return Collections.enumeration(getOrCreateEntry(name).attrs.keySet());
}
public String[] children(String f) {
if ((f.length() > 0) && (f.charAt(0) == '/')) {
f = f.substring(1);
}
if ((f.length() > 0) && !f.endsWith("/")) {
f = f + "/";
}
Set<String> l = new HashSet<String>();
//System.out.println("Folder: " + f);
synchronized(entries) {
for (String name : entries.keySet()) {
if (name.startsWith(f) || (f.trim().length() == 0)) {
int i = name.indexOf('/', f.length());
String child = null;
if (i > 0) {
child = name.substring(f.length(), i);
} else {
child = name.substring(f.length());
}
if (child.trim().length() > 0) {
l.add(child);
}
}
}
return l.toArray(new String[0]);
}
}
public void createData(String name) throws IOException {
if (isValidEntry(name, Boolean.FALSE)) {
StringBuffer message = new StringBuffer();
message.append("File already exists: ").append(name);
throw new IOException(message.toString());//NOI18N
}
getOrCreateEntry(name).data = new byte[0];
}
public void createFolder(String name) throws java.io.IOException {
if (isValidEntry(name, Boolean.FALSE)) {
StringBuffer message = new StringBuffer();
message.append("Folder already exists: ").append(name);
throw new IOException(message.toString());//NOI18N
}
getOrCreateEntry(name).data = null;
}
public void delete(String name) throws IOException {
if (entries.remove(name) == null) {
throw new IOException("No file to delete: " + name); // NOI18N
}
}
public void deleteAttributes(String name) {
}
public boolean folder(String name) {
return getOrCreateEntry(name).data == null;
}
public InputStream inputStream(String name) throws java.io.FileNotFoundException {
byte[] arr = getOrCreateEntry(name).data;
if (arr == null) {
arr = new byte[0];
}
return new ByteArrayInputStream(arr);
}
public java.util.Date lastModified(String name) {
java.util.Date d = getOrCreateEntry(name).last;
return (d == null) ? created : d;
}
public void lock(String name) throws IOException {
}
public void markUnimportant(String name) {
}
public String mimeType(String name) {
return (String) getOrCreateEntry(name).attrs.get("mimeType");
}
public OutputStream outputStream(final String name)
throws java.io.IOException {
class Out extends ByteArrayOutputStream {
@Override
public void close() throws IOException {
super.close();
getOrCreateEntry(name).data = toByteArray();
getOrCreateEntry(name).last = new Date();
}
}
return new Out();
}
public Object readAttribute(String name, String attrName) {
return isValidEntry(name) ? getOrCreateEntry(name).attrs.get(attrName) : null;
}
public boolean readOnly(String name) {
return false;
}
@Override
public void rename(String oldName, String newName)
throws IOException {
if (!isValidEntry(oldName)) {
throw new IOException("The file to rename does not exist.");
}
if (isValidEntry(newName)) {
throw new IOException("Cannot rename to existing file");
}
if ((newName.length() > 0) && (newName.charAt(0) == '/')) {
newName = newName.substring(1);
}
ArrayList<Map.Entry<String, Entry>> clone = new ArrayList<Map.Entry<String, Entry>>(entries.entrySet());
for (Map.Entry<String, Entry> each : clone) {
if (each.getKey().startsWith(oldName)) {
entries.remove(each.getKey());
String n = newName + each.getKey().substring(oldName.length());
entries.put(n, each.getValue());
}
}
}
public void renameAttributes(String oldName, String newName) {
}
public long size(String name) {
byte[] d = getOrCreateEntry(name).data;
return (d == null) ? 0 : d.length;
}
public void unlock(String name) {
}
public void writeAttribute(String name, String attrName, Object value)
throws IOException {
getOrCreateEntry(name).attrs.put(attrName, value);
}
private Map<String, Entry> initEntry() {
if (!ERR.isLoggable(Level.FINE)) {
return new ConcurrentHashMap<String, MemoryFileSystem.Entry>();
}
return new ConcurrentHashMap<String, MemoryFileSystem.Entry>() {
public MemoryFileSystem.Entry get(String key) {
MemoryFileSystem.Entry retval = super.get(key);
logMessage("called: GET" + " key: "+key + " result: " + retval);//NOI18N
return retval;
}
@Override
public MemoryFileSystem.Entry put(String key, MemoryFileSystem.Entry value) {
MemoryFileSystem.Entry retval = super.put(key, value);
logMessage("called: PUT" + " key: "+key + " value: "+value+ " result: " + retval);//NOI18N
return retval;
}
public MemoryFileSystem.Entry remove(String key) {
MemoryFileSystem.Entry retval = super.remove(key);
logMessage("called: REMOVE" + " key: "+key + " result: " + retval);//NOI18N
return retval;
}
};
}
static final class Entry {
/** String, Object */
public Map<String, Object> attrs = Collections.synchronizedMap(new HashMap<String, Object>());
public byte[] data;
public java.util.Date last;
private final String entryName;
Entry(String entryName) {
this.entryName = entryName;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(" [").append(entryName);//NOI18N
sb.append(" -> ").append(super.toString());//NOI18N
sb.append("] ");
return sb.toString();
}
}
private static void logMessage(final String message) {
StringBuffer sb = new StringBuffer();
sb.append(" -> ").append(message);
//ucomment if necessary
/*ByteArrayOutputStream bos = new ByteArrayOutputStream();
PrintWriter pw = new PrintWriter(bos);
new Exception().printStackTrace(pw);
pw.close();
sb.append(bos.toString());
*/
ERR.fine(sb.toString());
}
// Support for URLs of the form memory://fs23/folder/file
@ServiceProvider(service=URLMapper.class)
public static final class Mapper extends URLMapper {
private static final Map<Long,Reference<FileSystem>> filesystems = new HashMap<Long,Reference<FileSystem>>(); // i.e. a sparse array by id
public @Override URL getURL(FileObject fo, int type) {
if (type != URLMapper.INTERNAL) {
return null;
}
try {
FileSystem fs = fo.getFileSystem();
if (fs instanceof MemoryFileSystem) {
String path = fo.getPath();
if (fo.isFolder() && !fo.isRoot()) {
path += '/';
}
return url((MemoryFileSystem) fs, path);
}
} catch (FileStateInvalidException x) {
// ignore
}
return null;
}
// keep as separate method to avoid linking Handler until needed
private static synchronized URL url(MemoryFileSystem fs, String path) {
synchronized (filesystems) {
Reference<FileSystem> r = filesystems.get(fs.id);
if (r == null || r.get() == null) {
r = new WeakReference<FileSystem>(fs);
filesystems.put(fs.id, r);
}
}
try {
return new URL(null, Handler.PROTOCOL + "://fs" + fs.id + "/" + path, new Handler());
} catch (MalformedURLException x) {
throw new AssertionError(x);
}
}
private static final Pattern HOST = Pattern.compile("fs(\\d+)"); // NOI18N
static FileObject find(URL url) {
if (!Handler.PROTOCOL.equals(url.getProtocol())) {
return null;
}
Matcher m = HOST.matcher(url.getHost());
if (!m.matches()) {
return null;
}
Reference<FileSystem> r;
synchronized (filesystems) {
r = filesystems.get(Long.parseLong(m.group(1)));
}
if (r == null) {
return null;
}
FileSystem fs = r.get();
if (fs == null) {
return null;
}
return fs.findResource(url.getPath().substring(1));
}
public @Override FileObject[] getFileObjects(URL url) {
FileObject f = find(url);
return f != null ? new FileObject[] {f} : null;
}
}
@URLStreamHandlerRegistration(protocol=Handler.PROTOCOL)
public static final class Handler extends URLStreamHandler {
static final String PROTOCOL = "memory"; // NOI18N
protected @Override URLConnection openConnection(URL u) throws IOException {
return new MemoryConnection(u);
}
@Override
protected int hashCode(URL u) {
int h = 0;
String host = u.getHost();
if (host != null)
h += host.toLowerCase().hashCode();
// Generate the file part.
String file = u.getFile();
if (file != null)
h += file.hashCode();
// Generate the port part.
return h;
}
@Override
protected boolean equals(URL u1, URL u2) {
return
Objects.equals(u1.getHost(), u2.getHost()) &&
Objects.equals(u1.getFile(), u2.getFile());
}
private static class MemoryConnection extends FileURL {
MemoryConnection(URL u) {
super(u);
}
public @Override synchronized void connect() throws IOException {
if (fo == null) {
fo = Mapper.find(url);
}
if (fo == null) {
throw new FileNotFoundException(url.toString());
}
}
}
}
}