Maven plugin artifact filter unimportant dependencies - maven

I'm developing a Maven plugin and using the MavenProject object to access my dependencies with project.getDependencyArtifacts(), but this gives my all jar, even the test only jars.
Is there some method to filter all non runtime jar? If I just get the scope and compare for scope.equals("runtime") I will throw out the compile and other important dependencies.

I did not find an existing method for this either so I'm using the following logic. This is a plugin building a customized ear, which adds the needed dependencies to an xml file and include them in the archive. It is using getArtifacts instead of getDependencyArtifacts since I'm also interested in transitive dependencies.
Collection<Artifact> dependencies = new ArrayList<Artifact>();
dependencies.addAll(project.getArtifacts());
for (Iterator<Artifact> it=dependencies.iterator(); it.hasNext(); ) {
Artifact dependency = it.next();
String scope = dependency.getScope();
String type = dependency.getType();
if (dependency.isOptional() || !"jar".equals(type) || "provided".equals(scope) || "test".equals(scope) || "system".equals(scope)) {
getLog().debug("Pruning dependency " + dependency);
it.remove();
}
}

Related

Creating RepositorySystemSession using Aether

I'm trying to get all transitive dependencies of a maven project in a List of Artifacts.
I found the documentation of Aether with some example code to set up the process. One part of it is the RepositorySystem.
private static RepositorySystem newRepositorySystem() {
DefaultServiceLocator locator = MavenRepositorySystemUtils.newServiceLocator();
locator.addService(RepositoryConnectorFactory.class, BasicRepositoryConnectorFactory.class);
locator.addService(TransporterFactory.class, FileTransporterFactory.class);
locator.addService(TransporterFactory.class, HttpTransporterFactory.class);
return locator.getService(RepositorySystem.class);
}
But I get a NullPointerException in the return value.
I have no idea why?
Big thanks

How can I call code from one subproject in a gradle tasks of another subproject?

I have a project with two subprojects.
One of these subprojects, "A", contains code that is being published to an artifact.
The other subproject, "B", has a task that needs to do exactly what one of the methods in A's code does. I can replicate the logic in groovy, but is there any way I can actually have my task in subproject B call the code that was compiled as part of subproject A?
I'd tried adding a buildscript block in B that added the artifact from A to the classpath:
buildscript {
dependencies {
classpath project(':subproject-a')
}
}
...but this gave me an error:
Cannot use project dependencies in a script classpath definition.
I don't believe I can move subproject-a to buildSrc, as I'm also publishing its artifact to a maven repository for other projects to use.
You have a chicken or egg problem where all of the Gradle project classloaders are resolved before any classes are compiled. This can be resolved using a custom configuration and a Classloader
Eg:
configurations {
custom
}
dependencies {
custom project(':subproject-a')
}
task customTask {
doLast {
def urls = configurations.custom.files.collect { it.toURI().toURL() }
ClassLoader cl = new java.net.URLClassLoader(urls as URL[])
Class myClass = cl.loadClass('com.foo.MyClass')
// assuming zero args constructor
Object myObject = myClass.newInstance()
// assuming method which accepts single String argument
java.lang.reflect.Method myMethod = myClass.getMethod('myMethodName', String.class)
myMethod.invoke(myObject, 'methodArg')
}
}

How to get dependencies from a gradle plugin using "api" or "implementation" directives

