1 /*
   2  * Copyright (c) 2017, 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 package jdk.tools.jaotc.collect;
  25 
  26 import java.io.IOException;
  27 import java.nio.file.*;
  28 import java.nio.file.attribute.BasicFileAttributes;
  29 import java.util.ArrayList;
  30 import java.util.Iterator;
  31 
  32 import static java.nio.file.FileVisitResult.CONTINUE;
  33 
  34 /**
  35  * {@link FileVisitor} implementation to find class files recursively.
  36  */
  37 public final class FileSystemFinder extends SimpleFileVisitor<Path> implements Iterable<Path> {
  38     private final ArrayList<Path> fileNames = new ArrayList<>();
  39     private final PathMatcher filter;
  40 
  41     public FileSystemFinder(Path combinedPath, PathMatcher filter) {
  42         this.filter = filter;
  43         try {
  44             Files.walkFileTree(combinedPath, this);
  45         } catch (IOException e) {
  46             throw new InternalError(e);
  47         }
  48     }
  49 
  50     /**
  51      * Compares the glob pattern against the file name.
  52      */
  53     private void find(Path file) {
  54         Path name = file.getFileName();
  55         if (name != null && filter.matches(name)) {
  56             fileNames.add(file);
  57         }
  58     }
  59 
  60     @Override
  61     public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
  62         find(file);
  63         return CONTINUE;
  64     }
  65 
  66     @Override
  67     public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
  68         find(dir);
  69         return CONTINUE;
  70     }
  71 
  72     @Override
  73     public Iterator<Path> iterator() {
  74         return fileNames.iterator();
  75     }
  76 }