StreamTest.java 27.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/*
 * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/* @test
25
 * @bug 8006884 8019526
26 27
 * @build PassThroughFileSystem FaultyFileSystem
 * @run testng StreamTest
28
 * @summary Unit test for java.nio.file.Files methods that return a Stream
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
 */

import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.Charset;
import java.nio.charset.MalformedInputException;
import java.nio.file.DirectoryIteratorException;
import java.nio.file.DirectoryStream;
import java.nio.file.FileSystemLoopException;
import java.nio.file.FileVisitOption;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Arrays;
45
import java.util.Collections;
46 47 48 49 50
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
51
import java.util.concurrent.Callable;
52
import java.util.function.BiPredicate;
53
import java.util.stream.Stream;
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
import java.util.stream.Collectors;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

@Test(groups = "unit")
public class StreamTest {
    /**
     * Default test folder
     * testFolder - empty
     *            - file
     *            - dir - d1
     *                  - f1
     *                  - lnDir2 (../dir2)
     *            - dir2
     *            - linkDir (./dir)
     *            - linkFile(./file)
     */
    static Path testFolder;
    static boolean supportsLinks;
    static Path[] level1;
    static Path[] all;
    static Path[] all_folowLinks;

    @BeforeClass
    void setupTestFolder() throws IOException {
        testFolder = TestUtil.createTemporaryDirectory();
        supportsLinks = TestUtil.supportsLinks(testFolder);
        TreeSet<Path> set = new TreeSet<>();

        // Level 1
        Path empty = testFolder.resolve("empty");
        Path file = testFolder.resolve("file");
        Path dir = testFolder.resolve("dir");
        Path dir2 = testFolder.resolve("dir2");
        Files.createDirectory(empty);
        Files.createFile(file);
        Files.createDirectory(dir);
        Files.createDirectory(dir2);
        set.add(empty);
        set.add(file);
        set.add(dir);
        set.add(dir2);
        if (supportsLinks) {
            Path tmp = testFolder.resolve("linkDir");
            Files.createSymbolicLink(tmp, dir);
            set.add(tmp);
            tmp = testFolder.resolve("linkFile");
            Files.createSymbolicLink(tmp, file);
            set.add(tmp);
        }
        level1 = set.toArray(new Path[0]);

        // Level 2
        Path tmp = dir.resolve("d1");
        Files.createDirectory(tmp);
        set.add(tmp);
        tmp = dir.resolve("f1");
        Files.createFile(tmp);
        set.add(tmp);
        if (supportsLinks) {
            tmp = dir.resolve("lnDir2");
            Files.createSymbolicLink(tmp, dir2);
            set.add(tmp);
        }
        // walk include starting folder
        set.add(testFolder);
        all = set.toArray(new Path[0]);

        // Follow links
        if (supportsLinks) {
            tmp = testFolder.resolve("linkDir");
            set.add(tmp.resolve("d1"));
            set.add(tmp.resolve("f1"));
            tmp = tmp.resolve("lnDir2");
            set.add(tmp);
        }
        all_folowLinks = set.toArray(new Path[0]);
    }

    @AfterClass
    void cleanupTestFolder() throws IOException {
        TestUtil.removeAll(testFolder);
    }

    public void testBasic() {
141 142
        try (Stream<Path> s = Files.list(testFolder)) {
            Object[] actual = s.sorted().toArray();
143 144 145 146 147
            assertEquals(actual, level1);
        } catch (IOException ioe) {
            fail("Unexpected IOException");
        }

148
        try (Stream<Path> s = Files.list(testFolder.resolve("empty"))) {
149 150 151 152 153 154 155 156
            int count = s.mapToInt(p -> 1).reduce(0, Integer::sum);
            assertEquals(count, 0, "Expect empty stream.");
        } catch (IOException ioe) {
            fail("Unexpected IOException");
        }
    }

    public void testWalk() {
157 158
        try (Stream<Path> s = Files.walk(testFolder)) {
            Object[] actual = s.sorted().toArray();
159 160 161 162 163 164 165
            assertEquals(actual, all);
        } catch (IOException ioe) {
            fail("Unexpected IOException");
        }
    }