Background: Running Android Studio 3.0-beta7 and trying to get a javadoc task to work for an Android library (the fact that this is not available as a ready-made task in the first place is really strange), and I managed to tweak an answer to a different question for my needs, ending up with this code (https://stackoverflow.com/a/46810617/1226020):
task javadoc(type: Javadoc) {
failOnError false
source = android.sourceSets.main.java.srcDirs
// Also add the generated R class to avoid errors...
// TODO: debug is hard-coded
source += "$buildDir/generated/source/r/debug/"
// ... but exclude the R classes from the docs
excludes += "**/R.java"
// TODO: "compile" is deprecated in Gradle 4.1,
// but "implementation" and "api" are not resolvable :(
classpath += configurations.compile
afterEvaluate {
// Wait after evaluation to add the android classpath
// to avoid "buildToolsVersion is not specified" error
classpath += files(android.getBootClasspath())
// Process AAR dependencies
def aarDependencies = classpath.filter { it.name.endsWith('.aar') }
classpath -= aarDependencies
aarDependencies.each { aar ->
System.out.println("Adding classpath for aar: " + aar.name)
// Extract classes.jar from the AAR dependency, and add it to the javadoc classpath
def outputPath = "$buildDir/tmp/exploded-aar/${aar.name.replace('.aar', '.jar')}"
classpath += files(outputPath)
// Use a task so the actual extraction only happens before the javadoc task is run
dependsOn task(name: "extract ${aar.name}").doLast {
extractEntry(aar, 'classes.jar', outputPath)
}
}
}
}
// Utility method to extract only one entry in a zip file
private def extractEntry(archive, entryPath, outputPath) {
if (!archive.exists()) {
throw new GradleException("archive $archive not found")
}
def zip = new java.util.zip.ZipFile(archive)
zip.entries().each {
if (it.name == entryPath) {
def path = new File(outputPath)
if (!path.exists()) {
path.getParentFile().mkdirs()
// Surely there's a simpler is->os utility except
// the one in java.nio.Files? Ah well...
def buf = new byte[1024]
def is = zip.getInputStream(it)
def os = new FileOutputStream(path)
def len
while ((len = is.read(buf)) != -1) {
os.write(buf, 0, len)
}
os.close()
}
}
}
zip.close()
}
This code tries to find all dependency AAR:s, loops through them and extracts classes.jar from them, and puts them in a temp folder that is added to the classpath during javadoc generation. Basically trying to reproduce what the really old android gradle plugin used to do with "exploded-aar".
However, the code relies on using compile dependencies. Using api or implementation that are recommended with Gradle 4.1 will not work, since these are not resolvable from a Gradle task.
Question: how can I get a list of dependencies using the api or implementation directives when e.g. configuration.api renders a "not resolvable" error?
Bonus question: is there a new, better way to create javadocs for a library with Android Studio 3.0 that doesn't involve 100 lines of workarounds?
You can wait for this to be merged:
https://issues.apache.org/jira/browse/MJAVADOC-450
Basically, the current Maven Javadoc plugin ignores classifiers such as AAR.
I ran in to the same problem when trying your answer to this question when this error message kept me from resolving the implementation dependencies:
Resolving configuration 'implementation' directly is not allowed
Then I discovered that this answer has a solution that makes resolving of the implementation and api configurations possible:
configurations.implementation.setCanBeResolved(true)
I'm not sure how dirty this workaround is, but it seems to do the trick for the javadocJar task situation.

convertopom task in Ivy. How to add more artifacts to publications field

When I use convertpom task in Ivy to convert a pom.xml to ivy.xml, I get default publications
<publications>
<artifact name="XYZ" type="jar" ext="jar" conf="master"/>
</publications>
How do I modify pom.xml, so that more artifacts are added to this in conversion. Where does converttopom pick up the artifacts from. Also, how do I change the type?
Is it possible to override these in ivy:publish call?
found this piece of code in convertpom ant task, not sure how it is used.
private void addSourcesAndJavadocArtifactsIfPresent(
PomModuleDescriptorBuilder mdBuilder, ParserSettings ivySettings) {
if (mdBuilder.getMainArtifact() == null) {
// no main artifact in pom, we don't need to search for meta artifacts
return;
}
ModuleDescriptor md = mdBuilder.getModuleDescriptor();
ModuleRevisionId mrid = md.getModuleRevisionId();
DependencyResolver resolver = ivySettings.getResolver(
mrid);
if (resolver == null) {
Message.debug("no resolver found for " + mrid
+ ": no source or javadoc artifact lookup");
} else {
ArtifactOrigin mainArtifact = resolver.locate(mdBuilder.getMainArtifact());
if (!ArtifactOrigin.isUnknown(mainArtifact)) {
String mainArtifactLocation = mainArtifact.getLocation();
ArtifactOrigin sourceArtifact = resolver.locate(mdBuilder.getSourceArtifact());
if (!ArtifactOrigin.isUnknown(sourceArtifact)
&& !sourceArtifact.getLocation().equals(mainArtifactLocation)) {
Message.debug("source artifact found for " + mrid);
mdBuilder.addSourceArtifact();
} else {
// it seems that sometimes the 'src' classifier is used instead of 'sources'
// Cfr. IVY-1138
ArtifactOrigin srcArtifact = resolver.locate(mdBuilder.getSrcArtifact());
if (!ArtifactOrigin.isUnknown(srcArtifact)
&& !srcArtifact.getLocation().equals(mainArtifactLocation)) {
Message.debug("source artifact found for " + mrid);
mdBuilder.addSrcArtifact();
} else {
Message.debug("no source artifact found for " + mrid);
}
}
ArtifactOrigin javadocArtifact = resolver.locate(mdBuilder.getJavadocArtifact());
if (!ArtifactOrigin.isUnknown(javadocArtifact)
&& !javadocArtifact.getLocation().equals(mainArtifactLocation)) {
Message.debug("javadoc artifact found for " + mrid);
mdBuilder.addJavadocArtifact();
} else {
Message.debug("no javadoc artifact found for " + mrid);
}
}
}
}
This really demonstrates one of the key differences between Maven and ivy...
An ivy file explicitly lists all the files contained in the module. A Maven POM on the other hand does not. Instead zero or more additional files can be stored in Maven each with a different "classifier" to make the filename unique.
I can't see any way to build the complete "publications" section in ivy without having access to the Maven module's filesystem. Are you using a Maven repository manager? Nexus has a REST API that perhaps you could invoke to obtain all files in a module (Just a thought)
Another idea is to submit a request to extend the convertpom task. Create some optional child tags that enable you to list the available classifiers:
<ivy:convertpom pomFile="pom.xml" ivyFile="ivy.xml">
<classifier name="sources"/>
<classifier name="javadoc"/>
<classifier name="archive" type="tar.gz/>
</ivy:convertpom>
I don't see this change being very popular (or useful). Most people are converting in the other direction using the makepom task.

How to programmatically list all transitive dependencies, including overridden ones in Maven using DependencyGraphBuilder?

This is similar to other questions (like this), but I want to be able to do this with the latest API's. The maven-dependency-plugin:tree verbose option has been deprecated and does nothing in the latest (2.5.1) code, so there is no good example of how to do it.
I believe Aether utility class from jcabi-aether can help you to get a list of all dependencies of any Maven artifact, for example:
File repo = this.session.getLocalRepository().getBasedir();
Collection<Artifact> deps = new Aether(this.getProject(), repo).resolve(
new DefaultArtifact("junit", "junit-dep", "", "jar", "4.10"),
JavaScopes.RUNTIME
);
If you're outside of Maven plugin:
File repo = new File("/tmp/local-repository");
MavenProject project = new MavenProject();
project.setRemoteProjectRepositories(
Arrays.asList(
new RemoteRepository(
"maven-central",
"default",
"http://repo1.maven.org/maven2/"
)
)
);
Collection<Artifact> deps = new Aether(project, repo).resolve(
new DefaultArtifact("junit", "junit-dep", "", "jar", "4.10"),
"runtime"
);
The only dependency you need is:
<dependency>
<groupId>com.jcabi</groupId>
<artifactId>jcabi-aether</artifactId>
<version>0.7.5</version>
</dependency>
Including my approach here, as the additional steps may become part of your actual use case, esp. if working on a composite or multi-module project.
(Maven 3, my runtime was 3.6; no direct dependency on Aether)
In my case I wanted to resolve the dependency tree of a specific artifact foo-runtime from inside my plugin; however,
some of the dependency versions were only available in its parent's foo-parent POM (i.e. absent in the foo-runtime's own POM).
The parent POM also had additional details, such as exclusions for some of foo-runtime's dependencies - via dependencyManagement.
So I had to:
explicitly load the parent's model,
link the child model to it,
fill in the missing version numbers of the child model (still not sure why Maven didn't automatically resolve these after linking the parent), and then
run dependency resolution for the child.
To avoid model building from scratch, I derived the model of of foo-runtime using an existing artifact foo-api (which in my case is always guaranteed to be present in the Maven project being built). All these artifacts share the same groupId.
#Component
public LifecycleDependencyResolver resolver;
// ...
// `artifacts` contains all artifacts of current/reactor `MavenProject` obtained via `project.getArtifacts()`
private Set<Artifact> resolveRuntimeDeps(Set<Artifact> artifacts) throws MojoExecutionException {
// foo-api will always be present; use it to derive coordinates for foo-runtime
Artifact fooApi = artifacts.stream().filter(artifact -> "foo-api".equals(artifact.getArtifactId()))
.findFirst().orElseThrow(() -> new MojoExecutionException("Unable to find foo-api"));
Collection<String> scopes = Arrays.asList("compile", "runtime");
MavenProject fooRoot = deriveProject(fooApi, "foo-parent");
Model fooRootPom = fooRoot.getModel();
MavenProject fooSrv = deriveProject(fooApi, "foo-runtime");
fooSrv.setParent(fooRoot);
// some foo-runtime deps depend on versions declared on parent pom; merge them
Map<String, Artifact> depMgt = fooRootPom.getDependencyManagement().getDependencies().stream()
.collect(Collectors.toMap(dep -> dep.getGroupId() + ":" + dep.getArtifactId() + ":" + dep.getType(), this::toArtifact));
for (Dependency d : fooSrv.getDependencies()) {
if (d.getVersion() == null) {
Artifact managed = depMgt.get(d.getGroupId() + ":" + d.getArtifactId() + ":" + d.getType());
if (managed != null) {
d.setVersion(managed.getVersion());
}
}
}
try {
resolver.resolveProjectDependencies(fooSrv, scopes, scopes, session, false, Collections.emptySet());
return fooSrv.getArtifacts();
} catch (LifecycleExecutionException e) {
throw new MojoExecutionException("Error resolving foo-runtime dependencies", e);
}
}
// load POM for another artifact based on foo-api JAR available in current project
private MavenProject deriveProject(Artifact fooApi, String artifactId) throws MojoExecutionException {
Model pom;
String pomPath = fooApi.getFile().getAbsolutePath().replaceAll("foo-api", artifactId).replaceAll("\\.jar$", ".pom");
try (InputStream fooRootPomData = new FileInputStream(pomPath)) {
pom = new MavenXpp3Reader().read(fooRootPomData);
pom.setPomFile(new File(pomPath));
} catch (IOException | XmlPullParserException e) {
throw new MojoExecutionException("Error loading " + artifactId + " metadata", e);
}
// set these params to avoid skips/errors during resolution
MavenProject proj = new MavenProject(pom);
proj.setArtifact(toArtifact(pom));
proj.setArtifactFilter(Objects::nonNull);
proj.setRemoteArtifactRepositories(Collections.emptyList());
return proj;
}
private Artifact toArtifact(Model model) {
return new DefaultArtifact(
Optional.ofNullable(model.getGroupId()).orElseGet(() -> model.getParent().getGroupId()), model.getArtifactId(),
Optional.ofNullable(model.getVersion()).orElseGet(() -> model.getParent().getVersion()), "compile", model.getPackaging(), null,
project.getArtifact().getArtifactHandler());
}
private Artifact toArtifact(Dependency dep) {
return new DefaultArtifact(dep.getGroupId(), dep.getArtifactId(), dep.getVersion(), dep.getScope(), dep.getType(), dep.getClassifier(),
project.getArtifact().getArtifactHandler());
}
(I tried almost all the other suggested approaches, however all of them ended up with some error or another. Now, looking back, I suspect many of those errors might have been due to the fact that my leaf POM was missing version numbers for some artifacts. It seems (acceptably so) the "model enrichment" phase - propagating parent versions etc. - is carried out by some earlier component in Maven's flow; and the caller has to take care of this, at least partially, when invoking the dependency resolver from scratch.)

Resources