// the compile or test classpath. As a backup, we do a best-effort lookup in the Maven repository
// For transitive dependencies, we could evaluate Plugin-Dependencies transitively.
String dependencies = m.getMainAttributes().getValue("Plugin-Dependencies");
if(dependencies!=null) {
MavenEmbedder embedder = MavenUtil
.createEmbedder(new StreamTaskListener(System.out, Charset.defaultCharset()),
(File) null, null);
for( String dep : dependencies.split(",")) {
String[] tokens = dep.split(":");
String artifactId = tokens[0];
String version = tokens[1];
File dependencyJar=resolveDependencyJar(embedder,artifactId,version);
File dst = new File(home, "plugins/" + artifactId + ".jpi");
if(!dst.exists() || dst.lastModified()!=dependencyJar.lastModified()) {
FileUtils.copyFile(dependencyJar, dst);
}
}
}
}
}
private File resolveDependencyJar(MavenEmbedder embedder, String artifactId, String version) throws Exception {
// try to locate it from manifest
Enumeration<URL> manifests = getClass().getClassLoader().getResources("META-INF/MANIFEST.MF");
while (manifests.hasMoreElements()) {
URL manifest = manifests.nextElement();
InputStream is = manifest.openStream();
Manifest m = new Manifest(is);
is.close();
if (artifactId.equals(m.getMainAttributes().getValue("Short-Name")))
return Which.jarFile(manifest);
}
// need to search multiple group IDs
// TODO: extend manifest to include groupID:artifactID:version
Exception resolutionError=null;
for (String groupId : new String[]{"org.jvnet.hudson.plugins","org.jvnet.hudson.main"}) {
// first try to find it on the classpath.
// this takes advantage of Maven POM located in POM
URL dependencyPomResource = getClass().getResource("/META-INF/maven/"+groupId+"/"+artifactId+"/pom.xml");
if (dependencyPomResource != null) {
// found it
return Which.jarFile(dependencyPomResource);
} else {
try {
// currently the most of the plugins are still hpi
return resolvePluginFile(embedder, artifactId, version, groupId, "hpi");
} catch(AbstractArtifactResolutionException x){
try {
// but also try with the new jpi
return resolvePluginFile(embedder, artifactId, version, groupId, "jpi");
} catch(AbstractArtifactResolutionException x2){
// could be a wrong groupId
resolutionError = x;
}
}
}
}
throw new Exception("Failed to resolve plugin: "+artifactId+" version "+version,resolutionError);
}
private File resolvePluginFile(MavenEmbedder embedder, String artifactId, String version, String groupId, String type)
throws MavenEmbedderException, ComponentLookupException, AbstractArtifactResolutionException {
final Artifact jpi = embedder.createArtifact(groupId, artifactId, version, "compile"/*doesn't matter*/, type);
embedder.resolve(jpi, Arrays.asList(embedder.createRepository("http://maven.glassfish.org/content/groups/public/","repo")),embedder.getLocalRepository());
return jpi.getFile();
}
});
}