Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/src/java.base/share/classes/java/nio/file/FileTreeWalker.java
41159 views
1
/*
2
* Copyright (c) 2007, 2021, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation. Oracle designates this
8
* particular file as subject to the "Classpath" exception as provided
9
* by Oracle in the LICENSE file that accompanied this code.
10
*
11
* This code is distributed in the hope that it will be useful, but WITHOUT
12
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14
* version 2 for more details (a copy is included in the LICENSE file that
15
* accompanied this code).
16
*
17
* You should have received a copy of the GNU General Public License version
18
* 2 along with this work; if not, write to the Free Software Foundation,
19
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20
*
21
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22
* or visit www.oracle.com if you need additional information or have any
23
* questions.
24
*/
25
26
package java.nio.file;
27
28
import java.nio.file.attribute.BasicFileAttributes;
29
import java.io.Closeable;
30
import java.io.IOException;
31
import java.util.ArrayDeque;
32
import java.util.Collection;
33
import java.util.Iterator;
34
import sun.nio.fs.BasicFileAttributesHolder;
35
36
/**
37
* Walks a file tree, generating a sequence of events corresponding to the files
38
* in the tree.
39
*
40
* <pre>{@code
41
* Path top = ...
42
* Set<FileVisitOption> options = ...
43
* int maxDepth = ...
44
*
45
* try (FileTreeWalker walker = new FileTreeWalker(options, maxDepth)) {
46
* FileTreeWalker.Event ev = walker.walk(top);
47
* do {
48
* process(ev);
49
* ev = walker.next();
50
* } while (ev != null);
51
* }
52
* }</pre>
53
*
54
* @see Files#walkFileTree
55
*/
56
57
class FileTreeWalker implements Closeable {
58
private final boolean followLinks;
59
private final LinkOption[] linkOptions;
60
private final int maxDepth;
61
private final ArrayDeque<DirectoryNode> stack = new ArrayDeque<>();
62
private boolean closed;
63
64
/**
65
* The element on the walking stack corresponding to a directory node.
66
*/
67
private static class DirectoryNode {
68
private final Path dir;
69
private final Object key;
70
private final DirectoryStream<Path> stream;
71
private final Iterator<Path> iterator;
72
private boolean skipped;
73
74
DirectoryNode(Path dir, Object key, DirectoryStream<Path> stream) {
75
this.dir = dir;
76
this.key = key;
77
this.stream = stream;
78
this.iterator = stream.iterator();
79
}
80
81
Path directory() {
82
return dir;
83
}
84
85
Object key() {
86
return key;
87
}
88
89
DirectoryStream<Path> stream() {
90
return stream;
91
}
92
93
Iterator<Path> iterator() {
94
return iterator;
95
}
96
97
void skip() {
98
skipped = true;
99
}
100
101
boolean skipped() {
102
return skipped;
103
}
104
}
105
106
/**
107
* The event types.
108
*/
109
static enum EventType {
110
/**
111
* Start of a directory
112
*/
113
START_DIRECTORY,
114
/**
115
* End of a directory
116
*/
117
END_DIRECTORY,
118
/**
119
* An entry in a directory
120
*/
121
ENTRY;
122
}
123
124
/**
125
* Events returned by the {@link #walk} and {@link #next} methods.
126
*/
127
static class Event {
128
private final EventType type;
129
private final Path file;
130
private final BasicFileAttributes attrs;
131
private final IOException ioe;
132
133
private Event(EventType type, Path file, BasicFileAttributes attrs, IOException ioe) {
134
this.type = type;
135
this.file = file;
136
this.attrs = attrs;
137
this.ioe = ioe;
138
}
139
140
Event(EventType type, Path file, BasicFileAttributes attrs) {
141
this(type, file, attrs, null);
142
}
143
144
Event(EventType type, Path file, IOException ioe) {
145
this(type, file, null, ioe);
146
}
147
148
EventType type() {
149
return type;
150
}
151
152
Path file() {
153
return file;
154
}
155
156
BasicFileAttributes attributes() {
157
return attrs;
158
}
159
160
IOException ioeException() {
161
return ioe;
162
}
163
}
164
165
/**
166
* Creates a {@code FileTreeWalker}.
167
*
168
* @throws IllegalArgumentException
169
* if {@code maxDepth} is negative
170
* @throws ClassCastException
171
* if {@code options} contains an element that is not a
172
* {@code FileVisitOption}
173
* @throws NullPointerException
174
* if {@code options} is {@code null} or the options
175
* array contains a {@code null} element
176
*/
177
FileTreeWalker(Collection<FileVisitOption> options, int maxDepth) {
178
boolean fl = false;
179
for (FileVisitOption option: options) {
180
// will throw NPE if options contains null
181
switch (option) {
182
case FOLLOW_LINKS : fl = true; break;
183
default:
184
throw new AssertionError("Should not get here");
185
}
186
}
187
if (maxDepth < 0)
188
throw new IllegalArgumentException("'maxDepth' is negative");
189
190
this.followLinks = fl;
191
this.linkOptions = (fl) ? new LinkOption[0] :
192
new LinkOption[] { LinkOption.NOFOLLOW_LINKS };
193
this.maxDepth = maxDepth;
194
}
195
196
/**
197
* Returns the attributes of the given file, taking into account whether
198
* the walk is following sym links is not. The {@code canUseCached}
199
* argument determines whether this method can use cached attributes.
200
*/
201
@SuppressWarnings("removal")
202
private BasicFileAttributes getAttributes(Path file, boolean canUseCached)
203
throws IOException
204
{
205
// if attributes are cached then use them if possible
206
if (canUseCached &&
207
(file instanceof BasicFileAttributesHolder) &&
208
(System.getSecurityManager() == null))
209
{
210
BasicFileAttributes cached = ((BasicFileAttributesHolder)file).get();
211
if (cached != null && (!followLinks || !cached.isSymbolicLink())) {
212
return cached;
213
}
214
}
215
216
// attempt to get attributes of file. If fails and we are following
217
// links then a link target might not exist so get attributes of link
218
BasicFileAttributes attrs;
219
try {
220
attrs = Files.readAttributes(file, BasicFileAttributes.class, linkOptions);
221
} catch (IOException ioe) {
222
if (!followLinks)
223
throw ioe;
224
225
// attempt to get attrmptes without following links
226
attrs = Files.readAttributes(file,
227
BasicFileAttributes.class,
228
LinkOption.NOFOLLOW_LINKS);
229
}
230
return attrs;
231
}
232
233
/**
234
* Returns true if walking into the given directory would result in a
235
* file system loop/cycle.
236
*/
237
private boolean wouldLoop(Path dir, Object key) {
238
// if this directory and ancestor has a file key then we compare
239
// them; otherwise we use less efficient isSameFile test.
240
for (DirectoryNode ancestor: stack) {
241
Object ancestorKey = ancestor.key();
242
if (key != null && ancestorKey != null) {
243
if (key.equals(ancestorKey)) {
244
// cycle detected
245
return true;
246
}
247
} else {
248
try {
249
if (Files.isSameFile(dir, ancestor.directory())) {
250
// cycle detected
251
return true;
252
}
253
} catch (IOException | SecurityException x) {
254
// ignore
255
}
256
}
257
}
258
return false;
259
}
260
261
/**
262
* Visits the given file, returning the {@code Event} corresponding to that
263
* visit.
264
*
265
* The {@code ignoreSecurityException} parameter determines whether
266
* any SecurityException should be ignored or not. If a SecurityException
267
* is thrown, and is ignored, then this method returns {@code null} to
268
* mean that there is no event corresponding to a visit to the file.
269
*
270
* The {@code canUseCached} parameter determines whether cached attributes
271
* for the file can be used or not.
272
*/
273
private Event visit(Path entry, boolean ignoreSecurityException, boolean canUseCached) {
274
// need the file attributes
275
BasicFileAttributes attrs;
276
try {
277
attrs = getAttributes(entry, canUseCached);
278
} catch (IOException ioe) {
279
return new Event(EventType.ENTRY, entry, ioe);
280
} catch (SecurityException se) {
281
if (ignoreSecurityException)
282
return null;
283
throw se;
284
}
285
286
// at maximum depth or file is not a directory
287
int depth = stack.size();
288
if (depth >= maxDepth || !attrs.isDirectory()) {
289
return new Event(EventType.ENTRY, entry, attrs);
290
}
291
292
// check for cycles when following links
293
if (followLinks && wouldLoop(entry, attrs.fileKey())) {
294
return new Event(EventType.ENTRY, entry,
295
new FileSystemLoopException(entry.toString()));
296
}
297
298
// file is a directory, attempt to open it
299
DirectoryStream<Path> stream = null;
300
try {
301
stream = Files.newDirectoryStream(entry);
302
} catch (IOException ioe) {
303
return new Event(EventType.ENTRY, entry, ioe);
304
} catch (SecurityException se) {
305
if (ignoreSecurityException)
306
return null;
307
throw se;
308
}
309
310
// push a directory node to the stack and return an event
311
stack.push(new DirectoryNode(entry, attrs.fileKey(), stream));
312
return new Event(EventType.START_DIRECTORY, entry, attrs);
313
}
314
315
316
/**
317
* Start walking from the given file.
318
*/
319
Event walk(Path file) {
320
if (closed)
321
throw new IllegalStateException("Closed");
322
323
Event ev = visit(file,
324
false, // ignoreSecurityException
325
false); // canUseCached
326
assert ev != null;
327
return ev;
328
}
329
330
/**
331
* Returns the next Event or {@code null} if there are no more events or
332
* the walker is closed.
333
*/
334
Event next() {
335
DirectoryNode top = stack.peek();
336
if (top == null)
337
return null; // stack is empty, we are done
338
339
// continue iteration of the directory at the top of the stack
340
Event ev;
341
do {
342
Path entry = null;
343
IOException ioe = null;
344
345
// get next entry in the directory
346
if (!top.skipped()) {
347
Iterator<Path> iterator = top.iterator();
348
try {
349
if (iterator.hasNext()) {
350
entry = iterator.next();
351
}
352
} catch (DirectoryIteratorException x) {
353
ioe = x.getCause();
354
}
355
}
356
357
// no next entry so close and pop directory,
358
// creating corresponding event
359
if (entry == null) {
360
try {
361
top.stream().close();
362
} catch (IOException e) {
363
if (ioe == null) {
364
ioe = e;
365
} else {
366
ioe.addSuppressed(e);
367
}
368
}
369
stack.pop();
370
return new Event(EventType.END_DIRECTORY, top.directory(), ioe);
371
}
372
373
// visit the entry
374
ev = visit(entry,
375
true, // ignoreSecurityException
376
true); // canUseCached
377
378
} while (ev == null);
379
380
return ev;
381
}
382
383
/**
384
* Pops the directory node that is the current top of the stack so that
385
* there are no more events for the directory (including no END_DIRECTORY)
386
* event. This method is a no-op if the stack is empty or the walker is
387
* closed.
388
*/
389
void pop() {
390
if (!stack.isEmpty()) {
391
DirectoryNode node = stack.pop();
392
try {
393
node.stream().close();
394
} catch (IOException ignore) { }
395
}
396
}
397
398
/**
399
* Skips the remaining entries in the directory at the top of the stack.
400
* This method is a no-op if the stack is empty or the walker is closed.
401
*/
402
void skipRemainingSiblings() {
403
if (!stack.isEmpty()) {
404
stack.peek().skip();
405
}
406
}
407
408
/**
409
* Returns {@code true} if the walker is open.
410
*/
411
boolean isOpen() {
412
return !closed;
413
}
414
415
/**
416
* Closes/pops all directories on the stack.
417
*/
418
@Override
419
public void close() {
420
if (!closed) {
421
while (!stack.isEmpty()) {
422
pop();
423
}
424
closed = true;
425
}
426
}
427
}
428
429