com.flextrade.builder.ClassFinder Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of pojobuilder-maven-plugin Show documentation
Show all versions of pojobuilder-maven-plugin Show documentation
Maven Plugin which generates Builders and matchers
package com.flextrade.builder;
import static com.google.common.collect.Sets.newHashSet;
import static java.util.stream.Collectors.toList;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.MavenProject;
import org.reflections.Reflections;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
public class ClassFinder {
private final MavenProject project;
private final Log log;
private Optional urlException = Optional.empty();
public ClassFinder(MavenProject project, Log log) {
this.project = project;
this.log = log;
}
public Set> findClassesWhichExtend(String className) throws MojoFailureException {
URLClassLoader classLoader = getDependencyClassLoader();
log.debug("got classLoader");
try {
Class> superClass = Class.forName(className, true, classLoader);
return newHashSet((Iterable extends Class>>) findClassesWhichExtend(superClass, classLoader));
} catch (ClassNotFoundException e) {
log.error(e);
throw new MojoFailureException("Unable to find pojo classes");
}
}
private URLClassLoader getDependencyClassLoader() throws MojoFailureException {
Set artifacts = new HashSet<>(project.getDependencyArtifacts());
artifacts.add(project.getArtifact());
List urls = artifacts.stream().map(Artifact::getFile).filter(f -> f != null).map(f -> toURL(f)).collect(toList());
log.debug("got " + urls.size() + " urls");
urls.forEach(url -> log.debug(url.toString()));
if(urlException.isPresent()) {
throw new MojoFailureException("Unable to parse dependency URLs", urlException.get());
}
return new URLClassLoader(urls.toArray(new URL[0]), this.getClass().getClassLoader());
}
private Set> findClassesWhichExtend(Class superClass, URLClassLoader classLoader) {
Arrays.asList(classLoader.getURLs()).forEach(url -> log.info(url.toString()));
Reflections reflections = new Reflections(
new ConfigurationBuilder()
.setScanners(new SubTypesScanner())
.setUrls(ClasspathHelper.forClassLoader(classLoader))
.addClassLoader(classLoader));
log.debug("got reflections");
Set> classes = reflections.getSubTypesOf(superClass);
log.debug("got " + classes.size() + " classes");
return classes;
}
private URL toURL(File file) {
try {
return file.toURL();
} catch (MalformedURLException e) {
log.error(e);
urlException = Optional.of(e);
return null;
}
}
}