List of usage examples for org.apache.maven.project MavenProject getDependencyManagement
public DependencyManagement getDependencyManagement()
From source file:net.oneandone.maven.rules.common.AbstractFilterableRule.java
License:Apache License
protected void compareDependenciesWithParentManagement(MavenProject project, Log log, DifferenceHandler differenceHandler) { if (project.getParent() != null) { List<Dependency> projectDependencies = project.getDependencies(); if (project.getDependencyManagement() != null) { projectDependencies.addAll(project.getDependencyManagement().getDependencies()); }/*w ww. j a va 2s.c om*/ ImmutableListMultimap<String, Dependency> parentProjectDependencies = RuleHelper .getManagedDependenciesAsMap(project.getParent()); for (Dependency dependency : projectDependencies) { ImmutableList<Dependency> parentDependencies = parentProjectDependencies .get(RuleHelper.getDependencyIdentifier(dependency)); if (parentDependencies != null && !isExcluded(dependency.getManagementKey())) { for (Dependency parentDependency : parentDependencies) { if (dependency.getManagementKey().equals(parentDependency.getManagementKey())) { if (!dependency.getVersion().equals(parentDependency.getVersion())) { differenceHandler.handleDifference(log, dependency, parentDependency); } break; } } } } } }
From source file:net.oneandone.maven.rules.common.AbstractRule.java
License:Apache License
protected boolean projectHasManagedDependencies(MavenProject project) { return project.getDependencyManagement() != null && !project.getDependencyManagement().getDependencies().isEmpty(); }
From source file:net.oneandone.maven.rules.common.RuleHelper.java
License:Apache License
public static ImmutableListMultimap<String, Dependency> getManagedDependenciesAsMap(MavenProject project) { if (project.getDependencyManagement() != null) { return Multimaps.index(project.getDependencyManagement().getDependencies(), new Function<Dependency, String>() { public String apply(Dependency from) { if (from != null) { return from.getGroupId() + ":" + from.getArtifactId(); }//from w ww . ja v a 2 s. co m return null; } }); } return ImmutableListMultimap.of(); }
From source file:org.apache.tuscany.maven.plugin.eclipse.AbstractIdeSupportMojo.java
License:Apache License
/** * Resolve project dependencies. Manual resolution is needed in order to avoid resolution of multiproject artifacts * (if projects will be linked each other an installed jar is not needed) and to avoid a failure when a jar is * missing.//from ww w. j a v a 2 s. c o m * * @throws MojoExecutionException if dependencies can't be resolved * @return resolved IDE dependencies, with attached jars for non-reactor dependencies */ protected IdeDependency[] doDependencyResolution() throws MojoExecutionException { if (ideDeps == null) { if (resolveDependencies) { MavenProject project = getProject(); Set<String> imported = Collections.emptySet(); try { imported = BundleUtil.getImportedPackages(project.getBasedir()); } catch (IOException e1) { throw new MojoExecutionException(e1.getMessage(), e1); } ArtifactRepository localRepo = getLocalRepository(); List deps = getProject().getDependencies(); // Collect the list of resolved IdeDependencies. List dependencies = new ArrayList(); if (deps != null) { Map managedVersions = createManagedVersionMap(getArtifactFactory(), project.getId(), project.getDependencyManagement()); ArtifactResolutionResult artifactResolutionResult = null; try { List listeners = new ArrayList(); if (logger.isDebugEnabled()) { listeners.add(new DebugResolutionListener(logger)); } listeners.add(new WarningResolutionListener(logger)); artifactResolutionResult = artifactCollector.collect(getProjectArtifacts(), project.getArtifact(), managedVersions, localRepo, project.getRemoteArtifactRepositories(), getArtifactMetadataSource(), null, listeners); } catch (ArtifactResolutionException e) { getLog().debug(e.getMessage(), e); getLog().error( Messages.getString("AbstractIdeSupportMojo.artifactresolution", new Object[] { //$NON-NLS-1$ e.getGroupId(), e.getArtifactId(), e.getVersion(), e.getMessage() })); // if we are here artifactResolutionResult is null, create a project without dependencies but // don't fail // (this could be a reactor projects, we don't want to fail everything) // Causes MECLIPSE-185. Not sure if it should be handled this way?? return new IdeDependency[0]; } // keep track of added reactor projects in order to avoid duplicates Set emittedReactorProjectId = new HashSet(); for (Iterator i = artifactResolutionResult.getArtifactResolutionNodes().iterator(); i .hasNext();) { ResolutionNode node = (ResolutionNode) i.next(); int dependencyDepth = node.getDepth(); Artifact art = node.getArtifact(); // don't resolve jars for reactor projects if (hasToResolveJar(art)) { try { artifactResolver.resolve(art, node.getRemoteRepositories(), localRepository); } catch (ArtifactNotFoundException e) { getLog().debug(e.getMessage(), e); getLog().warn(Messages.getString("AbstractIdeSupportMojo.artifactdownload", //$NON-NLS-1$ new Object[] { e.getGroupId(), e.getArtifactId(), e.getVersion(), e.getMessage() })); } catch (ArtifactResolutionException e) { getLog().debug(e.getMessage(), e); getLog().warn(Messages.getString("AbstractIdeSupportMojo.artifactresolution", //$NON-NLS-1$ new Object[] { e.getGroupId(), e.getArtifactId(), e.getVersion(), e.getMessage() })); } } boolean includeArtifact = true; if (getExcludes() != null) { String artifactFullId = art.getGroupId() + ":" + art.getArtifactId(); if (getExcludes().contains(artifactFullId)) { getLog().info("excluded: " + artifactFullId); includeArtifact = false; } } if (includeArtifact && (!(getUseProjectReferences() && isAvailableAsAReactorProject(art)) || emittedReactorProjectId.add(art.getGroupId() + '-' + art.getArtifactId()))) { // the following doesn't work: art.getArtifactHandler().getPackaging() always returns "jar" // also // if the packaging specified in pom.xml is different. // osgi-bundle packaging is provided by the felix osgi plugin // eclipse-plugin packaging is provided by this eclipse plugin // String packaging = art.getArtifactHandler().getPackaging(); // boolean isOsgiBundle = "osgi-bundle".equals( packaging ) || "eclipse-plugin".equals( // packaging ); // we need to check the manifest, if "Bundle-SymbolicName" is there the artifact can be // considered // an osgi bundle if ("pom".equals(art.getType())) { continue; } File artifactFile = art.getFile(); MavenProject reactorProject = getReactorProject(art); if (reactorProject != null) { artifactFile = reactorProject.getBasedir(); } boolean isOsgiBundle = false; String osgiSymbolicName = null; try { osgiSymbolicName = BundleUtil.getBundleSymbolicName(artifactFile); } catch (IOException e) { getLog().error("Unable to read jar manifest from " + artifactFile, e); } isOsgiBundle = osgiSymbolicName != null; IdeDependency dep = new IdeDependency(art.getGroupId(), art.getArtifactId(), art.getVersion(), art.getClassifier(), useProjectReference(art), Artifact.SCOPE_TEST.equals(art.getScope()), Artifact.SCOPE_SYSTEM.equals(art.getScope()), Artifact.SCOPE_PROVIDED.equals(art.getScope()), art.getArtifactHandler().isAddedToClasspath(), art.getFile(), art.getType(), isOsgiBundle, osgiSymbolicName, dependencyDepth, getProjectNameForArifact(art)); // no duplicate entries allowed. System paths can cause this problem. if (!dependencies.contains(dep)) { // [rfeng] Do not add compile/provided dependencies if (!(pde && (Artifact.SCOPE_COMPILE.equals(art.getScope()) || Artifact.SCOPE_PROVIDED.equals(art.getScope())))) { dependencies.add(dep); } else { // Check this compile dependency is an OSGi package supplier if (!imported.isEmpty()) { Set<String> exported = Collections.emptySet(); try { exported = BundleUtil.getExportedPackages(artifactFile); } catch (IOException e) { getLog().error("Unable to read jar manifest from " + art.getFile(), e); } boolean matched = false; for (String p : imported) { if (exported.contains(p)) { matched = true; break; } } if (!matched) { dependencies.add(dep); } else { getLog().debug( "Compile dependency is skipped as it is added through OSGi dependency: " + art); } } else { dependencies.add(dep); } } } } } // @todo a final report with the list of // missingArtifacts? } ideDeps = (IdeDependency[]) dependencies.toArray(new IdeDependency[dependencies.size()]); } else { ideDeps = new IdeDependency[0]; } } return ideDeps; }
From source file:org.codehaus.mojo.pluginsupport.dependency.DependencyHelper.java
License:Apache License
public static Map getManagedVersionMap(final MavenProject project, final ArtifactFactory factory) throws ProjectBuildingException { assert project != null; assert factory != null; DependencyManagement dependencyManagement = project.getDependencyManagement(); Map managedVersionMap;//from w w w . java 2s. c om if (dependencyManagement != null && dependencyManagement.getDependencies() != null) { managedVersionMap = new HashMap(); Iterator iter = dependencyManagement.getDependencies().iterator(); while (iter.hasNext()) { Dependency d = (Dependency) iter.next(); try { VersionRange versionRange = VersionRange.createFromVersionSpec(d.getVersion()); Artifact artifact = factory.createDependencyArtifact(d.getGroupId(), d.getArtifactId(), versionRange, d.getType(), d.getClassifier(), d.getScope()); managedVersionMap.put(d.getManagementKey(), artifact); } catch (InvalidVersionSpecificationException e) { throw new ProjectBuildingException(project.getId(), "Unable to parse version '" + d.getVersion() + "' for dependency '" + d.getManagementKey() + "': " + e.getMessage(), e); } } } else { managedVersionMap = Collections.EMPTY_MAP; } return managedVersionMap; }
From source file:org.codehaus.mojo.pom.PomRefactorMojo.java
License:Apache License
/** * {@inheritDoc}// ww w.ja va2 s. co m */ @Override @SuppressWarnings("unchecked") public void execute(ProjectContainer projectContainer) throws MojoExecutionException, MojoFailureException { if (getNewAttributes().isEmpty()) { throw new MojoExecutionException( "At least one of the new*-parameters (newVersion, newArtifactId, newGroupId, newScope or newClassifier) have to be configured!"); } super.execute(projectContainer); MavenProject project = projectContainer.getProject(); updateProject(projectContainer, project, false); MavenProject parent = project.getParent(); if (parent != null) { updateProject(projectContainer, parent, true); } updateDependencies(project.getDependencies(), projectContainer, ProjectContainer.XML_TAG_DEPENDENCIES); DependencyManagement dependencyManagement = project.getDependencyManagement(); if (dependencyManagement != null) { updateDependencies(dependencyManagement.getDependencies(), projectContainer, ProjectContainer.XML_TAG_DEPENDENCY_MANAGEMENT); } }
From source file:org.codehaus.mojo.versions.CompareDependenciesMojo.java
License:Apache License
/** * @param pom the pom to update.//from ww w. java 2 s . co m * @throws org.apache.maven.plugin.MojoExecutionException * Something wrong with the plugin itself * @throws org.apache.maven.plugin.MojoFailureException * The plugin detected an error in the build * @throws javax.xml.stream.XMLStreamException * when things go wrong with XML streaming * @see AbstractVersionsUpdaterMojo#update(org.codehaus.mojo.versions.rewriting.ModifiedPomXMLEventReader) */ protected void update(ModifiedPomXMLEventReader pom) throws MojoExecutionException, MojoFailureException, XMLStreamException { if (this.ignoreRemoteDependencies && this.ignoreRemoteDependencyManagement) { throw new MojoFailureException(" ignoreRemoteDependencies and ignoreRemoteDependencyManagement" + "are both set to true. At least one of these needs to be false "); } if (updateDependencies) { reportMode = false; } String[] remotePomParts = this.remotePom.split(":"); if (remotePomParts.length != 3) { throw new MojoFailureException(" Invalid format for remotePom: " + remotePom); } String rGroupId = remotePomParts[0]; String rArtifactId = remotePomParts[1]; String rVersion = remotePomParts[2]; Dependency remoteDependency = new Dependency(); remoteDependency.setGroupId(rGroupId); remoteDependency.setArtifactId(rArtifactId); remoteDependency.setVersion(rVersion); Artifact remoteArtifact = this.toArtifact(remoteDependency); MavenProject remoteMavenProject = null; try { remoteMavenProject = mavenProjectBuilder.buildFromRepository(remoteArtifact, remoteArtifactRepositories, localRepository); } catch (ProjectBuildingException e) { throw new MojoExecutionException("Unable to build remote project " + remoteArtifact, e); } Map<String, Dependency> remoteDepsMap = new HashMap<String, Dependency>(); if (!ignoreRemoteDependencyManagement) { List<Dependency> remoteProjectDepMgmtDeps = (remoteMavenProject.getDependencyManagement() == null) ? null : remoteMavenProject.getDependencyManagement().getDependencies(); mapDependencies(remoteDepsMap, remoteProjectDepMgmtDeps); } if (!ignoreRemoteDependencies) { List<Dependency> remoteProjectDeps = remoteMavenProject.getDependencies(); mapDependencies(remoteDepsMap, remoteProjectDeps); } List<String> totalDiffs = new ArrayList<String>(); List<String> propertyDiffs = new ArrayList<String>(); if (getProject().getDependencyManagement() != null && isProcessingDependencyManagement()) { List<String> depManDiffs = compareVersions(pom, getProject().getDependencyManagement().getDependencies(), remoteDepsMap); totalDiffs.addAll(depManDiffs); } if (isProcessingDependencies()) { List<String> depDiffs = compareVersions(pom, getProject().getDependencies(), remoteDepsMap); totalDiffs.addAll(depDiffs); } if (updatePropertyVersions) { Map<Property, PropertyVersions> versionProperties = this.getHelper() .getVersionPropertiesMap(getProject(), null, null, null, true); List<String> diff = updatePropertyVersions(pom, versionProperties, remoteDepsMap); propertyDiffs.addAll(diff); } if (reportMode) { getLog().info("The following differences were found:"); if (totalDiffs.size() == 0) { getLog().info(" none"); } else { for (String totalDiff : totalDiffs) { getLog().info(" " + totalDiff); } } getLog().info("The following property differences were found:"); if (propertyDiffs.size() == 0) { getLog().info(" none"); } else { for (String propertyDiff : propertyDiffs) { getLog().info(" " + propertyDiff); } } } if (reportOutputFile != null) { writeReportFile(totalDiffs, propertyDiffs); } }
From source file:org.commonjava.emb.project.graph.DependencyGraphResolver.java
License:Apache License
private DependencyGraph accumulate(final ProjectToolsSession session, final RepositorySystemSession rss, final Collection<MavenProject> projects, final RemoteRepository... remoteRepositories) { final ArtifactTypeRegistry stereotypes = rss.getArtifactTypeRegistry(); final DependencyGraph depGraph = session.getDependencyGraph(); final GraphAccumulator accumulator = new GraphAccumulator(depGraph); for (final MavenProject project : projects) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Collecting dependencies for: " + project); }/*from ww w .j ava2 s.c o m*/ final CollectRequest request = new CollectRequest(); request.setRequestContext("project"); request.setRepositories(Arrays.asList(remoteRepositories)); if (project.getDependencyArtifacts() == null) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Adding dependencies to collection request..."); } for (final Dependency dependency : project.getDependencies()) { request.addDependency(RepositoryUtils.toDependency(dependency, stereotypes)); } } else { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Mapping project dependencies by management key..."); } final Map<String, Dependency> dependencies = new HashMap<String, Dependency>(); for (final Dependency dependency : project.getDependencies()) { final String key = dependency.getManagementKey(); dependencies.put(key, dependency); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Adding dependencies to collection request..."); } for (final org.apache.maven.artifact.Artifact artifact : project.getDependencyArtifacts()) { final String key = artifact.getDependencyConflictId(); final Dependency dependency = dependencies.get(key); final Collection<org.apache.maven.model.Exclusion> exclusions = dependency != null ? dependency.getExclusions() : null; org.sonatype.aether.graph.Dependency dep = RepositoryUtils.toDependency(artifact, exclusions); if (!JavaScopes.SYSTEM.equals(dep.getScope()) && dep.getArtifact().getFile() != null) { // enable re-resolution org.sonatype.aether.artifact.Artifact art = dep.getArtifact(); art = art.setFile(null).setVersion(art.getBaseVersion()); dep = dep.setArtifact(art); } request.addDependency(dep); } } final DependencyManagement depMngt = project.getDependencyManagement(); if (depMngt != null) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Adding managed dependencies to collection request..."); } for (final Dependency dependency : depMngt.getDependencies()) { request.addManagedDependency(RepositoryUtils.toDependency(dependency, stereotypes)); } } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Collecting dependencies..."); } CollectResult result; try { result = repositorySystem.collectDependencies(rss, request); } catch (final DependencyCollectionException e) { // TODO: Handle problem resolving POMs... result = e.getResult(); // result.setDependencyGraph( e.getResult().getRoot() ); // result.setCollectionErrors( e.getResult().getExceptions() ); // // throw new DependencyResolutionException( result, "Could not resolve dependencies for project " // + project.getId() + ": " + e.getMessage(), e ); } final DependencyNode root = result.getRoot(); final DepGraphRootNode rootNode = depGraph.addRoot(root, project); accumulator.resetForNextRun(root, rootNode); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Adding collected dependencies to consolidated dependency graph..."); } result.getRoot().accept(accumulator); } return depGraph; }
From source file:org.commonjava.maven.plugins.betterdep.AbstractDepgraphGoal.java
License:Open Source License
protected void readFromReactorProjects() throws MojoExecutionException { getLog().info("Initializing direct graph relationships from reactor projects: " + projects); for (final MavenProject project : projects) { final List<Profile> activeProfiles = project.getActiveProfiles(); if (activeProfiles != null) { for (final Profile profile : activeProfiles) { profiles.add(RelationshipUtils.profileLocation(profile.getId())); }//from w w w.j a v a2 s. c om } final ProjectVersionRef projectRef = new SimpleProjectVersionRef(project.getGroupId(), project.getArtifactId(), project.getVersion()); roots.add(projectRef); final List<Dependency> deps = project.getDependencies(); // final List<ProjectVersionRef> roots = new ArrayList<ProjectVersionRef>( deps.size() ); URI localUri; try { localUri = new URI(MavenLocationExpander.LOCAL_URI); } catch (final URISyntaxException e) { throw new MojoExecutionException( "Failed to construct dummy local URI to use as the source of the current project in the depgraph: " + e.getMessage(), e); } final int index = 0; for (final Dependency dep : deps) { final ProjectVersionRef depRef = new SimpleProjectVersionRef(dep.getGroupId(), dep.getArtifactId(), dep.getVersion()); // roots.add( depRef ); final List<Exclusion> exclusions = dep.getExclusions(); final List<ProjectRef> excludes = new ArrayList<ProjectRef>(); if (exclusions != null && !exclusions.isEmpty()) { for (final Exclusion exclusion : exclusions) { excludes.add(new SimpleProjectRef(exclusion.getGroupId(), exclusion.getArtifactId())); } } rootRels.add(new SimpleDependencyRelationship(localUri, projectRef, new SimpleArtifactRef(depRef, dep.getType(), dep.getClassifier(), dep.isOptional()), DependencyScope.getScope(dep.getScope()), index, false, excludes.toArray(new ProjectRef[excludes.size()]))); } final DependencyManagement dm = project.getDependencyManagement(); if (dm != null) { final List<Dependency> managed = dm.getDependencies(); int i = 0; for (final Dependency dep : managed) { if ("pom".equals(dep.getType()) && "import".equals(dep.getScope())) { final ProjectVersionRef depRef = new SimpleProjectVersionRef(dep.getGroupId(), dep.getArtifactId(), dep.getVersion()); rootRels.add(new SimpleBomRelationship(localUri, projectRef, depRef, i++)); } } } ProjectVersionRef lastParent = projectRef; MavenProject parent = project.getParent(); while (parent != null) { final ProjectVersionRef parentRef = new SimpleProjectVersionRef(parent.getGroupId(), parent.getArtifactId(), parent.getVersion()); rootRels.add(new SimpleParentRelationship(localUri, projectRef, parentRef)); lastParent = parentRef; parent = parent.getParent(); } rootRels.add(new SimpleParentRelationship(lastParent)); } }
From source file:org.eclipse.m2e.core.embedder.MavenModelManager.java
License:Open Source License
DependencyNode readDependencyTree(RepositorySystemSession repositorySession, MavenProject mavenProject, String scope) throws CoreException { DefaultRepositorySystemSession session = new DefaultRepositorySystemSession(repositorySession); DependencyGraphTransformer transformer = new ChainedDependencyGraphTransformer( new JavaEffectiveScopeCalculator(), new NearestVersionConflictResolver()); session.setDependencyGraphTransformer(transformer); ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); try {//w ww. j a v a 2 s . c o m Thread.currentThread().setContextClassLoader(maven.getProjectRealm(mavenProject)); ArtifactTypeRegistry stereotypes = session.getArtifactTypeRegistry(); CollectRequest request = new CollectRequest(); request.setRequestContext("project"); //$NON-NLS-1$ request.setRepositories(mavenProject.getRemoteProjectRepositories()); for (org.apache.maven.model.Dependency dependency : mavenProject.getDependencies()) { request.addDependency(RepositoryUtils.toDependency(dependency, stereotypes)); } DependencyManagement depMngt = mavenProject.getDependencyManagement(); if (depMngt != null) { for (org.apache.maven.model.Dependency dependency : depMngt.getDependencies()) { request.addManagedDependency(RepositoryUtils.toDependency(dependency, stereotypes)); } } DependencyNode node; try { node = MavenPluginActivator.getDefault().getRepositorySystem().collectDependencies(session, request) .getRoot(); } catch (DependencyCollectionException ex) { String msg = Messages.MavenModelManager_error_read; log.error(msg, ex); throw new CoreException(new Status(IStatus.ERROR, IMavenConstants.PLUGIN_ID, -1, msg, ex)); } Collection<String> scopes = new HashSet<String>(); Collections.addAll(scopes, Artifact.SCOPE_SYSTEM, Artifact.SCOPE_COMPILE, Artifact.SCOPE_PROVIDED, Artifact.SCOPE_RUNTIME, Artifact.SCOPE_TEST); if (Artifact.SCOPE_COMPILE.equals(scope)) { scopes.remove(Artifact.SCOPE_COMPILE); scopes.remove(Artifact.SCOPE_SYSTEM); scopes.remove(Artifact.SCOPE_PROVIDED); } else if (Artifact.SCOPE_RUNTIME.equals(scope)) { scopes.remove(Artifact.SCOPE_COMPILE); scopes.remove(Artifact.SCOPE_RUNTIME); } else if (Artifact.SCOPE_COMPILE_PLUS_RUNTIME.equals(scope)) { scopes.remove(Artifact.SCOPE_COMPILE); scopes.remove(Artifact.SCOPE_SYSTEM); scopes.remove(Artifact.SCOPE_PROVIDED); scopes.remove(Artifact.SCOPE_RUNTIME); } else { scopes.clear(); } CloningDependencyVisitor cloner = new CloningDependencyVisitor(); node.accept(new FilteringDependencyVisitor(cloner, new ScopeDependencyFilter(null, scopes))); node = cloner.getRootNode(); return node; } finally { Thread.currentThread().setContextClassLoader(oldClassLoader); } }