Java Code Examples for org.apache.maven.model.Dependency

The following examples show how to use org.apache.maven.model.Dependency. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: yaks   Source File: YamlFileDependencyLoader.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected List<Dependency> load(Path filePath, Properties properties, Logger logger) throws LifecycleExecutionException {
    try {
        List<Dependency> dependencyList = new ArrayList<>();
        Yaml yaml = new Yaml();

        HashMap<String, List<Map<String, Object>>> root = yaml.load(new StringReader(new String(Files.readAllBytes(filePath), StandardCharsets.UTF_8)));
        if (root.containsKey("dependencies")) {
            for (Map<String, Object> coordinates : root.get("dependencies")) {
                Dependency dependency = new Dependency();
                dependency.setGroupId(Objects.toString(coordinates.get("groupId")));
                dependency.setArtifactId(Objects.toString(coordinates.get("artifactId")));
                dependency.setVersion(resolveVersionProperty(Objects.toString(coordinates.get("version")), properties));

                logger.info(String.format("Add %s", dependency));
                dependencyList.add(dependency);
            }
        }

        return dependencyList;
    } catch (IOException e) {
        throw new LifecycleExecutionException("Failed to read dependency configuration file", e);
    }
}
 
Example 2
private Multimap<ArtifactCoordinates, ArtifactCoordinates> getSnapshots(MavenProject project,
    PomPropertyResolver propertyResolver) {
  this.log.debug("\t\tChecking direct plugin references");
  Multimap<ArtifactCoordinates, ArtifactCoordinates> result = HashMultimap.create();
  Build build = project.getBuild();
  if (build != null) {
    for (Plugin plugin : build.getPlugins()) {
      Collection<Dependency> snapshots = Collections2.filter(plugin.getDependencies(),
          new IsSnapshotDependency(propertyResolver));
      if (!snapshots.isEmpty()) {
        result.putAll(PluginToCoordinates.INSTANCE.apply(plugin),
            Collections2.transform(snapshots, DependencyToCoordinates.INSTANCE));
      }
    }
  }
  return result;
}
 
Example 3
Source Project: butterfly   Source File: PomAddDependencyTest.java    License: MIT License 6 votes vote down vote up
/**
 * Get dependency list from a maven model. Note: This is needed because
 * {@link AbstractArtifactPomOperation#getDependencyInList(List, String, String)}
 * does not accept a version as argument.
 */
private Dependency getDependencyInList(Model model, String groupId, String artifactId, String version) {
    List<Dependency> dependencyList = model.getDependencies();
    if (dependencyList == null || dependencyList.size() == 0) {
        return null;
    }

    Dependency dependency = null;
    for (Dependency d : dependencyList) {
        if (d.getArtifactId().equals(artifactId) && d.getGroupId().equals(groupId)
                && d.getVersion().equals(version)) {
            dependency = d;
            break;
        }
    }

    return dependency;
}
 
Example 4
Source Project: quarkus   Source File: GradleBuildFileFromConnector.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public List<Dependency> getDependencies() throws IOException {
    if (dependencies == null) {
        EclipseProject eclipseProject = null;
        if (getBuildContent() != null) {
            try {
                ProjectConnection connection = GradleConnector.newConnector()
                        .forProjectDirectory(getProjectDirPath().toFile())
                        .connect();
                eclipseProject = connection.getModel(EclipseProject.class);
            } catch (BuildException e) {
                // ignore this error.
                e.printStackTrace();
            }
        }
        if (eclipseProject != null) {
            dependencies = eclipseProject.getClasspath().stream().map(this::gradleModuleVersionToDependency)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
        } else {
            dependencies = Collections.emptyList();
        }
        dependencies = Collections.unmodifiableList(dependencies);
    }
    return dependencies;
}
 
