Path: blob/master/test/jdk/java/nio/file/Files/walkFileTree/SkipSubtree.java
41155 views
/*1* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/*24* @test25* @summary Unit test for Files.walkFileTree to test SKIP_SUBTREE return value26* @library ../..27* @compile SkipSubtree.java CreateFileTree.java28* @run main SkipSubtree29* @key randomness30*/31import java.nio.file.*;32import java.nio.file.attribute.BasicFileAttributes;33import java.io.IOException;34import java.util.HashSet;35import java.util.Random;36import java.util.Set;3738public class SkipSubtree {3940static final Random rand = new Random();41static final Set<Path> skipped = new HashSet<>();4243// check if this path should have been skipped44static void check(Path path) {45do {46if (skipped.contains(path))47throw new RuntimeException(path + " should not have been visited");48path = path.getParent();49} while (path != null);50}5152// indicates if the subtree should be skipped53static boolean skip(Path path) {54if (rand.nextInt(3) == 0) {55skipped.add(path);56return true;57}58return false;59}6061public static void main(String[] args) throws Exception {62Path top = CreateFileTree.create();63try {64test(top);65} finally {66TestUtil.removeAll(top);67}68}6970static void test(final Path start) throws IOException {71Files.walkFileTree(start, new SimpleFileVisitor<Path>() {72@Override73public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {74check(dir);75if (skip(dir))76return FileVisitResult.SKIP_SUBTREE;77return FileVisitResult.CONTINUE;78}79@Override80public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {81check(file);82return FileVisitResult.CONTINUE;83}84@Override85public FileVisitResult postVisitDirectory(Path dir, IOException x) {86if (x != null)87throw new RuntimeException(x);88check(dir);89return FileVisitResult.CONTINUE;90}91});92}93}949596