001package com.ganteater.ae.maven.plugin; 002 003import java.io.File; 004import java.io.IOException; 005import java.util.ArrayList; 006import java.util.Enumeration; 007import java.util.LinkedHashSet; 008import java.util.List; 009import java.util.Set; 010import java.util.jar.JarEntry; 011import java.util.jar.JarFile; 012 013import org.apache.commons.lang.StringUtils; 014import org.apache.maven.artifact.Artifact; 015import org.apache.maven.plugin.MojoExecutionException; 016 017/** 018 * Scans dependencies looking for tests. 019 */ 020public class DependencyScanner { 021 private final List<File> dependenciesToScan; 022 023 public DependencyScanner(List<File> dependenciesToScan) { 024 this.dependenciesToScan = dependenciesToScan; 025 } 026 027 public Set<Class> scan() throws MojoExecutionException { 028 Set<Class> classes = new LinkedHashSet<>(); 029 for (File artifact : dependenciesToScan) { 030 try { 031 scanArtifact(artifact, classes); 032 } catch (Exception e) { 033 throw new MojoExecutionException("Could not scan dependency " + artifact.toString(), e); 034 } 035 } 036 return classes; 037 } 038 039 @SuppressWarnings("squid:S134") 040 private static void scanArtifact(File artifact, Set<Class> classes) throws IOException, ClassNotFoundException { 041 if (artifact != null && artifact.isFile()) { 042 try(JarFile jar = new JarFile(artifact)) { 043 for (Enumeration<JarEntry> entries = jar.entries(); entries.hasMoreElements();) { 044 JarEntry entry = entries.nextElement(); 045 046 String name = entry.getName(); 047 if (name.endsWith("Operations.class")) { 048 String className = StringUtils.substringBeforeLast(name, "."); 049 className = StringUtils.replaceChars(className, '/', '.'); 050 Class<?> clazz = Class.forName(className); 051 classes.add(clazz); 052 } 053 } 054 } 055 } 056 } 057 058 public static List<File> filter(List<Artifact> artifacts, List<String> groupArtifactIds) { 059 List<File> matches = new ArrayList<>(); 060 if (groupArtifactIds == null || artifacts == null) { 061 return matches; 062 } 063 for (Artifact artifact : artifacts) { 064 for (String groups : groupArtifactIds) { 065 String[] groupArtifact = groups.split(":"); 066 if (groupArtifact.length != 2) { 067 throw new IllegalArgumentException( 068 "dependencyToScan argument should be in format" + " 'groupid:artifactid': " + groups); 069 } 070 if (artifact.getGroupId().matches(groupArtifact[0]) 071 && artifact.getArtifactId().matches(groupArtifact[1])) { 072 matches.add(artifact.getFile()); 073 } 074 } 075 } 076 return matches; 077 } 078}