    public void testWalkOneLevel() {
166
        try (Stream<Path> s = Files.walk(testFolder, 1)) {
167
            Object[] actual = s.filter(path -> ! path.equals(testFolder))
168
                               .sorted()
169 170 171 172 173 174 175 176 177 178
                               .toArray();
            assertEquals(actual, level1);
        } catch (IOException ioe) {
            fail("Unexpected IOException");
        }
    }

    public void testWalkFollowLink() {
        // If link is not supported, the directory structure won't have link.
        // We still want to test the behavior with FOLLOW_LINKS option.
179 180
        try (Stream<Path> s = Files.walk(testFolder, FileVisitOption.FOLLOW_LINKS)) {
            Object[] actual = s.sorted().toArray();
181 182 183 184 185 186 187
            assertEquals(actual, all_folowLinks);
        } catch (IOException ioe) {
            fail("Unexpected IOException");
        }
    }

    private void validateFileSystemLoopException(Path start, Path... causes) {
188
        try (Stream<Path> s = Files.walk(start, FileVisitOption.FOLLOW_LINKS)) {
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
            try {
                int count = s.mapToInt(p -> 1).reduce(0, Integer::sum);
                fail("Should got FileSystemLoopException, but got " + count + "elements.");
            } catch (UncheckedIOException uioe) {
                IOException ioe = uioe.getCause();
                if (ioe instanceof FileSystemLoopException) {
                    FileSystemLoopException fsle = (FileSystemLoopException) ioe;
                    boolean match = false;
                    for (Path cause: causes) {
                        if (fsle.getFile().equals(cause.toString())) {
                            match = true;
                            break;
                        }
                    }
                    assertTrue(match);
                } else {
                    fail("Unexpected UncheckedIOException cause " + ioe.toString());
                }
            }
        } catch(IOException ex) {
            fail("Unexpected IOException " + ex);
        }
    }

    public void testWalkFollowLinkLoop() {
        if (!supportsLinks) {
            return;
        }

        // Loops.
        try {
            Path dir = testFolder.resolve("dir");
            Path linkdir = testFolder.resolve("linkDir");
            Path d1 = dir.resolve("d1");
            Path cause = d1.resolve("lnSelf");
            Files.createSymbolicLink(cause, d1);

            // loop in descendant.
            validateFileSystemLoopException(dir, cause);
            // loop in self
            validateFileSystemLoopException(d1, cause);
            // start from other place via link
            validateFileSystemLoopException(linkdir,
                    linkdir.resolve(Paths.get("d1", "lnSelf")));
            Files.delete(cause);

            // loop to parent.
            cause = d1.resolve("lnParent");
            Files.createSymbolicLink(cause, dir);

            // loop should be detected at test/dir/d1/lnParent/d1
            validateFileSystemLoopException(d1, cause.resolve("d1"));
            // loop should be detected at link
            validateFileSystemLoopException(dir, cause);
            // loop should be detected at test/linkdir/d1/lnParent
            // which is test/dir we have visited via test/linkdir
            validateFileSystemLoopException(linkdir,
                    linkdir.resolve(Paths.get("d1", "lnParent")));
            Files.delete(cause);

            // cross loop
            Path dir2 = testFolder.resolve("dir2");
            cause = dir2.resolve("lnDir");
            Files.createSymbolicLink(cause, dir);
            validateFileSystemLoopException(dir,
                    dir.resolve(Paths.get("lnDir2", "lnDir")));
            validateFileSystemLoopException(dir2,
                    dir2.resolve(Paths.get("lnDir", "lnDir2")));
            validateFileSystemLoopException(linkdir,
                    linkdir.resolve(Paths.get("lnDir2", "lnDir")));
        } catch(IOException ioe) {
            fail("Unexpected IOException " + ioe);
        }
    }

    private static class PathBiPredicate implements BiPredicate<Path, BasicFileAttributes> {
        private final BiPredicate<Path, BasicFileAttributes> pred;
        private final Set<Path> visited = new TreeSet<Path>();

        PathBiPredicate(BiPredicate<Path, BasicFileAttributes> pred) {
            this.pred = Objects.requireNonNull(pred);
        }

        public boolean test(Path path, BasicFileAttributes attrs) {
            visited.add(path);
            return pred.test(path, attrs);
        }

        public Path[] visited() {
            return visited.toArray(new Path[0]);
        }
    }

