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.io.UncheckedIOException;
25  import java.net.URI;
26  import java.net.URISyntaxException;
27  import java.net.URL;
28  import java.nio.file.Files;
29  import java.nio.file.Path;
30  import java.util.List;
31  import java.util.jar.JarEntry;
32  import java.util.jar.JarInputStream;
33  import java.util.stream.Collectors;
34  import java.util.stream.Stream;
35  
36  import org.apache.maven.shared.dependency.analyzer.asm.VisitClassException;
37  
38  /**
39   * Utility to visit classes in a library given either as a jar file or an exploded directory.
40   *
41   * @author <a href="mailto:markhobson@gmail.com">Mark Hobson</a>
42   */
43  public final class ClassFileVisitorUtils {
44  
45      private ClassFileVisitorUtils() {
46          // private constructor for utility class
47      }
48  
49      /**
50       * @param url the URL of the jar file or directory to visit
51       * @param visitor a {@link org.apache.maven.shared.dependency.analyzer.ClassFileVisitor} object
52       * @throws java.io.IOException I/O error or corrupt class file
53       */
54      public static void accept(URL url, ClassFileVisitor visitor) throws IOException {
55          if (url.getPath().endsWith(".jar")) {
56              acceptJar(url, visitor);
57          } else if (url.getProtocol().equalsIgnoreCase("file")) {
58              try {
59                  File file = new File(new URI(url.toString()));
60  
61                  if (file.isDirectory()) {
62                      acceptDirectory(file, visitor);
63                  } else if (file.exists()) {
64                      throw new IllegalArgumentException("Cannot accept visitor on URL: " + url);
65                  }
66              } catch (URISyntaxException exception) {
67                  throw new IllegalArgumentException("Cannot accept visitor on URL: " + url, exception);
68              }
69          } else {
70              throw new IllegalArgumentException("Cannot accept visitor on URL: " + url);
71          }
72      }
73  
74      // private methods --------------------------------------------------------
75  
76      private static void acceptJar(URL url, ClassFileVisitor visitor) throws IOException {
77          try (JarInputStream in = new JarInputStream(url.openStream())) {
78              JarEntry entry;
79              while ((entry = in.getNextJarEntry()) != null) {
80                  String name = entry.getName();
81                  // ignore files like package-info.class and module-info.class
82                  if (name.endsWith(".class") && name.indexOf('-') == -1) {
83                      // Jars(ZIP) always use / as the separator character
84                      visitClass(name, in, visitor, '/');
85                  }
86              }
87          }
88      }
89  
90      private static void acceptDirectory(File directory, ClassFileVisitor visitor) throws IOException {
91          try (Stream<Path> walk = Files.walk(directory.toPath())) {
92              List<Path> classFiles = walk.filter(
93                              path -> path.getFileName().toString().endsWith(".class"))
94                      .collect(Collectors.toList());
95              for (Path path : classFiles) {
96                  try (InputStream in = Files.newInputStream(path)) {
97                      try {
98                          visitClass(directory, path, in, visitor);
99                      } catch (IOException e) {
100                         throw new IOException(
101                                 String.format("%s from directory = %s, path = %s", e.getMessage(), directory, path), e);
102                     }
103                 }
104             }
105         }
106     }
107 
108     private static void visitClass(File baseDirectory, Path path, InputStream in, ClassFileVisitor visitor)
109             throws IOException {
110         // getPath() returns a String, not a java.nio.file.Path
111         String stringPath =
112                 path.toFile().getPath().substring(baseDirectory.getPath().length() + 1);
113         visitClass(stringPath, in, visitor, File.separatorChar);
114     }
115 
116     private static void visitClass(String stringPath, InputStream in, ClassFileVisitor visitor, char separator)
117             throws IOException {
118         String className = stringPath.substring(0, stringPath.length() - 6);
119 
120         className = className.replace(separator, '.');
121 
122         try {
123             visitor.visitClass(className, in);
124         } catch (UncheckedIOException e) {
125             throw e.getCause();
126         } catch (VisitClassException e) {
127             throw new IOException(e);
128         }
129     }
130 }