Example 5
Source Project: pom-manipulation-ext   Source File: Project.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This method will scan the dependencies in the potentially active Profiles in this project and
 * return a fully resolved list.  Note that this will only return full dependencies not managed
 * i.e. those with a group, artifact and version.
 *
 * Note that while updating the {@link Dependency} reference returned will be reflected in the
 * Model as it is the same object, if you wish to remove or add items to the Model then you
 * must use {@link #getModel()}
 *
 * @param session MavenSessionHandler, used by {@link PropertyResolver}
 * @return a list of fully resolved {@link ArtifactRef} to the original {@link Dependency}
 * @throws ManipulationException if an error occurs
 */
public Map<Profile, Map<ArtifactRef, Dependency>> getResolvedProfileDependencies( MavenSessionHandler session) throws ManipulationException
{
    Map<Profile, Map<ArtifactRef, Dependency>> resolvedProfileDependencies = new HashMap<>();

    for ( final Profile profile : ProfileUtils.getProfiles( session, model ) )
    {
        Map<ArtifactRef, Dependency> profileDeps = new HashMap<>();

        resolveDeps( session, profile.getDependencies(), false, profileDeps );

        resolvedProfileDependencies.put( profile, profileDeps );
    }

    return resolvedProfileDependencies;
}
 
Example 6
Source Project: camel-spring-boot   Source File: BomGeneratorMojo.java    License: Apache License 2.0 6 votes vote down vote up
private void checkConflictsWithExternalBoms(Collection<Dependency> dependencies, Set<String> external) throws MojoFailureException {
    Set<String> errors = new TreeSet<>();
    for (Dependency d : dependencies) {
        String key = comparisonKey(d);
        if (external.contains(key)) {
            errors.add(key);
        }
    }

    if (errors.size() > 0) {
        StringBuilder msg = new StringBuilder();
        msg.append("Found ").append(errors.size()).append(" conflicts between the current managed dependencies and the external BOMS:\n");
        for (String error : errors) {
            msg.append(" - ").append(error).append("\n");
        }

        throw new MojoFailureException(msg.toString());
    }
}
 
Example 7
Source Project: versions-maven-plugin   Source File: UseReleasesMojo.java    License: Apache License 2.0 6 votes vote down vote up
private void noRangeMatching( ModifiedPomXMLEventReader pom, Dependency dep, String version, String releaseVersion,
                              ArtifactVersions versions )
    throws XMLStreamException
{
    if ( versions.containsVersion( releaseVersion ) )
    {
        if ( PomHelper.setDependencyVersion( pom, dep.getGroupId(), dep.getArtifactId(), version, releaseVersion,
                                             getProject().getModel() ) )
        {
            getLog().info( "Updated " + toString( dep ) + " to version " + releaseVersion );
        }
    }
    else if ( failIfNotReplaced )
    {
        throw new NoSuchElementException( "No matching release of " + toString( dep ) + " found for update." );
    }
}
 
Example 8
/**
 *
 * @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;
}
 
Example 9
Source Project: versions-maven-plugin   Source File: LockSnapshotsMojo.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Determine the timestamp version of the snapshot dependency used in the build.
 *
 * @param dep
 * @return The timestamp version if exists, otherwise the original snapshot dependency version is returned.
 */
private String resolveSnapshotVersion( Dependency dep )
{
    getLog().debug( "Resolving snapshot version for dependency: " + dep );

    String lockedVersion = dep.getVersion();

    try
    {
        Artifact depArtifact =
            artifactFactory.createDependencyArtifact( dep.getGroupId(), dep.getArtifactId(),
                                                      VersionRange.createFromVersionSpec( dep.getVersion() ),
                                                      dep.getType(), dep.getClassifier(), dep.getScope() );
        resolver.resolve( depArtifact, getProject().getRemoteArtifactRepositories(), localRepository );

        lockedVersion = depArtifact.getVersion();
    }
    catch ( Exception e )
    {
        getLog().error( e );
    }
    return lockedVersion;
}
 
Example 10
Source Project: quarkus   Source File: LocalWorkspaceDiscoveryTest.java    License: Apache License 2.0 5 votes vote down vote up
private static Dependency newDependency(String groupId, String artifactId, String version) {
    final Dependency dep = new Dependency();
    dep.setGroupId(groupId);
    dep.setArtifactId(artifactId);
    dep.setVersion(version);
    return dep;
}
 
Example 11
Source Project: netbeans   Source File: DependencyNode.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 12
Source Project: flatten-maven-plugin   Source File: FlattenMojo.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates the {@link List} of {@link Dependency dependencies} for the flattened POM. These are all resolved
 * {@link Dependency dependencies} except for those added from {@link Profile profiles}.
 *
 * @param effectiveModel is the effective POM {@link Model} to process.
 * @return the {@link List} of {@link Dependency dependencies}.
 * @throws MojoExecutionException if anything goes wrong.
 */
protected List<Dependency> createFlattenedDependencies( Model effectiveModel )
        throws MojoExecutionException {
    List<Dependency> flattenedDependencies = new ArrayList<Dependency>();
    // resolve all direct and inherited dependencies...
    try {
        createFlattenedDependencies( effectiveModel, flattenedDependencies );
    }
    catch (Exception e) {
        throw new MojoExecutionException("unable to create flattened dependencies", e);
    }
    if ( isEmbedBuildProfileDependencies() )
    {
        Model projectModel = this.project.getModel();
        Dependencies modelDependencies = new Dependencies();
        modelDependencies.addAll( projectModel.getDependencies() );
        for ( Profile profile : projectModel.getProfiles() )
        {
            // build-time driven activation (by property or file)?
            if ( isBuildTimeDriven( profile.getActivation() ) )
            {
                List<Dependency> profileDependencies = profile.getDependencies();
                for ( Dependency profileDependency : profileDependencies )
                {
                    if ( modelDependencies.contains( profileDependency ) )
                    {
                        // our assumption here is that the profileDependency has been added to model because of
                        // this build-time driven profile. Therefore we need to add it to the flattened POM.
                        // Non build-time driven profiles will remain in the flattened POM with their dependencies
                        // and
                        // allow dynamic dependencies due to OS or JDK.
                        flattenedDependencies.add( modelDependencies.resolve(profileDependency) );
                    }
                }
            }
        }
        getLog().debug( "Resolved " + flattenedDependencies.size() + " dependency/-ies for flattened POM." );
    }
    return flattenedDependencies;
}
 
Example 13
private static Dependency createDependency(String groupId, String artifactId, String version) {
    final Dependency dependency = new Dependency();
    dependency.setGroupId(groupId);
    dependency.setArtifactId(artifactId);
    dependency.setVersion(version);
    return dependency;
}
 
Example 14
Source Project: capsule-maven-plugin   Source File: Mojo.java    License: MIT License 5 votes vote down vote up
private Artifact toArtifact(final Dependency dependency) {
	if (dependency == null) return null;
	final Artifact artifact = toArtifact(resolve(dependency));
	artifact.setScope(dependency.getScope());
	if (artifact.getScope() == null || artifact.getScope().isEmpty()) artifact.setScope("compile");
	return artifact;
}
 
Example 15
@SuppressWarnings("unchecked")
public List<Dependency> getGeneratedDependencies() {
    if (configurations == null) {
        return Collections.emptyList();
    }
    return (List<Dependency>) pomDependenciesConverter.convert(getScopeMappings(), configurations);
}
 
Example 16
@Test
public void shouldLoadFromEnv() throws LifecycleExecutionException {
    EnvironmentSettingDependencyLoader loader = new EnvironmentSettingDependencyLoader() {
        @Override
        protected String getEnvSetting(String name) {
            return "org.foo:foo-artifact:1.0.0,org.bar:bar-artifact:1.5.0";
        }
    };

    List<Dependency> dependencyList = loader.load(properties, logger);
    TestHelper.verifyDependencies(dependencyList);
}
 
Example 17
@Test
public void shouldLoadFromEnvWithVersionResolving() throws LifecycleExecutionException {
    EnvironmentSettingDependencyLoader loader = new EnvironmentSettingDependencyLoader() {
        @Override
        protected String getEnvSetting(String name) {
            return "org.foo:foo-artifact:@[email protected],org.bar:bar-artifact:@[email protected]";
        }
    };

    properties.put("foo.version", "1.0.0");
    properties.put("bar.version", "1.5.0");

    List<Dependency> dependencyList = loader.load(properties, logger);
    TestHelper.verifyDependencies(dependencyList);
}
 
Example 18
Source Project: butterfly   Source File: PomAddDependencyTest.java    License: MIT License 5 votes vote down vote up
@Test
public void addDependencyWithVersionTest() throws IOException, XmlPullParserException {
    PomAddDependency uut = new PomAddDependency("org.springframework.batch", "spring-batch-core", "3.0.7.RELEASE").relative("pom.xml");

    Assert.assertNull(getDependencyBeforeChange(uut));
    executeAndAssertSuccess(uut);
    Dependency dependencyAfterChange = getDependencyAfterChange(uut);
    Assert.assertNotNull(dependencyAfterChange);
    Assert.assertEquals(dependencyAfterChange.getGroupId(), "org.springframework.batch");
    Assert.assertEquals(dependencyAfterChange.getArtifactId(), "spring-batch-core");
    Assert.assertEquals(dependencyAfterChange.getVersion(), "3.0.7.RELEASE");
    Assert.assertEquals(dependencyAfterChange.getScope(), null);

}
 
Example 19
Source Project: flatten-maven-plugin   Source File: Dependencies.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param dependency the {@link Dependency} to test.
 * @return <code>true</code> if the given {@link Dependency} is contained in these {@link Dependencies},
 *         <code>false</code> otherwise.
 */
public boolean contains( Dependency dependency )
{

    // ATTENTION: Dependency does not have a proper equals implementation, we only check that the key is
    // contained. However, this should be sufficient for all reasonable scenarios...
    return this.key2DependencyMap.containsKey( getKey( dependency ) );
}
 
Example 20
Source Project: multi-module-maven-release-plugin   Source File: PomUpdater.java    License: MIT License 5 votes vote down vote up
private void alterSingleDependency(List<String> errors, String searchingFrom, Properties projectProperties, Dependency dependency) {
    String version = dependency.getVersion();
    if (MavenVersionResolver.isSnapshot(MavenVersionResolver.resolveVersion(version, projectProperties))) {
        try {
            ReleasableModule dependencyBeingReleased = reactor.find(dependency.getGroupId(), dependency.getArtifactId(), version);
            dependency.setVersion(dependencyBeingReleased.getVersionToDependOn());
            log.debug(" Dependency on " + dependencyBeingReleased.getArtifactId() + " rewritten to version " + dependencyBeingReleased.getVersionToDependOn());
        } catch (UnresolvedSnapshotDependencyException e) {
            errors.add(searchingFrom + " references dependency " + e.artifactId + " " + e.version);
        }
    }
    else {
        log.debug(" Dependency on " + dependency.getArtifactId() + " kept at version " + dependency.getVersion());
    }
}
 
Example 21
Source Project: butterfly   Source File: PomAddManagedDependencyTest.java    License: MIT License 5 votes vote down vote up
@Test
public void noOpIfPresentTest() throws IOException, XmlPullParserException {
    PomAddManagedDependency uut = new PomAddManagedDependency("junit", "junit", "4.11").relative("pom.xml").noOpIfPresent();

    TOExecutionResult executionResult = uut.execution(transformedAppFolder, transformationContext);
    Assert.assertEquals(executionResult.getType(), TOExecutionResult.Type.NO_OP);
    Assert.assertNull(executionResult.getException());
    Dependency dependencyAfterChange = getManagedDependencyInList(getTransformedPomModel("pom.xml"), "junit", "junit", "4.11");
    Assert.assertNull(dependencyAfterChange);

    assertNotChangedFile("pom.xml");
}
 
Example 22
Source Project: sundrio   Source File: GenerateBomMojo.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns all dependencies defined in dependency management of the root pom.
 *
 * @return
 */
private Set<Artifact> getProjectDependencyManagement() {
    Set<Artifact> result = new LinkedHashSet<Artifact>();
    DependencyManagement dependencyManagement = getProject().getDependencyManagement();
    if (dependencyManagement != null) {
        for (Dependency dependency : dependencyManagement.getDependencies()) {
            result.add(toArtifact(dependency));
        }
    }
    return result;
}
 
Example 23
/**
 * utility method to return {@link Dependency} as G:V:A:C maven coordinates
 *
 * @param dependency - the maven {@link Dependency} whose coordinates need to be computed
 * @return - the {@link Dependency} info as G:V:A:C string
 */
private static String asCoordinates(Dependency dependency) {
    StringBuilder dependencyCoordinates = new StringBuilder().
        append(dependency.getGroupId())
        .append(":")
        .append(dependency.getArtifactId())
        .append(":")
        .append(dependency.getVersion());

    if (dependency.getClassifier() != null) {
        dependencyCoordinates.append(":").append(dependency.getClassifier());
    }

    return dependencyCoordinates.toString();
}
 
Example 24
Source Project: sundrio   Source File: GenerateBomMojo.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns all dependency artifacts in all modules, excluding all reactor artifacts (including attached).
 *
 * @return
 */
private Set<Artifact> getProjectDependencies() {
    Set<Artifact> result = new LinkedHashSet<Artifact>();
    for (MavenProject p : getSession().getProjectDependencyGraph().getSortedProjects()) {
        for (Dependency dependency : p.getDependencies()) {
            result.add(toArtifact(dependency));
        }
    }
    return result;
}
 
Example 25
Source Project: capsule-maven-plugin   Source File: Mojo.java    License: MIT License 5 votes vote down vote up
private Dependency toDependency(final Artifact artifact) {
	if (artifact == null) return null;
	final Dependency dependency = new Dependency();
	dependency.setGroupId(artifact.getGroupId());
	dependency.setArtifactId(artifact.getArtifactId());
	dependency.setVersion(artifact.getVersion());
	dependency.setScope(artifact.getScope());
	dependency.setClassifier(artifact.getClassifier());
	dependency.setOptional(artifact.isOptional());
	if (dependency.getScope() == null || dependency.getScope().isEmpty()) dependency.setScope("compile");
	return dependency;
}
 
Example 26
Source Project: butterfly   Source File: PomAddDependencyTest.java    License: MIT License 5 votes vote down vote up
@Test
public void addDependencyWithoutVersionTest() throws IOException, XmlPullParserException {
    PomAddDependency uut = new PomAddDependency("org.springframework.batch", "spring-batch-core").relative("pom.xml");

    Assert.assertNull(getDependencyBeforeChange(uut));
    executeAndAssertSuccess(uut);
    Dependency dependencyAfterChange = getDependencyAfterChange(uut);
    Assert.assertNotNull(dependencyAfterChange);
    Assert.assertEquals(dependencyAfterChange.getGroupId(), "org.springframework.batch");
    Assert.assertEquals(dependencyAfterChange.getArtifactId(), "spring-batch-core");
    Assert.assertEquals(dependencyAfterChange.getVersion(), null);
    Assert.assertEquals(dependencyAfterChange.getScope(), null);

}
 
Example 27
Source Project: sarl   Source File: MavenHelper.java    License: Apache License 2.0 5 votes vote down vote up
/** Convert an artifact to a dependency.
 *
 * @param artifact the artifact to convert.
 * @return the result of the conversion.
 */
@SuppressWarnings("static-method")
public Dependency toDependency(Artifact artifact) {
	final Dependency result = new Dependency();
	result.setArtifactId(artifact.getArtifactId());
	result.setClassifier(artifact.getClassifier());
	result.setGroupId(artifact.getGroupId());
	result.setOptional(artifact.isOptional());
	result.setScope(artifact.getScope());
	result.setType(artifact.getType());
	result.setVersion(artifact.getVersion());
	return result;
}
 
Example 28
private Set<ArtifactCoordinates> getSnapshotsFromManagement(Profile profile, PomPropertyResolver propertyResolver) {
  this.log.debug("\t\tChecking managed dependencies of profile '" + profile.getId() + "'");
  DependencyManagement dependencyManagement = profile.getDependencyManagement();
  if (dependencyManagement != null) {
    Collection<Dependency> snapshots = Collections2.filter(dependencyManagement.getDependencies(),
        new IsSnapshotDependency(propertyResolver));
    return Sets.newHashSet(Collections2.transform(snapshots, DependencyToCoordinates.INSTANCE));
  }
  return Collections.emptySet();
}
 
Example 29
Source Project: quarkus   Source File: MvnProjectBuilder.java    License: Apache License 2.0 5 votes vote down vote up
public MvnProjectBuilder addDependency(String artifactId) {
    final Dependency dep = new Dependency();
    dep.setGroupId(DEFAULT_GROUP_ID);
    dep.setArtifactId(artifactId);
    dep.setVersion(DEFAULT_VERSION);
    return addDependency(dep);
}
 
Example 30
Source Project: smart-testing   Source File: DependencyResolver.java    License: Apache License 2.0 5 votes vote down vote up
private Dependency smartTestingProviderDependency() {
    final Dependency smartTestingSurefireProvider = new Dependency();
    smartTestingSurefireProvider.setGroupId("org.arquillian.smart.testing");
    smartTestingSurefireProvider.setArtifactId("surefire-provider");
    smartTestingSurefireProvider.setVersion(ExtensionVersion.version().toString());
    smartTestingSurefireProvider.setScope("runtime");
    smartTestingSurefireProvider.setClassifier("shaded");
    return smartTestingSurefireProvider;
}