View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.maven.shared.dependency.analyzer;
20  
21  import java.io.File;
22  import java.io.IOException;
23  import java.io.InputStream;
24  import java.net.URI;
25  import java.net.URISyntaxException;
26  import java.net.URL;
27  import java.nio.file.Files;
28  import java.nio.file.Path;
29  import java.util.List;
30  import java.util.jar.JarEntry;
31  import java.util.jar.JarInputStream;
32  import java.util.stream.Collectors;
33  import java.util.stream.Stream;
34  
35  /**
36   * Utility to visit classes in a library given either as a jar file or an exploded directory.
37   *
38   * @author <a href="mailto:markhobson@gmail.com">Mark Hobson</a>
39   */
40  public final class ClassFileVisitorUtils {
41  
42      private ClassFileVisitorUtils() {
43          // private constructor for utility class
44      }
45  
46      /**
47       * @param url     a {@link java.net.URL} object
48       * @param visitor a {@link org.apache.maven.shared.dependency.analyzer.ClassFileVisitor} object
49       * @throws java.io.IOException if any
50       */
51      public static void accept(URL url, ClassFileVisitor visitor) throws IOException {
52          if (url.getPath().endsWith(".jar")) {
53              acceptJar(url, visitor);
54          } else if (url.getProtocol().equalsIgnoreCase("file")) {
55              try {
56                  File file = new File(new URI(url.toString()));
57  
58                  if (file.isDirectory()) {
59                      acceptDirectory(file, visitor);
60                  } else if (file.exists()) {
61                      throw new IllegalArgumentException("Cannot accept visitor on URL: " + url);
62                  }
63              } catch (URISyntaxException exception) {
64                  throw new IllegalArgumentException("Cannot accept visitor on URL: " + url, exception);
65              }
66          } else {
67              throw new IllegalArgumentException("Cannot accept visitor on URL: " + url);
68          }
69      }
70  
71      // private methods --------------------------------------------------------
72  
73      private static void acceptJar(URL url, ClassFileVisitor visitor) throws IOException {
74          try (JarInputStream in = new JarInputStream(url.openStream())) {
75              JarEntry entry;
76              while ((entry = in.getNextJarEntry()) != null) {
77                  String name = entry.getName();
78                  // ignore files like package-info.class and module-info.class
79                  if (name.endsWith(".class") && name.indexOf('-') == -1) {
80                      // Jars(ZIP) always use / as the separator character
81                      visitClass(name, in, visitor, '/');
82                  }
83              }
84          }
85      }
86  
87      private static void acceptDirectory(File directory, ClassFileVisitor visitor) throws IOException {
88  
89          List<Path> classFiles;
90          try (Stream<Path> walk = Files.walk(directory.toPath())) {
91              classFiles = walk.filter(path -> path.getFileName().toString().endsWith(".class"))
92                      .collect(Collectors.toList());
93          }
94  
95          for (Path path : classFiles) {
96              try (InputStream in = Files.newInputStream(path)) {
97                  try {
98                      visitClass(directory, path, in, visitor);
99                  } catch (RuntimeException e) {
100                     // visitClass throws RuntimeException
101                     throw new RuntimeException(
102                             String.format("%s from directory = %s, path = %s", e.getMessage(), directory, path), e);
103                 }
104             }
105         }
106     }
107 
108     private static void visitClass(File baseDirectory, Path path, InputStream in, ClassFileVisitor visitor) {
109         // getPath() returns a String, not a java.nio.file.Path
110         String stringPath =
111                 path.toFile().getPath().substring(baseDirectory.getPath().length() + 1);
112         visitClass(stringPath, in, visitor, File.separatorChar);
113     }
114 
115     private static void visitClass(String stringPath, InputStream in, ClassFileVisitor visitor, char separator) {
116         String className = stringPath.substring(0, stringPath.length() - 6);
117 
118         className = className.replace(separator, '.');
119 
120         visitor.visitClass(className, in);
121     }
122 }