    public void testFind() throws IOException {
        PathBiPredicate pred = new PathBiPredicate((path, attrs) -> true);

285
        try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
286 287 288 289 290 291
            Set<Path> result = s.collect(Collectors.toCollection(TreeSet::new));
            assertEquals(pred.visited(), all);
            assertEquals(result.toArray(new Path[0]), pred.visited());
        }

        pred = new PathBiPredicate((path, attrs) -> attrs.isSymbolicLink());
292
        try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
293 294 295 296 297 298
            s.forEach(path -> assertTrue(Files.isSymbolicLink(path)));
            assertEquals(pred.visited(), all);
        }

        pred = new PathBiPredicate((path, attrs) ->
            path.getFileName().toString().startsWith("e"));
299
        try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
300 301 302 303 304 305
            s.forEach(path -> assertEquals(path.getFileName().toString(), "empty"));
            assertEquals(pred.visited(), all);
        }

        pred = new PathBiPredicate((path, attrs) ->
            path.getFileName().toString().startsWith("l") && attrs.isRegularFile());
306
        try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
307 308 309 310 311 312 313 314 315 316 317 318 319
            s.forEach(path -> fail("Expect empty stream"));
            assertEquals(pred.visited(), all);
        }
    }

    // Test borrowed from BytesAndLines
    public void testLines() throws IOException {
        final Charset US_ASCII = Charset.forName("US-ASCII");
        Path tmpfile = Files.createTempFile("blah", "txt");

        try {
            // zero lines
            assertTrue(Files.size(tmpfile) == 0, "File should be empty");
320 321 322
            try (Stream<String> s = Files.lines(tmpfile)) {
                checkLines(s, Collections.emptyList());
            }
323
            try (Stream<String> s = Files.lines(tmpfile, US_ASCII)) {
324
                checkLines(s, Collections.emptyList());
325 326 327
            }

            // one line
328 329 330 331 332
            List<String> oneLine = Arrays.asList("hi");
            Files.write(tmpfile, oneLine, US_ASCII);
            try (Stream<String> s = Files.lines(tmpfile)) {
                checkLines(s, oneLine);
            }
333
            try (Stream<String> s = Files.lines(tmpfile, US_ASCII)) {
334
                checkLines(s, oneLine);
335 336 337
            }

            // two lines using platform's line separator
338 339 340 341 342
            List<String> twoLines = Arrays.asList("hi", "there");
            Files.write(tmpfile, twoLines, US_ASCII);
            try (Stream<String> s = Files.lines(tmpfile)) {
                checkLines(s, twoLines);
            }
343
            try (Stream<String> s = Files.lines(tmpfile, US_ASCII)) {
344
                checkLines(s, twoLines);
345 346 347 348 349
            }

            // MalformedInputException
            byte[] bad = { (byte)0xff, (byte)0xff };
            Files.write(tmpfile, bad);
350 351 352
            try (Stream<String> s = Files.lines(tmpfile)) {
                checkMalformedInputException(s);
            }
353
            try (Stream<String> s = Files.lines(tmpfile, US_ASCII)) {
354
                checkMalformedInputException(s);
355 356 357
            }

            // NullPointerException
358 359 360
            checkNullPointerException(() -> Files.lines(null));
            checkNullPointerException(() -> Files.lines(null, US_ASCII));
            checkNullPointerException(() -> Files.lines(tmpfile, null));
361 362 363 364 365 366

        } finally {
            Files.delete(tmpfile);
        }
    }

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
    private void checkLines(Stream<String> s, List<String> expected) {
        List<String> lines = s.collect(Collectors.toList());
        assertTrue(lines.size() == expected.size(), "Unexpected number of lines");
        assertTrue(lines.equals(expected), "Unexpected content");
    }

    private void checkMalformedInputException(Stream<String> s) {
        try {
            List<String> lines = s.collect(Collectors.toList());
            fail("UncheckedIOException expected");
        } catch (UncheckedIOException ex) {
            IOException cause = ex.getCause();
            assertTrue(cause instanceof MalformedInputException,
                "MalformedInputException expected");
        }
    }

    private void checkNullPointerException(Callable<?> c) {
        try {
            c.call();
            fail("NullPointerException expected");
        } catch (NullPointerException ignore) {
        } catch (Exception e) {
            fail(e + " not expected");
        }
    }

