下面列出了怎么用org.apache.maven.project.ProjectBuildingException的API类实例代码及写法,或者点击链接到github查看源代码。
private static MavenProject readMavenProject(MavenEmbedder embedder, Artifact artifact, List<ArtifactRepository> remoteRepos) throws ProjectBuildingException {
ProjectBuilder bldr = embedder.lookupComponent(ProjectBuilder.class);
assert bldr !=null : "ProjectBuilder component not found in maven";
DefaultMaven maven = (DefaultMaven) embedder.lookupComponent(Maven.class);
assert bldr !=null : "DefaultMaven component not found in maven";
MavenExecutionRequest req = embedder.createMavenExecutionRequest();
req.setLocalRepository(embedder.getLocalRepository());
req.setRemoteRepositories(remoteRepos);
ProjectBuildingRequest configuration = req.getProjectBuildingRequest();
configuration.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);
configuration.setResolveDependencies(true);
configuration.setRepositorySession(maven.newRepositorySession(req));
ProjectBuildingResult projectBuildingResult = bldr.build(artifact, configuration);
return projectBuildingResult.getProject();
}
protected List<File> getParents() {
LinkedList<File> ret = new LinkedList<>();
MavenProject project = getOriginalMavenProject();
while(true) {
try {
MavenProject parent = loadParentOf(getEmbedder(), project);
File parentFile = parent != null ? parent.getFile() : null;
if(parentFile != null) {
ret.add(parentFile);
project = parent;
} else {
break;
}
} catch (ProjectBuildingException ex) {
break;
}
}
return ret;
}
public MavenExecutionResult readProjectWithDependencies(MavenExecutionRequest req, boolean useWorkspaceResolution) {
if (useWorkspaceResolution) {
req.setWorkspaceReader(new NbWorkspaceReader());
}
File pomFile = req.getPom();
MavenExecutionResult result = new DefaultMavenExecutionResult();
try {
ProjectBuildingRequest configuration = req.getProjectBuildingRequest();
configuration.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);
configuration.setResolveDependencies(true);
configuration.setRepositorySession(maven.newRepositorySession(req));
ProjectBuildingResult projectBuildingResult = projectBuilder.build(pomFile, configuration);
result.setProject(projectBuildingResult.getProject());
result.setDependencyResolutionResult(projectBuildingResult.getDependencyResolutionResult());
} catch (ProjectBuildingException ex) {
//don't add the exception here. this should come out as a build marker, not fill
//the error logs with msgs
return result.addException(ex);
}
normalizePaths(result.getProject());
return result;
}
private MavenProject load(ArtifactInfo ai) {
try {
Artifact projectArtifact = embedder.createArtifact(ai.getGroupId(), ai.getArtifactId(), ai.getVersion(), ai.getPackaging() != null ? ai.getPackaging() : "jar");
ProjectBuildingRequest dpbr = embedder.createMavenExecutionRequest().getProjectBuildingRequest();
//mkleint: remote repositories don't matter we use project embedder.
dpbr.setRemoteRepositories(remoteRepos);
dpbr.setProcessPlugins(false);
dpbr.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);
ProjectBuildingResult res = embedder.buildProject(projectArtifact, dpbr);
if (res.getProject() != null) {
return res.getProject();
} else {
LOG.log(Level.FINER, "No project model from repository for {0}: {1}", new Object[] {ai, res.getProblems()});
}
} catch (ProjectBuildingException ex) {
LOG.log(Level.FINER, "Failed to load project model from repository for {0}: {1}", new Object[] {ai, ex});
} catch (Exception exception) {
LOG.log(Level.FINER, "Failed to load project model from repository for " + ai, exception);
}
return null;
}
/**
* Get the <code>Maven project</code> from the repository depending
* the <code>Artifact</code> given.
*
* @param artifact an artifact
* @return the Maven project for the given artifact
* @throws org.apache.maven.project.ProjectBuildingException
* if any
*/
private MavenProject getMavenProjectFromRepository( Artifact artifact, ArtifactRepository localRepository )
throws ProjectBuildingException
{
Artifact projectArtifact = artifact;
boolean allowStubModel = false;
if ( !"pom".equals( artifact.getType() ) )
{
projectArtifact = factory.createProjectArtifact( artifact.getGroupId(), artifact.getArtifactId(),
artifact.getVersion(), artifact.getScope() );
allowStubModel = true;
}
// TODO: we should use the MavenMetadataSource instead
return mavenProjectBuilder.buildFromRepository( projectArtifact, project.getRemoteArtifactRepositories(),
localRepository, allowStubModel );
}
/**
*
* @param projectId
* @param dependencyManagement
* @return
* @throws ProjectBuildingException
*/
private Map<String,Artifact> createManagedVersionMap(String projectId, DependencyManagement dependencyManagement) throws ProjectBuildingException {
Map<String,Artifact> map;
if (dependencyManagement != null && dependencyManagement.getDependencies() != null) {
map = new HashMap<>();
for (Dependency d : dependencyManagement.getDependencies()) {
try {
VersionRange versionRange = VersionRange.createFromVersionSpec(d.getVersion());
Artifact artifact = factory.createDependencyArtifact(d.getGroupId(), d.getArtifactId(),
versionRange, d.getType(), d.getClassifier(),
d.getScope());
map.put(d.getManagementKey(), artifact);
} catch (InvalidVersionSpecificationException e) {
throw new ProjectBuildingException(projectId, "Unable to parse version '" + d.getVersion()
+ "' for dependency '" + d.getManagementKey() + "': " + e.getMessage(), e);
}
}
} else {
map = Collections.emptyMap();
}
return map;
}
public ExtensionClassLoader createExtensionClassLoader() throws MojoExecutionException, ProjectBuildingException {
final Artifact narArtifact = project.getArtifact();
final Set<Artifact> narArtifacts = getNarDependencies(narArtifact);
final ArtifactsHolder artifactsHolder = new ArtifactsHolder();
artifactsHolder.addArtifacts(narArtifacts);
getLog().debug("Project artifacts: ");
narArtifacts.forEach(artifact -> getLog().debug(artifact.getArtifactId()));
final ExtensionClassLoader parentClassLoader = createClassLoader(narArtifacts, artifactsHolder);
final ExtensionClassLoader classLoader = createClassLoader(narArtifacts, parentClassLoader, narArtifact);
if (getLog().isDebugEnabled()) {
getLog().debug("Full ClassLoader is:\n" + classLoader.toTree());
}
return classLoader;
}
private Set<Artifact> getNarDependencies(final Artifact narArtifact) throws MojoExecutionException, ProjectBuildingException {
final ProjectBuildingRequest narRequest = new DefaultProjectBuildingRequest();
narRequest.setRepositorySession(repoSession);
narRequest.setSystemProperties(System.getProperties());
narRequest.setLocalRepository(localRepo);
final ProjectBuildingResult narResult = projectBuilder.build(narArtifact, narRequest);
final Set<Artifact> narDependencies = new TreeSet<>();
gatherArtifacts(narResult.getProject(), narDependencies);
narDependencies.remove(narArtifact);
narDependencies.remove(project.getArtifact());
getLog().debug("Found NAR dependency of " + narArtifact + ", which resolved to the following artifacts: " + narDependencies);
return narDependencies;
}
private ExtensionClassLoader createProvidedEntitiesClassLoader(final ArtifactsHolder artifactsHolder)
throws MojoExecutionException, ProjectBuildingException {
final String nifiApiVersion = determineProvidedEntityVersion(artifactsHolder.getAllArtifacts(), "org.apache.nifi", "nifi-api");
if (nifiApiVersion == null) {
throw new MojoExecutionException("Could not find any dependency, provided or otherwise, on [org.apache.nifi:nifi-api]");
} else {
getLog().info("Found a dependency on version " + nifiApiVersion + " of NiFi API");
}
final String slf4jApiVersion = determineProvidedEntityVersion(artifactsHolder.getAllArtifacts(),"org.slf4j", "slf4j-api");
final Artifact nifiApiArtifact = getProvidedArtifact("org.apache.nifi", "nifi-api", nifiApiVersion);
final Artifact nifiFrameworkApiArtifact = getProvidedArtifact("org.apache.nifi", "nifi-framework-api", nifiApiArtifact.getVersion());
final Artifact slf4jArtifact = getProvidedArtifact("org.slf4j", "slf4j-api", slf4jApiVersion);
final Set<Artifact> providedArtifacts = new HashSet<>();
providedArtifacts.add(nifiApiArtifact);
providedArtifacts.add(nifiFrameworkApiArtifact);
providedArtifacts.add(slf4jArtifact);
getLog().debug("Creating Provided Entities Class Loader with artifacts: " + providedArtifacts);
return createClassLoader(providedArtifacts, null, null);
}
@Override
public MavenProject getProject() {
ProjectBuildingRequest buildingRequest = new DefaultProjectBuildingRequest(this.session.getProjectBuildingRequest());
buildingRequest.setRepositorySession(this.session.getRepositorySession());
buildingRequest.setProject(null);
buildingRequest.setResolveDependencies(true);
buildingRequest.setActiveProfileIds(this.profiles);
DefaultArtifact artifact = new DefaultArtifact(this.groupId, this.artifactId, this.version, SCOPE_COMPILE, this.type, this.classifier, new DefaultArtifactHandler());
try {
return this.projectBuilder.build(artifact, buildingRequest).getProject();
} catch (ProjectBuildingException e) {
throw new IllegalStateException("Error while creating Maven project from Artifact '" + artifact + "'.", e);
}
}
static MavenProject createMavenProject(Path pomFile, RepositorySystemSession session)
throws MavenRepositoryException {
// MavenCli's way to instantiate PlexusContainer
ClassWorld classWorld =
new ClassWorld("plexus.core", Thread.currentThread().getContextClassLoader());
ContainerConfiguration containerConfiguration =
new DefaultContainerConfiguration()
.setClassWorld(classWorld)
.setRealm(classWorld.getClassRealm("plexus.core"))
.setClassPathScanning(PlexusConstants.SCANNING_INDEX)
.setAutoWiring(true)
.setJSR250Lifecycle(true)
.setName("linkage-checker");
try {
PlexusContainer container = new DefaultPlexusContainer(containerConfiguration);
MavenExecutionRequest mavenExecutionRequest = new DefaultMavenExecutionRequest();
ProjectBuildingRequest projectBuildingRequest =
mavenExecutionRequest.getProjectBuildingRequest();
projectBuildingRequest.setRepositorySession(session);
// Profile activation needs properties such as JDK version
Properties properties = new Properties(); // allowing duplicate entries
properties.putAll(projectBuildingRequest.getSystemProperties());
properties.putAll(OsProperties.detectOsProperties());
properties.putAll(System.getProperties());
projectBuildingRequest.setSystemProperties(properties);
ProjectBuilder projectBuilder = container.lookup(ProjectBuilder.class);
ProjectBuildingResult projectBuildingResult =
projectBuilder.build(pomFile.toFile(), projectBuildingRequest);
return projectBuildingResult.getProject();
} catch (PlexusContainerException | ComponentLookupException | ProjectBuildingException ex) {
throw new MavenRepositoryException(ex);
}
}
/**
* replacement for MavenProject.getParent() which has bad long term memory behaviour. We offset it by recalculating/reparsing everything
* therefore should not be used lightly!
* pass a MavenProject instance and current configuration and other settings will be applied when loading the parent.
* @param project
* @return null or the parent mavenproject
*/
public MavenProject loadParentOf(MavenEmbedder embedder, MavenProject project) throws ProjectBuildingException {
MavenProject parent = null;
ProjectBuilder builder = embedder.lookupComponent(ProjectBuilder.class);
MavenExecutionRequest req = embedder.createMavenExecutionRequest();
M2Configuration active = configProvider.getActiveConfiguration();
req.addActiveProfiles(active.getActivatedProfiles());
req.setNoSnapshotUpdates(true);
req.setUpdateSnapshots(false);
req.setInteractiveMode(false);
req.setRecursive(false);
req.setOffline(true);
//#238800 important to merge, not replace
Properties uprops = req.getUserProperties();
uprops.putAll(MavenProjectCache.createUserPropsForProjectLoading(active.getProperties()));
req.setUserProperties(uprops);
ProjectBuildingRequest request = req.getProjectBuildingRequest();
request.setRemoteRepositories(project.getRemoteArtifactRepositories());
DefaultMaven maven = (DefaultMaven) embedder.lookupComponent(Maven.class);
request.setRepositorySession(maven.newRepositorySession(req));
if (project.getParentFile() != null) {
parent = builder.build(project.getParentFile(), request).getProject();
} else if (project.getModel().getParent() != null) {
parent = builder.build(project.getParentArtifact(), request).getProject();
}
//clear the project building request, it references multiple Maven Models via the RepositorySession cache
//is not used in maven itself, most likely used by m2e only..
if (parent != null) {
parent.setProjectBuildingRequest(null);
}
MavenEmbedder.normalizePaths(parent);
return parent;
}
private MavenProject loadMavenProject(File pom, String groupId, String artifactId, String version) {
MavenEmbedder embedder = EmbedderFactory.getProjectEmbedder();
Artifact projectArtifact = embedder.createArtifact(groupId, artifactId, version, "jar");
try {
ProjectBuildingRequest dpbr = embedder.createMavenExecutionRequest().getProjectBuildingRequest();
dpbr.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);
dpbr.setProcessPlugins(false);
dpbr.setResolveDependencies(true);
ArrayList<ArtifactRepository> remoteRepos = new ArrayList<ArtifactRepository>();
//for project embedder doens't matter
// remoteRepos = RepositoryPreferences.getInstance().remoteRepositories();
dpbr.setRemoteRepositories(remoteRepos);
ProjectBuildingResult res = embedder.buildProject(projectArtifact, dpbr);
if (res.getProject() != null) {
return res.getProject();
} else {
LOG.log(Level.INFO, "No project model from repository for {0}: {1}", new Object[] {projectArtifact, res.getProblems()});
}
} catch (ProjectBuildingException ex) {
LOG.log(Level.FINER, "Failed to load project model from repository for {0}: {1}", new Object[] {projectArtifact, ex});
} catch (Exception exception) {
LOG.log(Level.FINER, "Failed to load project model from repository for " + projectArtifact, exception);
}
return null;
}
private Relocation getRelocation(org.netbeans.modules.maven.model.pom.Dependency d) {
ProjectBuildingRequest dpbr = EmbedderFactory.getProjectEmbedder().createMavenExecutionRequest().getProjectBuildingRequest();
dpbr.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);
dpbr.setProcessPlugins(false);
dpbr.setResolveDependencies(false);
ArrayList<ArtifactRepository> remoteRepos = new ArrayList<>();
dpbr.setRemoteRepositories(remoteRepos);
String groupId = d.getGroupId();
String artifactId = d.getArtifactId();
String version = d.getVersion();
if(groupId != null && !"".equals(groupId.trim()) &&
artifactId != null && !"".equals(artifactId.trim()) &&
version != null && !"".equals(version.trim()))
{
MavenEmbedder embedder = EmbedderFactory.getProjectEmbedder();
Artifact a = embedder.createProjectArtifact(groupId, artifactId, version);
try {
ProjectBuildingResult r = embedder.buildProject(a, dpbr);
DistributionManagement dm = r.getProject().getDistributionManagement();
return dm != null ? dm.getRelocation() : null;
} catch (ProjectBuildingException ex) {
// just log and hope for the best ...
Logger.getLogger(DependencyNode.class.getName()).log(Level.INFO, version, ex);
}
}
return null;
}
private static List<Dependency> getDependenciesFromDM(MavenProject project, Project nbprj) {
NbMavenProjectImpl p = nbprj.getLookup().lookup(NbMavenProjectImpl.class);
MavenProject localProj = project;
DependencyManagement curDM;
List<Dependency> result = new ArrayList<Dependency>();
//mkleint: without the managementKey checks I got some entries multiple times.
// do we actually need to traverse the parent poms, are they completely resolved anyway?
//XXX
Set<String> knownKeys = new HashSet<String>();
while (localProj != null) {
curDM = localProj.getDependencyManagement();
if (curDM != null) {
@SuppressWarnings("unchecked")
List<Dependency> ds = curDM.getDependencies();
for (Dependency d : ds) {
if (knownKeys.contains(d.getManagementKey())) {
continue;
}
result.add(d);
knownKeys.add(d.getManagementKey());
}
}
try {
localProj = p.loadParentOf(EmbedderFactory.getProjectEmbedder(), localProj);
} catch (ProjectBuildingException x) {
break;
}
}
Collections.sort(result, new Comparator<Dependency>() {
@Override
public int compare(Dependency o1, Dependency o2) {
return o1.getManagementKey().compareTo(o2.getManagementKey());
}
});
return result;
}
static List<ModelProblem> runMavenValidationImpl(final File pom) {
//TODO profiles based on current configuration??
MavenEmbedder embedder = EmbedderFactory.getProjectEmbedder();
MavenExecutionRequest meReq = embedder.createMavenExecutionRequest();
ProjectBuildingRequest req = meReq.getProjectBuildingRequest();
req.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_1); // currently enables just <reporting> warning
req.setLocalRepository(embedder.getLocalRepository());
List<ArtifactRepository> remoteRepos = RepositoryPreferences.getInstance().remoteRepositories(embedder);
req.setRemoteRepositories(remoteRepos);
req.setRepositorySession(((DefaultMaven) embedder.lookupComponent(Maven.class)).newRepositorySession(meReq));
List<ModelProblem> problems;
try {
problems = embedder.lookupComponent(ProjectBuilder.class).build(pom, req).getProblems();
} catch (ProjectBuildingException x) {
problems = new ArrayList<ModelProblem>();
List<ProjectBuildingResult> results = x.getResults();
if (results != null) { //one code point throwing ProjectBuildingException contains results,
for (ProjectBuildingResult result : results) {
problems.addAll(result.getProblems());
}
} else {
// another code point throwing ProjectBuildingException doesn't contain results..
Throwable cause = x.getCause();
if (cause instanceof ModelBuildingException) {
problems.addAll(((ModelBuildingException) cause).getProblems());
}
}
}
return problems;
}
public ProjectBuildingResult buildProject(Artifact art, ProjectBuildingRequest req) throws ProjectBuildingException {
if (req.getLocalRepository() == null) {
req.setLocalRepository(getLocalRepository());
}
MavenExecutionRequest request = createMavenExecutionRequest();
req.setProcessPlugins(false);
req.setRepositorySession(maven.newRepositorySession(request));
ProjectBuildingResult res = projectBuilder.build(art, req);
normalizePaths(res.getProject());
return res;
}
static List<ModelProblem> runMavenValidationImpl(final File pom) {
MavenEmbedder embedder = EmbedderFactory.getProjectEmbedder();
MavenExecutionRequest meReq = embedder.createMavenExecutionRequest();
ProjectBuildingRequest req = meReq.getProjectBuildingRequest();
req.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_0); // 3.1 currently enables just <reporting> warning, see issue 223562 for details on why it's bad to show.
req.setLocalRepository(embedder.getLocalRepository());
List<ArtifactRepository> remoteRepos = RepositoryPreferences.getInstance().remoteRepositories(embedder);
req.setRemoteRepositories(remoteRepos);
req.setRepositorySession(((DefaultMaven) embedder.lookupComponent(Maven.class)).newRepositorySession(meReq));
List<ModelProblem> problems;
try {
problems = embedder.lookupComponent(ProjectBuilder.class).build(pom, req).getProblems();
} catch (ProjectBuildingException x) {
problems = new ArrayList<ModelProblem>();
List<ProjectBuildingResult> results = x.getResults();
if (results != null) { //one code point throwing ProjectBuildingException contains results,
for (ProjectBuildingResult result : results) {
problems.addAll(result.getProblems());
}
} else {
// another code point throwing ProjectBuildingException doesn't contain results..
Throwable cause = x.getCause();
if (cause instanceof ModelBuildingException) {
problems.addAll(((ModelBuildingException) cause).getProblems());
}
}
}
List<ModelProblem> toRet = new LinkedList<ModelProblem>();
for (ModelProblem problem : problems) {
if(ModelUtils.checkByCLIMavenValidationLevel(problem)) {
toRet.add(problem);
}
}
return toRet;
}
/**
* Finds the local root of the specified project.
*
* @param project The project to find the local root for.
* @return The local root project (this may be the current project)
*/
private MavenProject getLocalRoot( final MavenProject project ) throws IOException
{
MavenProject currentProject = project;
MavenProject localRootProject = project;
List<File> parentDirs = new ArrayList<>();
getAllParentDirectories( project.getBasedir(), parentDirs );
for (File parentDir : parentDirs) {
getLog().debug( "Checking to see if " + parentDir + " is an aggregator parent" );
File parent = new File( parentDir, "pom.xml" );
if ( parent.isFile() )
{
try
{
final ProjectBuildingResult result = projectBuilder.build( parent, session.getProjectBuildingRequest() );
final MavenProject parentProject = result.getProject();
final String currentProjectCanonicalPath = currentProject.getBasedir().getCanonicalPath();
if ( getAllChildModules( parentProject ).contains( currentProjectCanonicalPath ) )
{
getLog().debug( parentDir + " is an aggregator parent of current project " );
localRootProject = parentProject;
currentProject = parentProject;
}
else
{
getLog().debug( parentDir + " is not an aggregator parent of current project ("+getAllChildModules( parentProject )+"/"+currentProjectCanonicalPath+") " );
}
}
catch ( ProjectBuildingException e )
{
getLog().warn( e );
}
}
}
getLog().debug( "Local aggregation root is " + localRootProject.getBasedir() );
return localRootProject;
}
private ExtensionClassLoader createClassLoader(final Set<Artifact> artifacts, final ArtifactsHolder artifactsHolder)
throws MojoExecutionException, ProjectBuildingException {
final Artifact nar = removeNarArtifact(artifacts);
if (nar == null) {
final ExtensionClassLoader providedEntityClassLoader = createProvidedEntitiesClassLoader(artifactsHolder);
return createClassLoader(artifacts, providedEntityClassLoader, null);
}
final Set<Artifact> narDependencies = getNarDependencies(nar);
artifactsHolder.addArtifacts(narDependencies);
return createClassLoader(narDependencies, createClassLoader(narDependencies, artifactsHolder), nar);
}
private String determineProvidedEntityVersion(final Set<Artifact> artifacts, final String groupId, final String artifactId) throws ProjectBuildingException, MojoExecutionException {
getLog().debug("Determining provided entities for " + groupId + ":" + artifactId);
for (final Artifact artifact : artifacts) {
if (artifact.getGroupId().equals(groupId) && artifact.getArtifactId().equals(artifactId)) {
return artifact.getVersion();
}
}
return findProvidedDependencyVersion(artifacts, groupId, artifactId);
}
@Override
public void libertyCreate() throws PluginExecutionException {
try {
if (isUsingBoost()) {
log.info("Running boost:package");
runBoostMojo("package");
} else {
runLibertyMojoCreate();
}
} catch (MojoExecutionException | ProjectBuildingException e) {
throw new PluginExecutionException(e);
}
}
private void runBoostMojo(String goal)
throws MojoExecutionException, ProjectBuildingException {
MavenProject boostProject = this.project;
MavenSession boostSession = this.session;
log.debug("plugin version: " + boostPlugin.getVersion());
executeMojo(boostPlugin, goal(goal), configuration(),
executionEnvironment(boostProject, boostSession, pluginManager));
}
@Messages({
"Progress_Download=Downloading Maven dependencies for {0}",
"TIT_Error=Panel loading error.",
"BTN_CLOSE=&Close"
})
@NonNull private Lookup createViewerLookup(final @NullAllowed NBVersionInfo info, final @NonNull Artifact artifact, final @NullAllowed List<ArtifactRepository> fRepos) {
final InstanceContent ic = new InstanceContent();
AbstractLookup lookup = new AbstractLookup(ic);
ic.add(artifact);
if (info != null) {
ic.add(info);
}
final Artifact fArt = artifact;
RP.post(new Runnable() {
@Override
public void run() {
MavenEmbedder embedder = EmbedderFactory.getOnlineEmbedder();
AggregateProgressHandle hndl = AggregateProgressFactory.createHandle(Progress_Download(artifact.getId()),
new ProgressContributor[] {
AggregateProgressFactory.createProgressContributor("zaloha") }, //NOI18N
ProgressTransferListener.cancellable(), null);
ProgressTransferListener.setAggregateHandle(hndl);
hndl.start();
try {
List<ArtifactRepository> repos = new ArrayList<ArtifactRepository>();
if (fRepos != null) {
repos.addAll(fRepos);
}
if (repos.isEmpty()) {
//add central repo
repos.add(embedder.createRemoteRepository(RepositorySystem.DEFAULT_REMOTE_REPO_URL, RepositorySystem.DEFAULT_REMOTE_REPO_ID));
//add repository form info
if (info != null && !RepositorySystem.DEFAULT_REMOTE_REPO_ID.equals(info.getRepoId())) {
RepositoryInfo rinfo = RepositoryPreferences.getInstance().getRepositoryInfoById(info.getRepoId());
if (rinfo != null) {
String url = rinfo.getRepositoryUrl();
if (url != null) {
repos.add(embedder.createRemoteRepository(url, rinfo.getId()));
}
}
}
}
MavenProject mvnprj = readMavenProject(embedder, fArt, repos);
if(mvnprj != null){
DependencyNode root = DependencyTreeFactory.createDependencyTree(mvnprj, embedder, Artifact.SCOPE_TEST);
ic.add(root);
ic.add(mvnprj);
}
} catch (ProjectBuildingException ex) {
ErrorPanel pnl = new ErrorPanel(ex);
DialogDescriptor dd = new DialogDescriptor(pnl, TIT_Error());
JButton close = new JButton();
org.openide.awt.Mnemonics.setLocalizedText(close, BTN_CLOSE());
dd.setOptions(new Object[] { close });
dd.setClosingOptions(new Object[] { close });
DialogDisplayer.getDefault().notify(dd);
ic.add(new MavenProject()); // XXX is this useful for anything?
} catch (ThreadDeath d) { // download interrupted
} catch (IllegalStateException ise) { //download interrupted in dependent thread. #213812
if (!(ise.getCause() instanceof ThreadDeath)) {
throw ise;
}
} finally {
hndl.finish();
ProgressTransferListener.clearAggregateHandle();
}
}
});
Action[] toolbarActions = new Action[] {
new AddAsDependencyAction(fArt),
CommonArtifactActions.createScmCheckoutAction(lookup),
CommonArtifactActions.createLibraryAction(lookup)
};
ic.add(toolbarActions);
return lookup;
}
@NbBundle.Messages({
"TXT_Artifact_Resolution_problem=Artifact Resolution problem",
"TXT_Artifact_Not_Found=Artifact Not Found",
"TXT_Cannot_Load_Project=Unable to properly load project",
"TXT_Cannot_read_model=Error reading project model",
"TXT_NoMsg=Exception thrown while loading maven project at {0}. See messages.log for more information."
})
private Collection<ProjectProblem> reportExceptions(MavenExecutionResult res) {
List<ProjectProblem> toRet = new ArrayList<ProjectProblem>();
for (Throwable e : res.getExceptions()) {
LOG.log(Level.FINE, "Error on loading project " + project.getProjectDirectory(), e);
if (e instanceof ArtifactResolutionException) { // XXX when does this occur?
toRet.add(ProjectProblem.createError(TXT_Artifact_Resolution_problem(), getDescriptionText(e)));
problemReporter.addMissingArtifact(((ArtifactResolutionException) e).getArtifact());
} else if (e instanceof ArtifactNotFoundException) { // XXX when does this occur?
toRet.add(ProjectProblem.createError(TXT_Artifact_Not_Found(), getDescriptionText(e)));
problemReporter.addMissingArtifact(((ArtifactNotFoundException) e).getArtifact());
} else if (e instanceof ProjectBuildingException) {
toRet.add(ProjectProblem.createError(TXT_Cannot_Load_Project(), getDescriptionText(e), new SanityBuildAction(project)));
if (e.getCause() instanceof ModelBuildingException) {
ModelBuildingException mbe = (ModelBuildingException) e.getCause();
for (ModelProblem mp : mbe.getProblems()) {
LOG.log(Level.FINE, mp.toString(), mp.getException());
if (mp.getException() instanceof UnresolvableModelException) {
// Probably obsoleted by ProblemReporterImpl.checkParent, but just in case:
UnresolvableModelException ume = (UnresolvableModelException) mp.getException();
problemReporter.addMissingArtifact(EmbedderFactory.getProjectEmbedder().createProjectArtifact(ume.getGroupId(), ume.getArtifactId(), ume.getVersion()));
} else if (mp.getException() instanceof PluginResolutionException) {
Plugin plugin = ((PluginResolutionException) mp.getException()).getPlugin();
// XXX this is not actually accurate; should rather pick out the ArtifactResolutionException & ArtifactNotFoundException inside
problemReporter.addMissingArtifact(EmbedderFactory.getProjectEmbedder().createArtifact(plugin.getGroupId(), plugin.getArtifactId(), plugin.getVersion(), "jar"));
} else if (mp.getException() instanceof PluginManagerException) {
PluginManagerException ex = (PluginManagerException) mp.getException();
problemReporter.addMissingArtifact(EmbedderFactory.getProjectEmbedder().createArtifact(ex.getPluginGroupId(), ex.getPluginArtifactId(), ex.getPluginVersion(), "jar"));
}
}
}
} else {
String msg = e.getMessage();
if(msg != null) {
LOG.log(Level.INFO, "Exception thrown while loading maven project at " + project.getProjectDirectory(), e); //NOI18N
toRet.add(ProjectProblem.createError(TXT_Cannot_read_model(), msg));
} else {
String path = project.getProjectDirectory().getPath();
toRet.add(ProjectProblem.createError(TXT_Cannot_read_model(), TXT_NoMsg(path)));
LOG.log(Level.WARNING, "Exception thrown while loading maven project at " + path, e); //NOI18N
}
}
}
return toRet;
}
/**
* @param isPlugins <code>true</code> to use <code>plugins</code> variable, <code>false</code> to use
* <code>reports</code> variable.
*/
private void renderSectionPlugins( boolean isPlugins )
{
List<Artifact> list = ( isPlugins ? plugins : reports );
String[] tableHeader = getPluginTableHeader();
startSection( ( isPlugins ? getReportString( "report.plugins.title" )
: getReportString( "report.plugins.report.title" ) ) );
if ( list == null || list.isEmpty() )
{
paragraph( ( isPlugins ? getReportString( "report.plugins.nolist" )
: getReportString( "report.plugins.report.nolist" ) ) );
endSection();
return;
}
Collections.sort( list, getArtifactComparator() );
startTable();
tableHeader( tableHeader );
for ( Iterator<Artifact> iterator = list.iterator(); iterator.hasNext(); )
{
Artifact artifact = (Artifact) iterator.next();
VersionRange versionRange;
if ( StringUtils.isEmpty( artifact.getVersion() ) )
{
versionRange = VersionRange.createFromVersion( Artifact.RELEASE_VERSION );
}
else
{
versionRange = VersionRange.createFromVersion( artifact.getVersion() );
}
Artifact pluginArtifact = artifactFactory.createParentArtifact( artifact.getGroupId(), artifact
.getArtifactId(), versionRange.toString() );
List<?> artifactRepositories = project.getPluginArtifactRepositories();
if ( artifactRepositories == null )
{
artifactRepositories = new ArrayList<>();
}
try
{
MavenProject pluginProject = mavenProjectBuilder.buildFromRepository( pluginArtifact,
artifactRepositories,
localRepository );
tableRow( getPluginRow( pluginProject.getGroupId(), pluginProject.getArtifactId(), pluginProject
.getVersion(), pluginProject.getUrl() ) );
}
catch ( ProjectBuildingException e )
{
log.info( "Could not build project for: " + artifact.getArtifactId() + ":" + e.getMessage(), e );
tableRow( getPluginRow( artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(),
null ) );
}
}
endTable();
endSection();
}
private void printDescriptionsAndURLs( ReportingResolutionListener.Node node )
{
Artifact artifact = node.getArtifact();
String id = artifact.getDependencyConflictId();
if ( !Artifact.SCOPE_SYSTEM.equals( artifact.getScope() ) )
{
try
{
MavenProject artifactProject = getMavenProjectFromRepository( artifact, localRepository );
String artifactDescription = artifactProject.getDescription();
String artifactUrl = artifactProject.getUrl();
String artifactName = artifactProject.getName();
sink.paragraph();
sink.anchor( id );
sink.bold();
sink.text( artifactName );
sink.bold_();
sink.anchor_();
sink.paragraph_();
if ( artifactDescription != null )
{
sink.paragraph();
sink.text( artifactDescription );
sink.paragraph_();
}
if ( artifactUrl != null )
{
sink.paragraph();
sink.link( artifactUrl );
sink.text( artifactUrl );
sink.link_();
sink.paragraph_();
}
}
catch ( ProjectBuildingException e )
{
log.debug( e );
}
node.getChildren().forEach( dep -> printDescriptionsAndURLs( dep ));
}
else
{
sink.paragraph();
sink.anchor( id );
sink.bold();
sink.text( id );
sink.bold_();
sink.anchor_();
sink.paragraph_();
sink.paragraph();
sink.text( artifact.getFile().toString() );
sink.paragraph_();
}
}
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
try {
// find the nar dependency
Artifact narArtifact = null;
for (final Artifact artifact : project.getDependencyArtifacts()) {
if (NAR.equals(artifact.getType())) {
// ensure the project doesn't have two nar dependencies
if (narArtifact != null) {
throw new MojoExecutionException("Project can only have one NAR dependency.");
}
// record the nar dependency
narArtifact = artifact;
}
}
// ensure there is a nar dependency
if (narArtifact == null) {
throw new MojoExecutionException("Project does not have any NAR dependencies.");
}
// build the project for the nar artifact
final ProjectBuildingRequest narRequest = new DefaultProjectBuildingRequest();
narRequest.setRepositorySession(repoSession);
narRequest.setSystemProperties(System.getProperties());
final ProjectBuildingResult narResult = projectBuilder.build(narArtifact, narRequest);
narRequest.setProject(narResult.getProject());
// get the artifact handler for excluding dependencies
final ArtifactHandler narHandler = excludesDependencies(narArtifact);
narArtifact.setArtifactHandler(narHandler);
// nar artifacts by nature includes dependencies, however this prevents the
// transitive dependencies from printing using tools like dependency:tree.
// here we are overriding the artifact handler for all nars so the
// dependencies can be listed. this is important because nar dependencies
// will be used as the parent classloader for this nar and seeing what
// dependencies are provided is critical.
final Map<String, ArtifactHandler> narHandlerMap = new HashMap<>();
narHandlerMap.put(NAR, narHandler);
artifactHandlerManager.addHandlers(narHandlerMap);
// get the dependency tree
final DependencyNode root = dependencyGraphBuilder.buildDependencyGraph(narRequest, null);
// write the appropriate output
DependencyNodeVisitor visitor = null;
if ("tree".equals(mode)) {
visitor = new TreeWriter();
} else if ("pom".equals(mode)) {
visitor = new PomWriter();
}
// ensure the mode was specified correctly
if (visitor == null) {
throw new MojoExecutionException("The specified mode is invalid. Supported options are 'tree' and 'pom'.");
}
// visit and print the results
root.accept(visitor);
getLog().info("--- Provided NAR Dependencies ---\n\n" + visitor.toString());
} catch (ProjectBuildingException | DependencyGraphBuilderException e) {
throw new MojoExecutionException("Cannot build project dependency tree", e);
}
}