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 * @key randomness 31 */ 32 import java.nio.file.*; 33 import java.nio.file.attribute.BasicFileAttributes; 34 import java.io.IOException; 35 import java.util.HashSet; 36 import java.util.Random; 37 import java.util.Set; 38 39 public class SkipSubtree { 40 41 static final Random rand = new Random(); 42 static final Set<Path> skipped = new HashSet<>(); 43 44 // check if this path should have been skipped 45 static void check(Path path) { 46 do { 47 if (skipped.contains(path)) 48 throw new RuntimeException(path + " should not have been visited"); 49 path = path.getParent(); 50 } while (path != null); 51 } 52 53 // indicates if the subtree should be skipped 54 static boolean skip(Path path) { 55 if (rand.nextInt(3) == 0) { 56 skipped.add(path); 57 return true; 58 } 59 return false; 60 } 61 62 public static void main(String[] args) throws Exception { 63 Path top = CreateFileTree.create(); 64 try { 65 test(top); 66 } finally { 67 TestUtil.removeAll(top); 68 } 69 } 70 71 static void test(final Path start) throws IOException { 72 Files.walkFileTree(start, new SimpleFileVisitor<Path>() { 73 @Override 74 public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) { 75 check(dir); 76 if (skip(dir)) 77 return FileVisitResult.SKIP_SUBTREE; 78 return FileVisitResult.CONTINUE; 79 } 80 @Override 81 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { 82 check(file); 83 return FileVisitResult.CONTINUE; 84 } 85 @Override 86 public FileVisitResult postVisitDirectory(Path dir, IOException x) { 87 if (x != null) 88 throw new RuntimeException(x); 89 check(dir); 90 return FileVisitResult.CONTINUE; 91 } 92 }); 93 } 94 }