394 395 396 397 398 399 400 401 402 403 404
    public void testDirectoryIteratorException() throws IOException {
        Path dir = testFolder.resolve("dir2");
        Path trigger = dir.resolve("DirectoryIteratorException");
        Files.createFile(trigger);
        FaultyFileSystem.FaultyFSProvider fsp = FaultyFileSystem.FaultyFSProvider.getInstance();
        FaultyFileSystem fs = (FaultyFileSystem) fsp.newFileSystem(dir, null);

        try {
            fsp.setFaultyMode(false);
            Path fakeRoot = fs.getRoot();
            try {
405
                try (Stream<Path> s = Files.list(fakeRoot)) {
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
                    s.forEach(path -> assertEquals(path.getFileName().toString(), "DirectoryIteratorException"));
                }
            } catch (UncheckedIOException uioe) {
                fail("Unexpected exception.");
            }

            fsp.setFaultyMode(true);
            try {
                try (DirectoryStream<Path> ds = Files.newDirectoryStream(fakeRoot)) {
                    Iterator<Path> itor = ds.iterator();
                    while (itor.hasNext()) {
                        itor.next();
                    }
                }
                fail("Shoule throw DirectoryIteratorException");
            } catch (DirectoryIteratorException die) {
            }

            try {
425
                try (Stream<Path> s = Files.list(fakeRoot)) {
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
                    s.forEach(path -> fail("should not get here"));
                }
            } catch (UncheckedIOException uioe) {
                assertTrue(uioe.getCause() instanceof FaultyFileSystem.FaultyException);
            } catch (DirectoryIteratorException die) {
                fail("Should have been converted into UncheckedIOException.");
            }
        } finally {
            // Cleanup
            if (fs != null) {
                fs.close();
            }
            Files.delete(trigger);
        }
    }

    public void testUncheckedIOException() throws IOException {
        Path triggerFile = testFolder.resolve(Paths.get("dir2", "IOException"));
        Files.createFile(triggerFile);
        Path triggerDir = testFolder.resolve(Paths.get("empty", "IOException"));
        Files.createDirectories(triggerDir);
        Files.createFile(triggerDir.resolve("file"));
        FaultyFileSystem.FaultyFSProvider fsp = FaultyFileSystem.FaultyFSProvider.getInstance();
        FaultyFileSystem fs = (FaultyFileSystem) fsp.newFileSystem(testFolder, null);

        try {
            fsp.setFaultyMode(false);
            Path fakeRoot = fs.getRoot();
454
            try (Stream<Path> s = Files.list(fakeRoot.resolve("dir2"))) {
455 456 457 458
                // only one file
                s.forEach(path -> assertEquals(path.getFileName().toString(), "IOException"));
            }

459
            try (Stream<Path> s = Files.walk(fakeRoot.resolve("empty"))) {
460 461 462 463 464 465 466
                String[] result = s.map(path -> path.getFileName().toString())
                                   .toArray(String[]::new);
                // ordered as depth-first
                assertEquals(result, new String[] { "empty", "IOException", "file"});
            }

            fsp.setFaultyMode(true);
467
            try (Stream<Path> s = Files.list(fakeRoot.resolve("dir2"))) {
468 469 470 471 472
                s.forEach(path -> fail("should have caused exception"));
            } catch (UncheckedIOException uioe) {
                assertTrue(uioe.getCause() instanceof FaultyFileSystem.FaultyException);
            }

473
            try (Stream<Path> s = Files.walk(fakeRoot.resolve("empty"))) {
474 475 476 477 478 479 480
                String[] result = s.map(path -> path.getFileName().toString())
                                   .toArray(String[]::new);
                fail("should not reach here due to IOException");
            } catch (UncheckedIOException uioe) {
                assertTrue(uioe.getCause() instanceof FaultyFileSystem.FaultyException);
            }

481
            try (Stream<Path> s = Files.walk(
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
                fakeRoot.resolve("empty").resolve("IOException")))
            {
                String[] result = s.map(path -> path.getFileName().toString())
                                   .toArray(String[]::new);
                fail("should not reach here due to IOException");
            } catch (IOException ioe) {
                assertTrue(ioe instanceof FaultyFileSystem.FaultyException);
            } catch (UncheckedIOException ex) {
                fail("Top level should be repored as is");
            }
         } finally {
            // Cleanup
            if (fs != null) {
                fs.close();
            }
            Files.delete(triggerFile);
            TestUtil.removeAll(triggerDir);
        }
    }

    public void testSecurityException() throws IOException {
503 504 505 506 507 508
        Path empty = testFolder.resolve("empty");
        Path triggerFile = Files.createFile(empty.resolve("SecurityException"));
        Path sampleFile = Files.createDirectories(empty.resolve("sample"));

        Path dir2 = testFolder.resolve("dir2");
        Path triggerDir = Files.createDirectories(dir2.resolve("SecurityException"));
509
        Files.createFile(triggerDir.resolve("fileInSE"));
510 511 512 513 514 515 516 517 518 519 520 521
        Path sample = Files.createFile(dir2.resolve("file"));

        Path triggerLink = null;
        Path linkTriggerDir = null;
        Path linkTriggerFile = null;
        if (supportsLinks) {
            Path dir = testFolder.resolve("dir");
            triggerLink = Files.createSymbolicLink(dir.resolve("SecurityException"), empty);
            linkTriggerDir = Files.createSymbolicLink(dir.resolve("lnDirSE"), triggerDir);
            linkTriggerFile = Files.createSymbolicLink(dir.resolve("lnFileSE"), triggerFile);
        }

522 523 524 525 526 527 528
        FaultyFileSystem.FaultyFSProvider fsp = FaultyFileSystem.FaultyFSProvider.getInstance();
        FaultyFileSystem fs = (FaultyFileSystem) fsp.newFileSystem(testFolder, null);

        try {
            fsp.setFaultyMode(false);
            Path fakeRoot = fs.getRoot();
            // validate setting
529
            try (Stream<Path> s = Files.list(fakeRoot.resolve("empty"))) {
530 531
                String[] result = s.map(path -> path.getFileName().toString())
                                   .toArray(String[]::new);
532
                assertEqualsNoOrder(result, new String[] { "SecurityException", "sample" });
533 534
            }

535
            try (Stream<Path> s = Files.walk(fakeRoot.resolve("dir2"))) {
536 537 538 539 540
                String[] result = s.map(path -> path.getFileName().toString())
                                   .toArray(String[]::new);
                assertEqualsNoOrder(result, new String[] { "dir2", "SecurityException", "fileInSE", "file" });
            }

541
            if (supportsLinks) {
542
                try (Stream<Path> s = Files.list(fakeRoot.resolve("dir"))) {
543 544 545 546 547 548
                    String[] result = s.map(path -> path.getFileName().toString())
                                       .toArray(String[]::new);
                    assertEqualsNoOrder(result, new String[] { "d1", "f1", "lnDir2", "SecurityException", "lnDirSE", "lnFileSE" });
                }
            }

549 550 551
            // execute test
            fsp.setFaultyMode(true);
            // ignore file cause SecurityException
552
            try (Stream<Path> s = Files.walk(fakeRoot.resolve("empty"))) {
553 554
                String[] result = s.map(path -> path.getFileName().toString())
                                   .toArray(String[]::new);
555
                assertEqualsNoOrder(result, new String[] { "empty", "sample" });
556 557
            }
            // skip folder cause SecurityException
558
            try (Stream<Path> s = Files.walk(fakeRoot.resolve("dir2"))) {
559 560 561 562 563
                String[] result = s.map(path -> path.getFileName().toString())
                                   .toArray(String[]::new);
                assertEqualsNoOrder(result, new String[] { "dir2", "file" });
            }

564 565
            if (supportsLinks) {
                // not following links
566
                try (Stream<Path> s = Files.walk(fakeRoot.resolve("dir"))) {
567 568 569 570 571 572
                    String[] result = s.map(path -> path.getFileName().toString())
                                       .toArray(String[]::new);
                    assertEqualsNoOrder(result, new String[] { "dir", "d1", "f1", "lnDir2", "lnDirSE", "lnFileSE" });
                }

                // following links
573
                try (Stream<Path> s = Files.walk(fakeRoot.resolve("dir"), FileVisitOption.FOLLOW_LINKS)) {
574 575 576 577 578 579 580 581
                    String[] result = s.map(path -> path.getFileName().toString())
                                       .toArray(String[]::new);
                    // ?? Should fileInSE show up?
                    // With FaultyFS, it does as no exception thrown for link to "SecurityException" with read on "lnXxxSE"
                    assertEqualsNoOrder(result, new String[] { "dir", "d1", "f1", "lnDir2", "file", "lnDirSE", "lnFileSE", "fileInSE" });
                }
            }

582
            // list instead of walk
583
            try (Stream<Path> s = Files.list(fakeRoot.resolve("empty"))) {
584 585
                String[] result = s.map(path -> path.getFileName().toString())
                                   .toArray(String[]::new);
586
                assertEqualsNoOrder(result, new String[] { "sample" });
587
            }
588
            try (Stream<Path> s = Files.list(fakeRoot.resolve("dir2"))) {
589 590 591 592 593 594
                String[] result = s.map(path -> path.getFileName().toString())
                                   .toArray(String[]::new);
                assertEqualsNoOrder(result, new String[] { "file" });
            }

            // root cause SecurityException should be reported
595
            try (Stream<Path> s = Files.walk(
596 597 598 599 600 601 602 603 604 605
                fakeRoot.resolve("dir2").resolve("SecurityException")))
            {
                String[] result = s.map(path -> path.getFileName().toString())
                                   .toArray(String[]::new);
                fail("should not reach here due to SecurityException");
            } catch (SecurityException se) {
                assertTrue(se.getCause() instanceof FaultyFileSystem.FaultyException);
            }

            // Walk a file cause SecurityException, we should get SE
606
            try (Stream<Path> s = Files.walk(
607 608 609 610 611 612 613 614 615 616
                fakeRoot.resolve("dir").resolve("SecurityException")))
            {
                String[] result = s.map(path -> path.getFileName().toString())
                                   .toArray(String[]::new);
                fail("should not reach here due to SecurityException");
            } catch (SecurityException se) {
                assertTrue(se.getCause() instanceof FaultyFileSystem.FaultyException);
            }

            // List a file cause SecurityException, we should get SE as cannot read attribute
617
            try (Stream<Path> s = Files.list(
618 619 620 621 622 623 624 625 626
                fakeRoot.resolve("dir2").resolve("SecurityException")))
            {
                String[] result = s.map(path -> path.getFileName().toString())
                                   .toArray(String[]::new);
                fail("should not reach here due to SecurityException");
            } catch (SecurityException se) {
                assertTrue(se.getCause() instanceof FaultyFileSystem.FaultyException);
            }

627
            try (Stream<Path> s = Files.list(
628 629 630 631 632 633 634 635 636 637 638 639 640
                fakeRoot.resolve("dir").resolve("SecurityException")))
            {
                String[] result = s.map(path -> path.getFileName().toString())
                                   .toArray(String[]::new);
                fail("should not reach here due to SecurityException");
            } catch (SecurityException se) {
                assertTrue(se.getCause() instanceof FaultyFileSystem.FaultyException);
            }
         } finally {
            // Cleanup
            if (fs != null) {
                fs.close();
            }
641 642 643 644 645
            if (supportsLinks) {
                Files.delete(triggerLink);
                Files.delete(linkTriggerDir);
                Files.delete(linkTriggerFile);
            }
646 647 648 649 650 651 652 653
            Files.delete(triggerFile);
            Files.delete(sampleFile);
            Files.delete(sample);
            TestUtil.removeAll(triggerDir);
        }
    }

    public void testConstructException() {
654
        try (Stream<String> s = Files.lines(testFolder.resolve("notExist"), Charset.forName("UTF-8"))) {
655 656 657 658 659 660 661
            s.forEach(l -> fail("File is not even exist!"));
        } catch (IOException ioe) {
            assertTrue(ioe instanceof NoSuchFileException);
        }
    }

    public void testClosedStream() throws IOException {
662
        try (Stream<Path> s = Files.list(testFolder)) {
663
            s.close();
664 665 666 667
            Object[] actual = s.sorted().toArray();
            fail("Operate on closed stream should throw IllegalStateException");
        } catch (IllegalStateException ex) {
            // expected
668 669
        }

670
        try (Stream<Path> s = Files.walk(testFolder)) {
671
            s.close();
672
            Object[] actual = s.sorted().toArray();
673 674 675 676 677
            fail("Operate on closed stream should throw IllegalStateException");
        } catch (IllegalStateException ex) {
            // expected
        }

678
        try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE,
679 680
                    (p, attr) -> true)) {
            s.close();
681
            Object[] actual = s.sorted().toArray();
682 683 684 685 686 687
            fail("Operate on closed stream should throw IllegalStateException");
        } catch (IllegalStateException ex) {
            // expected
        }
    }
}