1 /* 2 * Copyright (c) 2013, 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. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 */ 23 24 /* 25 * @test 26 * @summary Unit test for Files.walkFileTree to test SKIP_SUBTREE return value 27 * @library ../.. 28 * @compile SkipSubtree.java CreateFileTree.java 29 * @run main SkipSubtree 30 */ 31 import java.nio.file.*; 32 import java.nio.file.attribute.BasicFileAttributes; 33 import java.io.IOException; 34 import java.util.HashSet; 35 import java.util.Random; 36 import java.util.Set; 37 38 public class SkipSubtree { 39 40 static final Random rand = new Random(); 41 static final Set<Path> skipped = new HashSet<>(); 42 43 // check if this path should have been skipped 44 static void check(Path path) { 45 do { 46 if (skipped.contains(path)) 47 throw new RuntimeException(path + " should not have been visited"); 48 path = path.getParent(); 49 } while (path != null); 50 } 51 52 // indicates if the subtree should be skipped 53 static boolean skip(Path path) { 54 if (rand.nextInt(3) == 0) { 55 skipped.add(path); 56 return true; 57 } 58 return false; 59 } 60 61 public static void main(String[] args) throws Exception { 62 Path top = CreateFileTree.create(); 63 try { 64 test(top); 65 } finally { 66 TestUtil.removeAll(top); 67 } 68 } 69 70 static void test(final Path start) throws IOException { 71 Files.walkFileTree(start, new SimpleFileVisitor<Path>() { 72 @Override 73 public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) { 74 check(dir); 75 if (skip(dir)) 76 return FileVisitResult.SKIP_SUBTREE; 77 return FileVisitResult.CONTINUE; 78 } 79 @Override 80 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { 81 check(file); 82 return FileVisitResult.CONTINUE; 83 } 84 @Override 85 public FileVisitResult postVisitDirectory(Path dir, IOException x) { 86 if (x != null) 87 throw new RuntimeException(x); 88 check(dir); 89 return FileVisitResult.CONTINUE; 90 } 91 }); 92 } 93 }