This is an automated email from the ASF dual-hosted git repository.
slachiewicz pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/maven-dependency-analyzer.git
The following commit(s) were added to refs/heads/master by this push:
new c9e6727 Add class entry source abstraction for dependency analysis
c9e6727 is described below
commit c9e6727e848492c7239b97f1fbc057661f43b2b7
Author: Sylwester Lachiewicz <[email protected]>
AuthorDate: Thu Nov 19 14:09:40 2026 +0100
Add class entry source abstraction for dependency analysis
---
.../dependency/analyzer/BytesClassEntrySource.java | 65 ++++++++++
.../shared/dependency/analyzer/ClassAnalyzer.java | 28 +++++
.../shared/dependency/analyzer/ClassEntries.java | 69 +++++++++++
.../{ClassAnalyzer.java => ClassEntry.java} | 29 ++---
.../dependency/analyzer/ClassEntrySource.java | 51 ++++++++
.../dependency/analyzer/ClassFileVisitorUtils.java | 94 +++++---------
.../dependency/analyzer/DefaultClassAnalyzer.java | 21 +++-
.../dependency/analyzer/DependencyAnalyzer.java | 45 +++++++
.../dependency/analyzer/PathClassEntrySource.java | 110 +++++++++++++++++
.../dependency/analyzer/UrlClassEntrySource.java | 94 ++++++++++++++
.../analyzer/asm/ASMDependencyAnalyzer.java | 22 +++-
.../dependency/analyzer/ClassEntrySourceTest.java | 135 +++++++++++++++++++++
.../analyzer/ClassFileVisitorUtilsTest.java | 17 +--
.../analyzer/DefaultClassAnalyzerTest.java | 11 +-
14 files changed, 683 insertions(+), 108 deletions(-)
diff --git
a/src/main/java/org/apache/maven/shared/dependency/analyzer/BytesClassEntrySource.java
b/src/main/java/org/apache/maven/shared/dependency/analyzer/BytesClassEntrySource.java
new file mode 100644
index 0000000..26b946b
--- /dev/null
+++
b/src/main/java/org/apache/maven/shared/dependency/analyzer/BytesClassEntrySource.java
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.maven.shared.dependency.analyzer;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.jar.JarEntry;
+import java.util.jar.JarInputStream;
+import java.util.stream.Stream;
+
+/**
+ * A {@link ClassEntrySource} backed by the bytes of a JAR held in memory.
+ *
+ * @since 1.18.0
+ */
+public final class BytesClassEntrySource implements ClassEntrySource {
+
+ private final byte[] bytes;
+
+ /**
+ * Creates a source over the bytes of a JAR file.
+ *
+ * @param bytes the JAR contents, must not be {@code null}
+ */
+ public BytesClassEntrySource(byte[] bytes) {
+ if (bytes == null) {
+ throw new IllegalArgumentException("bytes are required");
+ }
+ this.bytes = bytes;
+ }
+
+ @Override
+ public Stream<ClassEntry> classes() throws IOException {
+ List<ClassEntry> entries = new ArrayList<>();
+ try (JarInputStream in = new JarInputStream(new
ByteArrayInputStream(bytes))) {
+ JarEntry entry;
+ while ((entry = in.getNextJarEntry()) != null) {
+ if (ClassEntries.isClassEntry(entry.getName())) {
+ byte[] content = ClassEntries.readAll(in);
+ entries.add(new ClassEntries.StreamClassEntry(
+ entry.getName(), () -> new
ByteArrayInputStream(content)));
+ }
+ }
+ }
+ return entries.stream();
+ }
+}
diff --git
a/src/main/java/org/apache/maven/shared/dependency/analyzer/ClassAnalyzer.java
b/src/main/java/org/apache/maven/shared/dependency/analyzer/ClassAnalyzer.java
index 411033f..44123c6 100644
---
a/src/main/java/org/apache/maven/shared/dependency/analyzer/ClassAnalyzer.java
+++
b/src/main/java/org/apache/maven/shared/dependency/analyzer/ClassAnalyzer.java
@@ -20,6 +20,7 @@ package org.apache.maven.shared.dependency.analyzer;
import java.io.IOException;
import java.net.URL;
+import java.nio.file.Path;
import java.util.Set;
/**
@@ -49,4 +50,31 @@ public interface ClassAnalyzer {
* @throws java.io.IOException if any
*/
Set<String> analyze(URL url, ClassesPatterns excludedClasses) throws
IOException;
+
+ /**
+ * Analyzes a JAR file or directory identified by a local path.
+ *
+ * @param path the JAR file or directory to analyze
+ * @return the class names found in the source
+ * @throws IOException if the source cannot be read
+ * @since 1.18.0
+ */
+ default Set<String> analyze(Path path) throws IOException {
+ return analyze(path, new ClassesPatterns());
+ }
+
+ /**
+ * Analyzes a JAR file or directory identified by a local path, excluding
matching classes.
+ *
+ * @param path the JAR file or directory to analyze
+ * @param excludedClasses patterns of classes to exclude
+ * @return the class names found in the source
+ * @throws IOException if the source cannot be read
+ * @since 1.18.0
+ */
+ default Set<String> analyze(Path path, ClassesPatterns excludedClasses)
throws IOException {
+ CollectorClassFileVisitor visitor = new
CollectorClassFileVisitor(excludedClasses);
+ ClassFileVisitorUtils.accept(new PathClassEntrySource(path), visitor);
+ return visitor.getClasses();
+ }
}
diff --git
a/src/main/java/org/apache/maven/shared/dependency/analyzer/ClassEntries.java
b/src/main/java/org/apache/maven/shared/dependency/analyzer/ClassEntries.java
new file mode 100644
index 0000000..b7f2805
--- /dev/null
+++
b/src/main/java/org/apache/maven/shared/dependency/analyzer/ClassEntries.java
@@ -0,0 +1,69 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.maven.shared.dependency.analyzer;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+final class ClassEntries {
+
+ private ClassEntries() {
+ // utility class
+ }
+
+ static boolean isClassEntry(String name) {
+ // the '-' check excludes package-info.class and module-info.class
+ return name.endsWith(".class") && name.indexOf('-') == -1;
+ }
+
+ static byte[] readAll(InputStream in) throws IOException {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ byte[] buffer = new byte[8192];
+ int read;
+ while ((read = in.read(buffer)) != -1) {
+ out.write(buffer, 0, read);
+ }
+ return out.toByteArray();
+ }
+
+ static final class StreamClassEntry implements ClassEntry {
+ private final String name;
+ private final InputStreamSupplier supplier;
+
+ StreamClassEntry(String name, InputStreamSupplier supplier) {
+ this.name = name;
+ this.supplier = supplier;
+ }
+
+ @Override
+ public String name() {
+ return name;
+ }
+
+ @Override
+ public InputStream open() throws IOException {
+ return supplier.get();
+ }
+ }
+
+ interface InputStreamSupplier {
+ InputStream get() throws IOException;
+ }
+}
diff --git
a/src/main/java/org/apache/maven/shared/dependency/analyzer/ClassAnalyzer.java
b/src/main/java/org/apache/maven/shared/dependency/analyzer/ClassEntry.java
similarity index 53%
copy from
src/main/java/org/apache/maven/shared/dependency/analyzer/ClassAnalyzer.java
copy to
src/main/java/org/apache/maven/shared/dependency/analyzer/ClassEntry.java
index 411033f..75f18f6 100644
---
a/src/main/java/org/apache/maven/shared/dependency/analyzer/ClassAnalyzer.java
+++ b/src/main/java/org/apache/maven/shared/dependency/analyzer/ClassEntry.java
@@ -19,34 +19,27 @@
package org.apache.maven.shared.dependency.analyzer;
import java.io.IOException;
-import java.net.URL;
-import java.util.Set;
+import java.io.InputStream;
/**
- * Gets the set of classes contained in a library given either as a jar file
or an exploded directory.
+ * One class file found by a {@link ClassEntrySource}.
*
- * @author <a href="mailto:[email protected]">Mark Hobson</a>
+ * @since 1.18.0
*/
-public interface ClassAnalyzer {
+public interface ClassEntry {
/**
- * <p>analyze.</p>
+ * Returns the entry name using '/' as the separator, with the {@code
.class} suffix included.
*
- * @param url the JAR file or directory to analyze
- * @return a {@link java.util.Set} object
- * @throws java.io.IOException if any
+ * @return the entry name
*/
- default Set<String> analyze(URL url) throws IOException {
- return analyze(url, new ClassesPatterns());
- }
+ String name();
/**
- * <p>analyze.</p>
+ * Opens the class file contents. The caller must close the returned
stream.
*
- * @param url the JAR file or directory to analyze
- * @param excludedClasses patterns of classes to exclude
- * @return a {@link java.util.Set} object
- * @throws java.io.IOException if any
+ * @return a stream over the class bytes
+ * @throws IOException if the bytes cannot be opened
*/
- Set<String> analyze(URL url, ClassesPatterns excludedClasses) throws
IOException;
+ InputStream open() throws IOException;
}
diff --git
a/src/main/java/org/apache/maven/shared/dependency/analyzer/ClassEntrySource.java
b/src/main/java/org/apache/maven/shared/dependency/analyzer/ClassEntrySource.java
new file mode 100644
index 0000000..d8cd780
--- /dev/null
+++
b/src/main/java/org/apache/maven/shared/dependency/analyzer/ClassEntrySource.java
@@ -0,0 +1,51 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.maven.shared.dependency.analyzer;
+
+import java.io.IOException;
+import java.util.stream.Stream;
+
+/**
+ * A source of class files for dependency analysis. Implementations may read a
JAR file, an exploded
+ * directory, a URL, or bytes held in memory. The source must be closed after
its entries have been
+ * consumed; {@link ClassFileVisitorUtils#accept(ClassEntrySource,
ClassFileVisitor)} does that for callers.
+ *
+ * @since 1.18.0
+ */
+public interface ClassEntrySource extends AutoCloseable {
+
+ /**
+ * Returns the class entries in this source. Package-info and module-info
classes, and any entry
+ * whose name contains a '-', are excluded by the implementations.
+ *
+ * @return a stream of class entries
+ * @throws IOException if the entries cannot be enumerated
+ */
+ Stream<ClassEntry> classes() throws IOException;
+
+ /**
+ * Releases resources held by this source. The default implementation does
nothing.
+ *
+ * @throws IOException if the resources cannot be released
+ */
+ @Override
+ default void close() throws IOException {
+ // no resources by default
+ }
+}
diff --git
a/src/main/java/org/apache/maven/shared/dependency/analyzer/ClassFileVisitorUtils.java
b/src/main/java/org/apache/maven/shared/dependency/analyzer/ClassFileVisitorUtils.java
index 89589e8..69348c5 100644
---
a/src/main/java/org/apache/maven/shared/dependency/analyzer/ClassFileVisitorUtils.java
+++
b/src/main/java/org/apache/maven/shared/dependency/analyzer/ClassFileVisitorUtils.java
@@ -18,20 +18,12 @@
*/
package org.apache.maven.shared.dependency.analyzer;
-import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
-import java.net.URI;
-import java.net.URISyntaxException;
import java.net.URL;
-import java.nio.file.Files;
import java.nio.file.Path;
-import java.util.List;
-import java.util.jar.JarEntry;
-import java.util.jar.JarInputStream;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
+import java.util.Iterator;
import org.apache.maven.shared.dependency.analyzer.asm.VisitClassException;
@@ -47,71 +39,51 @@ public final class ClassFileVisitorUtils {
}
/**
- * @param url the URL of the jar file or directory to visit
+ * Visits the classes exposed by a {@link ClassEntrySource} and closes the
source afterwards.
+ * This is the common implementation for local paths, URLs and in-memory
archives.
+ *
+ * @param source the class entry source to visit
* @param visitor a {@link
org.apache.maven.shared.dependency.analyzer.ClassFileVisitor} object
* @throws java.io.IOException I/O error or corrupt class file
+ * @since 1.18.0
*/
- public static void accept(URL url, ClassFileVisitor visitor) throws
IOException {
- if (url.getPath().endsWith(".jar")) {
- acceptJar(url, visitor);
- } else if (url.getProtocol().equalsIgnoreCase("file")) {
- try {
- File file = new File(new URI(url.toString()));
-
- if (file.isDirectory()) {
- acceptDirectory(file, visitor);
- } else if (file.exists()) {
- throw new IllegalArgumentException("Cannot accept visitor
on URL: " + url);
+ public static void accept(ClassEntrySource source, ClassFileVisitor
visitor) throws IOException {
+ try (ClassEntrySource closeable = source) {
+ Iterator<ClassEntry> iterator = source.classes().iterator();
+ while (iterator.hasNext()) {
+ ClassEntry entry = iterator.next();
+ try (InputStream in = entry.open()) {
+ visitClass(entry.name(), in, visitor, '/');
}
- } catch (URISyntaxException exception) {
- throw new IllegalArgumentException("Cannot accept visitor on
URL: " + url, exception);
}
- } else {
- throw new IllegalArgumentException("Cannot accept visitor on URL:
" + url);
}
}
- // private methods --------------------------------------------------------
-
- private static void acceptJar(URL url, ClassFileVisitor visitor) throws
IOException {
- try (JarInputStream in = new JarInputStream(url.openStream())) {
- JarEntry entry;
- while ((entry = in.getNextJarEntry()) != null) {
- String name = entry.getName();
- // ignore files like package-info.class and module-info.class
- if (name.endsWith(".class") && name.indexOf('-') == -1) {
- // Jars(ZIP) always use / as the separator character
- visitClass(name, in, visitor, '/');
- }
- }
- }
+ /**
+ * Visits the classes of a local JAR file or directory.
+ *
+ * @param path the JAR file or directory to visit
+ * @param visitor a {@link
org.apache.maven.shared.dependency.analyzer.ClassFileVisitor} object
+ * @throws java.io.IOException I/O error or corrupt class file
+ * @since 1.18.0
+ */
+ public static void accept(Path path, ClassFileVisitor visitor) throws
IOException {
+ accept(new PathClassEntrySource(path), visitor);
}
- private static void acceptDirectory(File directory, ClassFileVisitor
visitor) throws IOException {
- try (Stream<Path> walk = Files.walk(directory.toPath())) {
- List<Path> classFiles = walk.filter(
- path ->
path.getFileName().toString().endsWith(".class"))
- .collect(Collectors.toList());
- for (Path path : classFiles) {
- try (InputStream in = Files.newInputStream(path)) {
- try {
- visitClass(directory, path, in, visitor);
- } catch (IOException e) {
- throw new IOException(
- String.format("%s from directory = %s, path =
%s", e.getMessage(), directory, path), e);
- }
- }
- }
+ /**
+ * @param url the URL of the jar file or directory to visit
+ * @param visitor a {@link
org.apache.maven.shared.dependency.analyzer.ClassFileVisitor} object
+ * @throws java.io.IOException I/O error or corrupt class file
+ */
+ public static void accept(URL url, ClassFileVisitor visitor) throws
IOException {
+ if (!url.getPath().endsWith(".jar") &&
!"file".equalsIgnoreCase(url.getProtocol())) {
+ throw new IllegalArgumentException("Cannot accept visitor on URL:
" + url);
}
+ accept(new UrlClassEntrySource(url), visitor);
}
- private static void visitClass(File baseDirectory, Path path, InputStream
in, ClassFileVisitor visitor)
- throws IOException {
- // getPath() returns a String, not a java.nio.file.Path
- String stringPath =
-
path.toFile().getPath().substring(baseDirectory.getPath().length() + 1);
- visitClass(stringPath, in, visitor, File.separatorChar);
- }
+ // private methods --------------------------------------------------------
private static void visitClass(String stringPath, InputStream in,
ClassFileVisitor visitor, char separator)
throws IOException {
diff --git
a/src/main/java/org/apache/maven/shared/dependency/analyzer/DefaultClassAnalyzer.java
b/src/main/java/org/apache/maven/shared/dependency/analyzer/DefaultClassAnalyzer.java
index 4302279..0f4b50d 100644
---
a/src/main/java/org/apache/maven/shared/dependency/analyzer/DefaultClassAnalyzer.java
+++
b/src/main/java/org/apache/maven/shared/dependency/analyzer/DefaultClassAnalyzer.java
@@ -35,12 +35,25 @@ import java.util.zip.ZipException;
@Singleton
public class DefaultClassAnalyzer implements ClassAnalyzer {
- @Override
- public Set<String> analyze(URL url, ClassesPatterns excludedClasses)
throws IOException {
+ /**
+ * Analyzes the classes exposed by a source. Uses the same collector and
filtering rules as the URL form.
+ *
+ * @param source the class entry source to analyze
+ * @param excludedClasses patterns of classes to exclude
+ * @return the class names found in the source
+ * @throws IOException if the source cannot be read
+ * @since 1.18.0
+ */
+ public Set<String> analyze(ClassEntrySource source, ClassesPatterns
excludedClasses) throws IOException {
CollectorClassFileVisitor visitor = new
CollectorClassFileVisitor(excludedClasses);
+ ClassFileVisitorUtils.accept(source, visitor);
+ return visitor.getClasses();
+ }
+ @Override
+ public Set<String> analyze(URL url, ClassesPatterns excludedClasses)
throws IOException {
try {
- ClassFileVisitorUtils.accept(url, visitor);
+ return analyze(new UrlClassEntrySource(url), excludedClasses);
} catch (ZipException e) {
// since the current ZipException gives no indication what jar
file is corrupted
// we prefer to wrap another ZipException for better error
visibility
@@ -48,7 +61,5 @@ public class DefaultClassAnalyzer implements ClassAnalyzer {
ze.initCause(e);
throw ze;
}
-
- return visitor.getClasses();
}
}
diff --git
a/src/main/java/org/apache/maven/shared/dependency/analyzer/DependencyAnalyzer.java
b/src/main/java/org/apache/maven/shared/dependency/analyzer/DependencyAnalyzer.java
index d203ce4..19f8410 100644
---
a/src/main/java/org/apache/maven/shared/dependency/analyzer/DependencyAnalyzer.java
+++
b/src/main/java/org/apache/maven/shared/dependency/analyzer/DependencyAnalyzer.java
@@ -20,9 +20,12 @@ package org.apache.maven.shared.dependency.analyzer;
import java.io.IOException;
import java.net.URL;
+import java.nio.file.Path;
import java.util.Set;
import java.util.stream.Collectors;
+import
org.apache.maven.shared.dependency.analyzer.asm.DependencyClassFileVisitor;
+
/**
* Gets the set of classes referenced by a library given either as a jar file
or an exploded directory.
*
@@ -65,4 +68,46 @@ public interface DependencyAnalyzer {
* @throws IOException if an error occurs reading a JAR or .class file
*/
Set<DependencyUsage> analyzeUsages(URL url, ClassesPatterns
excludeClasses) throws IOException;
+
+ /**
+ * Analyzes a JAR file or directory identified by a local path.
+ *
+ * @param path the JAR file or directory to analyze
+ * @return the set of class names referenced by the library
+ * @throws IOException if an error occurs reading a JAR or .class file
+ * @since 1.18.0
+ */
+ default Set<String> analyze(Path path) throws IOException {
+ return analyze(path, new ClassesPatterns());
+ }
+
+ /**
+ * Analyzes a JAR file or directory identified by a local path, excluding
matching classes.
+ *
+ * @param path the JAR file or directory to analyze
+ * @param excludeClasses a class list to exclude
+ * @return the set of class names referenced by the library
+ * @throws IOException if an error occurs reading a JAR or .class file
+ * @since 1.18.0
+ */
+ default Set<String> analyze(Path path, ClassesPatterns excludeClasses)
throws IOException {
+ return analyzeUsages(path, excludeClasses).stream()
+ .map(DependencyUsage::getDependencyClass)
+ .collect(Collectors.toSet());
+ }
+
+ /**
+ * Returns referenced classes paired with their declaring classes for a
local path.
+ *
+ * @param path the JAR file or directory to analyze
+ * @param excludeClasses patterns of classes to exclude
+ * @return the referenced classes and their declaring classes
+ * @throws IOException if an error occurs reading a JAR or .class file
+ * @since 1.18.0
+ */
+ default Set<DependencyUsage> analyzeUsages(Path path, ClassesPatterns
excludeClasses) throws IOException {
+ DependencyClassFileVisitor visitor = new
DependencyClassFileVisitor(excludeClasses);
+ ClassFileVisitorUtils.accept(new PathClassEntrySource(path), visitor);
+ return visitor.getDependencyUsages();
+ }
}
diff --git
a/src/main/java/org/apache/maven/shared/dependency/analyzer/PathClassEntrySource.java
b/src/main/java/org/apache/maven/shared/dependency/analyzer/PathClassEntrySource.java
new file mode 100644
index 0000000..fdb49ad
--- /dev/null
+++
b/src/main/java/org/apache/maven/shared/dependency/analyzer/PathClassEntrySource.java
@@ -0,0 +1,110 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.maven.shared.dependency.analyzer;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+/**
+ * A {@link ClassEntrySource} backed by a local JAR file or an exploded
directory.
+ *
+ * @since 1.18.0
+ */
+public final class PathClassEntrySource implements ClassEntrySource {
+
+ private final Path path;
+ private ZipFile zipFile;
+
+ /**
+ * Creates a source for a JAR file or directory.
+ *
+ * @param path the path to read, must not be {@code null}
+ */
+ public PathClassEntrySource(Path path) {
+ if (path == null) {
+ throw new IllegalArgumentException("path is required");
+ }
+ this.path = path;
+ }
+
+ /**
+ * Returns the path being read.
+ *
+ * @return the path
+ */
+ public Path getPath() {
+ return path;
+ }
+
+ @Override
+ public Stream<ClassEntry> classes() throws IOException {
+ if (Files.isDirectory(path)) {
+ return directoryEntries();
+ }
+ if (Files.isRegularFile(path) &&
path.getFileName().toString().endsWith(".jar")) {
+ return jarEntries();
+ }
+ throw new IllegalArgumentException("Cannot create a class entry source
from path: " + path);
+ }
+
+ private Stream<ClassEntry> directoryEntries() throws IOException {
+ List<Path> classFiles;
+ try (Stream<Path> walk = Files.walk(path)) {
+ classFiles = walk.filter(Files::isRegularFile)
+ .filter(file ->
ClassEntries.isClassEntry(file.getFileName().toString()))
+ .collect(Collectors.toList());
+ }
+ List<ClassEntry> entries = new ArrayList<>(classFiles.size());
+ for (Path file : classFiles) {
+ String name =
path.relativize(file).toString().replace(java.io.File.separatorChar, '/');
+ entries.add(new ClassEntries.StreamClassEntry(name, () ->
Files.newInputStream(file)));
+ }
+ return entries.stream();
+ }
+
+ private Stream<ClassEntry> jarEntries() throws IOException {
+ final ZipFile jar = new ZipFile(path.toFile());
+ zipFile = jar;
+ List<ClassEntry> entries = new ArrayList<>();
+ Enumeration<? extends ZipEntry> enumeration = jar.entries();
+ while (enumeration.hasMoreElements()) {
+ ZipEntry entry = enumeration.nextElement();
+ if (ClassEntries.isClassEntry(entry.getName())) {
+ entries.add(new ClassEntries.StreamClassEntry(entry.getName(),
() -> jar.getInputStream(entry)));
+ }
+ }
+ return entries.stream();
+ }
+
+ @Override
+ public void close() throws IOException {
+ if (zipFile != null) {
+ zipFile.close();
+ zipFile = null;
+ }
+ }
+}
diff --git
a/src/main/java/org/apache/maven/shared/dependency/analyzer/UrlClassEntrySource.java
b/src/main/java/org/apache/maven/shared/dependency/analyzer/UrlClassEntrySource.java
new file mode 100644
index 0000000..d114399
--- /dev/null
+++
b/src/main/java/org/apache/maven/shared/dependency/analyzer/UrlClassEntrySource.java
@@ -0,0 +1,94 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.maven.shared.dependency.analyzer;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.stream.Stream;
+
+/**
+ * A {@link ClassEntrySource} backed by a URL. {@code file:} URLs delegate to
+ * {@link PathClassEntrySource}; other protocols are read into memory and
wrapped in a
+ * {@link BytesClassEntrySource}.
+ *
+ * @since 1.18.0
+ */
+public final class UrlClassEntrySource implements ClassEntrySource {
+
+ private final URL url;
+ private ClassEntrySource delegate;
+
+ /**
+ * Creates a source for a URL.
+ *
+ * @param url the URL to read, must not be {@code null}
+ */
+ public UrlClassEntrySource(URL url) {
+ if (url == null) {
+ throw new IllegalArgumentException("url is required");
+ }
+ this.url = url;
+ }
+
+ @Override
+ public Stream<ClassEntry> classes() throws IOException {
+ if ("file".equalsIgnoreCase(url.getProtocol())) {
+ try {
+ Path path = Paths.get(url.toURI());
+ if (!Files.exists(path)) {
+ // The URL-based API silently ignored a missing path, so
keep that behavior.
+ delegate = new ClassEntrySource() {
+ @Override
+ public Stream<ClassEntry> classes() {
+ return Stream.empty();
+ }
+ };
+ } else if (Files.isRegularFile(path)
+ && path.getFileName().toString().endsWith(".jar")) {
+ // Preserve the JarInputStream behavior of the original
URL-based API, which
+ // detects corrupt archives that ZipFile silently ignores.
+ try (InputStream in = url.openStream()) {
+ delegate = new
BytesClassEntrySource(ClassEntries.readAll(in));
+ }
+ } else {
+ delegate = new PathClassEntrySource(path);
+ }
+ } catch (URISyntaxException e) {
+ throw new IOException("Invalid file URL: " + url, e);
+ }
+ } else {
+ try (InputStream in = url.openStream()) {
+ delegate = new BytesClassEntrySource(ClassEntries.readAll(in));
+ }
+ }
+ return delegate.classes();
+ }
+
+ @Override
+ public void close() throws IOException {
+ if (delegate != null) {
+ delegate.close();
+ }
+ }
+}
diff --git
a/src/main/java/org/apache/maven/shared/dependency/analyzer/asm/ASMDependencyAnalyzer.java
b/src/main/java/org/apache/maven/shared/dependency/analyzer/asm/ASMDependencyAnalyzer.java
index 4e85c7b..4740830 100644
---
a/src/main/java/org/apache/maven/shared/dependency/analyzer/asm/ASMDependencyAnalyzer.java
+++
b/src/main/java/org/apache/maven/shared/dependency/analyzer/asm/ASMDependencyAnalyzer.java
@@ -25,10 +25,12 @@ import java.io.IOException;
import java.net.URL;
import java.util.Set;
+import org.apache.maven.shared.dependency.analyzer.ClassEntrySource;
import org.apache.maven.shared.dependency.analyzer.ClassFileVisitorUtils;
import org.apache.maven.shared.dependency.analyzer.ClassesPatterns;
import org.apache.maven.shared.dependency.analyzer.DependencyAnalyzer;
import org.apache.maven.shared.dependency.analyzer.DependencyUsage;
+import org.apache.maven.shared.dependency.analyzer.UrlClassEntrySource;
/**
* ASMDependencyAnalyzer
@@ -39,12 +41,26 @@ import
org.apache.maven.shared.dependency.analyzer.DependencyUsage;
@Singleton
public class ASMDependencyAnalyzer implements DependencyAnalyzer {
- @Override
- public Set<DependencyUsage> analyzeUsages(URL url, ClassesPatterns
excludeClasses) throws IOException {
+ /**
+ * Analyzes usages in the classes exposed by a source. Uses the same
visitor as the URL form.
+ *
+ * @param source the class entry source to analyze
+ * @param excludeClasses patterns of classes to exclude
+ * @return the referenced classes and their declaring classes
+ * @throws IOException if the source cannot be read
+ * @since 1.18.0
+ */
+ public Set<DependencyUsage> analyzeUsages(ClassEntrySource source,
ClassesPatterns excludeClasses)
+ throws IOException {
DependencyClassFileVisitor visitor = new
DependencyClassFileVisitor(excludeClasses);
- ClassFileVisitorUtils.accept(url, visitor);
+ ClassFileVisitorUtils.accept(source, visitor);
return visitor.getDependencyUsages();
}
+
+ @Override
+ public Set<DependencyUsage> analyzeUsages(URL url, ClassesPatterns
excludeClasses) throws IOException {
+ return analyzeUsages(new UrlClassEntrySource(url), excludeClasses);
+ }
}
diff --git
a/src/test/java/org/apache/maven/shared/dependency/analyzer/ClassEntrySourceTest.java
b/src/test/java/org/apache/maven/shared/dependency/analyzer/ClassEntrySourceTest.java
new file mode 100644
index 0000000..9668e61
--- /dev/null
+++
b/src/test/java/org/apache/maven/shared/dependency/analyzer/ClassEntrySourceTest.java
@@ -0,0 +1,135 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.maven.shared.dependency.analyzer;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.jar.JarOutputStream;
+import java.util.zip.ZipEntry;
+
+import org.apache.maven.shared.dependency.analyzer.asm.ASMDependencyAnalyzer;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class ClassEntrySourceTest {
+
+ @TempDir
+ private Path tempDir;
+
+ @Test
+ void allSourcesProduceTheSameClassNames() throws Exception {
+ Path jar = createJar();
+ Set<String> expected = new HashSet<>(Arrays.asList("a.b.c", "x.y.z"));
+
+ assertEquals(expected, new HashSet<>(classNames(new
PathClassEntrySource(jar))));
+ assertEquals(
+ expected,
+ new HashSet<>(classNames(new
UrlClassEntrySource(jar.toUri().toURL()))));
+ assertEquals(expected, new HashSet<>(classNames(new
BytesClassEntrySource(Files.readAllBytes(jar)))));
+ }
+
+ @Test
+ void directorySourceProducesTheSameClassNames() throws Exception {
+ Path dir = Files.createDirectories(tempDir.resolve("classes/a/b"));
+ Files.write(dir.resolve("c.class"), "class a.b.c".getBytes("UTF-8"));
+
+ Set<String> expected = Collections.singleton("a.b.c");
+ assertEquals(
+ expected,
+ new HashSet<>(
+ classNames(new
PathClassEntrySource(dir.getParent().getParent()))));
+ }
+
+ @Test
+ void analyzerOverloadsMatchUrlForms() throws Exception {
+ Path classes =
Paths.get("target/test-classes/org/apache/maven/shared/dependency/analyzer/testcases/analyze");
+ ClassesPatterns patterns = new
ClassesPatterns(Collections.singleton("ClassToExclude"));
+
+ DefaultClassAnalyzer classAnalyzer = new DefaultClassAnalyzer();
+ assertEquals(
+ classAnalyzer.analyze(classes.toUri().toURL(), patterns),
+ classAnalyzer.analyze(new PathClassEntrySource(classes),
patterns));
+ assertEquals(classAnalyzer.analyze(classes.toUri().toURL()),
classAnalyzer.analyze(classes));
+
+ ASMDependencyAnalyzer dependencyAnalyzer = new ASMDependencyAnalyzer();
+ assertEquals(
+ dependencyAnalyzer.analyzeUsages(classes.toUri().toURL(),
patterns),
+ dependencyAnalyzer.analyzeUsages(new
PathClassEntrySource(classes), patterns));
+ assertEquals(
+ dependencyAnalyzer.analyzeUsages(classes.toUri().toURL(),
patterns),
+ dependencyAnalyzer.analyzeUsages(classes, patterns));
+
+ List<String> viaUrl = new ArrayList<>();
+ List<String> viaPath = new ArrayList<>();
+ ClassFileVisitorUtils.accept(classes.toUri().toURL(), (name, in) ->
viaUrl.add(name));
+ ClassFileVisitorUtils.accept(classes, (name, in) -> viaPath.add(name));
+ assertEquals(viaUrl, viaPath);
+ }
+
+ @Test
+ void excludesInfoClasses() throws Exception {
+ Path jar = createJarWithInfoClasses();
+
+ List<String> names = classNames(new PathClassEntrySource(jar));
+ assertTrue(names.contains("a.b.c"));
+ assertEquals(1, names.size());
+ }
+
+ private Path createJar() throws IOException {
+ Path jar = Files.createTempFile(tempDir, "classes", ".jar");
+ try (JarOutputStream out = new
JarOutputStream(Files.newOutputStream(jar))) {
+ addEntry(out, "a/b/c.class", "class a.b.c");
+ addEntry(out, "x/y/z.class", "class x.y.z");
+ }
+ return jar;
+ }
+
+ private Path createJarWithInfoClasses() throws IOException {
+ Path jar = Files.createTempFile(tempDir, "info", ".jar");
+ try (JarOutputStream out = new
JarOutputStream(Files.newOutputStream(jar))) {
+ addEntry(out, "a/b/c.class", "class a.b.c");
+ addEntry(out, "module-info.class", "module");
+ addEntry(out, "a/b/package-info.class", "package");
+ }
+ return jar;
+ }
+
+ private static void addEntry(JarOutputStream out, String name, String
content) throws IOException {
+ out.putNextEntry(new ZipEntry(name));
+ out.write(content.getBytes("UTF-8"));
+ out.closeEntry();
+ }
+
+ private static List<String> classNames(ClassEntrySource source) throws
IOException {
+ List<String> names = new ArrayList<>();
+ ClassFileVisitorUtils.accept(source, (name, in) -> names.add(name));
+ return names;
+ }
+}
diff --git
a/src/test/java/org/apache/maven/shared/dependency/analyzer/ClassFileVisitorUtilsTest.java
b/src/test/java/org/apache/maven/shared/dependency/analyzer/ClassFileVisitorUtilsTest.java
index 1fc8f86..8bb42b4 100644
---
a/src/test/java/org/apache/maven/shared/dependency/analyzer/ClassFileVisitorUtilsTest.java
+++
b/src/test/java/org/apache/maven/shared/dependency/analyzer/ClassFileVisitorUtilsTest.java
@@ -34,9 +34,8 @@ import java.util.zip.ZipEntry;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
-import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
/**
* Tests <code>ClassFileVisitorUtils</code>.
@@ -129,24 +128,14 @@ class ClassFileVisitorUtilsTest {
Path path = Files.createTempFile(tempDir, "test", ".class");
URL url = path.toUri().toURL();
- try {
- ClassFileVisitorUtils.accept(url, visitor);
- fail("expected IllegalArgumentException");
- } catch (IllegalArgumentException exception) {
- assertEquals("Cannot accept visitor on URL: " + url,
exception.getMessage());
- }
+ assertThrows(IllegalArgumentException.class, () ->
ClassFileVisitorUtils.accept(url, visitor));
}
@Test
void testAcceptWithUnsupportedScheme() throws Exception {
URL url = new URL("http://localhost/");
- try {
- ClassFileVisitorUtils.accept(url, visitor);
- fail("expected IllegalArgumentException");
- } catch (IllegalArgumentException exception) {
- assertEquals("Cannot accept visitor on URL: " + url,
exception.getMessage());
- }
+ assertThrows(IllegalArgumentException.class, () ->
ClassFileVisitorUtils.accept(url, visitor));
}
private void writeToFile(Path parent, String file, String data) throws
IOException {
diff --git
a/src/test/java/org/apache/maven/shared/dependency/analyzer/DefaultClassAnalyzerTest.java
b/src/test/java/org/apache/maven/shared/dependency/analyzer/DefaultClassAnalyzerTest.java
index cd762e8..f1cadd2 100644
---
a/src/test/java/org/apache/maven/shared/dependency/analyzer/DefaultClassAnalyzerTest.java
+++
b/src/test/java/org/apache/maven/shared/dependency/analyzer/DefaultClassAnalyzerTest.java
@@ -37,8 +37,8 @@ import org.junit.jupiter.api.io.TempDir;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertIterableEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
/**
* Tests <code>DefaultClassAnalyzer</code>.
@@ -86,12 +86,9 @@ class DefaultClassAnalyzerTest {
ClassAnalyzer analyzer = new DefaultClassAnalyzer();
- try {
- analyzer.analyze(file.toUri().toURL());
- fail("Exception expected");
- } catch (ZipException e) {
- assertTrue(e.getMessage().startsWith("Cannot process Jar entry on
URL:"));
- }
+ ZipException exception = assertThrows(
+ ZipException.class, () ->
analyzer.analyze(file.toUri().toURL()));
+ assertTrue(exception.getMessage().startsWith("Cannot process Jar entry
on URL:"));
}
@Test