Path: blob/master/test/jdk/java/nio/file/Files/walkFileTree/SkipSiblings.java
41155 views
/*1* Copyright (c) 2008, 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_SIBLINGS return value26* @library ../..27* @compile SkipSiblings.java CreateFileTree.java28* @run main SkipSiblings29* @key randomness30*/3132import java.nio.file.*;33import java.nio.file.attribute.*;34import java.io.IOException;35import java.util.*;3637public class SkipSiblings {3839static final Random rand = new Random();40static final Set<Path> skipped = new HashSet<Path>();4142// check if this path's directory has been skipped43static void check(Path path) {44if (skipped.contains(path.getParent()))45throw new RuntimeException(path + " should not have been visited");46}4748// indicates if the siblings of this path should be skipped49static boolean skip(Path path) {50Path parent = path.getParent();51if (parent != null && rand.nextBoolean()) {52skipped.add(parent);53return true;54}55return false;56}5758public static void main(String[] args) throws Exception {59Path top = CreateFileTree.create();60try {61test(top);62} finally {63TestUtil.removeAll(top);64}65}6667static void test(final Path start) throws IOException {68Files.walkFileTree(start, new SimpleFileVisitor<Path>() {69@Override70public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {71check(dir);72if (skip(dir))73return FileVisitResult.SKIP_SIBLINGS;74return FileVisitResult.CONTINUE;75}76@Override77public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {78check(file);79if (skip(file))80return FileVisitResult.SKIP_SIBLINGS;81return FileVisitResult.CONTINUE;82}83@Override84public FileVisitResult postVisitDirectory(Path dir, IOException x) {85if (x != null)86throw new RuntimeException(x);87check(dir);88if (rand.nextBoolean()) {89return FileVisitResult.CONTINUE;90} else {91return FileVisitResult.SKIP_SIBLINGS;92}93}94});95}96}979899