Java Code Examples for org.apache.maven.model.Dependency#setVersion()

The following examples show how to use org.apache.maven.model.Dependency#setVersion() . 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 File: PomChangePluginTest.java    From butterfly with MIT License 6 votes vote down vote up
@Test
public void changePluginDependencyTest() throws IOException, XmlPullParserException {
    final Dependency dependency = new Dependency();
    dependency.setGroupId("com.test.butterfly");
    dependency.setArtifactId("butterfly-transformation");
    dependency.setVersion("1.0.0-SNAPSHOT");
    List<Dependency> dependencyList = Arrays.asList(dependency);
    PomChangePlugin uut = new PomChangePlugin("org.maven.plugins", "maven-antrun-plugin").relative("pom.xml").setPluginDependencies(dependencyList);

    assertFalse(getPluginBeforeChange(uut).getDependencies().isEmpty());
    assertNotEquals(getPluginBeforeChange(uut).getDependencies().size(), dependencyList.size());

    executeAndAssertSuccess(uut);
    List<Dependency> dependenciesAfterPluginChange = getPluginAfterChange(uut).getDependencies();

    assertEquals(dependenciesAfterPluginChange.size(), dependencyList.size());
    assertEquals(dependenciesAfterPluginChange.get(0).getArtifactId(), dependency.getArtifactId());
    assertEquals(dependenciesAfterPluginChange.get(0).getGroupId(), dependency.getGroupId());
    assertEquals(dependenciesAfterPluginChange.get(0).getVersion(), dependency.getVersion());
}
 
Example 2
Source File: DependencyLoader.java    From yaks with Apache License 2.0 6 votes vote down vote up
/**
 * Construct dependency form coordinate string that follows the format "groupId:artifactId:version". Coordinates must
 * have a version set.
 * @param coordinates
 * @param properties
 * @param logger
 * @return
 */
default Dependency build(String coordinates, Properties properties, Logger logger) throws LifecycleExecutionException {
    Dependency dependency = new Dependency();
    Matcher matcher = COORDINATE_PATTERN.matcher(coordinates);
    if (!matcher.matches()) {
        throw new LifecycleExecutionException("Unsupported dependency coordinate. Must be of format groupId:artifactId:version");
    }

    String groupId = matcher.group("groupId");
    String artifactId = matcher.group("artifactId");
    String version = resolveVersionProperty(matcher.group("version"), properties);
    dependency.setGroupId(groupId);
    dependency.setArtifactId(artifactId);
    dependency.setVersion(version);

    logger.info(String.format("Add %s", dependency));
    return dependency;
}
 
Example 3
Source File: DefaultPomDependenciesConverter.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private Dependency createMavenDependency(ModuleDependency dependency, String name, String type, String scope, String classifier,
        Set<Configuration> configurations) {
    Dependency mavenDependency =  new Dependency();
    mavenDependency.setGroupId(dependency.getGroup());
    if (dependency instanceof ProjectDependency) {
        mavenDependency.setArtifactId(determineProjectDependencyArtifactId((ProjectDependency) dependency));
    } else {
        mavenDependency.setArtifactId(name);
    }
    mavenDependency.setVersion(dependency.getVersion());
    mavenDependency.setType(type);
    mavenDependency.setScope(scope);
    mavenDependency.setOptional(false);
    mavenDependency.setClassifier(classifier);
    mavenDependency.setExclusions(getExclusions(dependency, configurations));
    return mavenDependency;
}
 
Example 4
Source File: DetectExtension.java    From os-maven-plugin with Apache License 2.0 6 votes vote down vote up
private static void interpolate(Map<String, String> dict, Iterable<Dependency> dependencies) {
    if (dependencies == null) {
        return;
    }

    for (Dependency d: dependencies) {
        d.setGroupId(interpolate(dict, d.getGroupId()));
        d.setArtifactId(interpolate(dict, d.getArtifactId()));
        d.setVersion(interpolate(dict, d.getVersion()));
        d.setClassifier(interpolate(dict, d.getClassifier()));
        d.setSystemPath(interpolate(dict, d.getSystemPath()));
        for (Exclusion e: d.getExclusions()) {
            e.setGroupId(interpolate(dict, e.getGroupId()));
            e.setArtifactId(interpolate(dict, e.getArtifactId()));
        }
    }
}
 
Example 5
Source File: DefaultPomDependenciesConverter.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private Dependency createMavenDependency(ModuleDependency dependency, String name, String type, String scope, String classifier,
        Set<Configuration> configurations) {
    Dependency mavenDependency =  new Dependency();
    mavenDependency.setGroupId(dependency.getGroup());
    if (dependency instanceof ProjectDependency) {
        mavenDependency.setArtifactId(determineProjectDependencyArtifactId((ProjectDependency) dependency));
    } else {
        mavenDependency.setArtifactId(name);
    }
    mavenDependency.setVersion(dependency.getVersion());
    mavenDependency.setType(type);
    mavenDependency.setScope(scope);
    mavenDependency.setOptional(false);
    mavenDependency.setClassifier(classifier);
    mavenDependency.setExclusions(getExclusions(dependency, configurations));
    return mavenDependency;
}
 
Example 6
Source File: AddExtensionIT.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Test
void testAddExtensionWithMultipleExtension() throws MavenInvocationException, IOException {
    testDir = initProject(PROJECT_SOURCE_DIR, "projects/testAddExtensionWithMultipleExtension");
    invoker = initInvoker(testDir);
    addExtension(false, "quarkus-vertx, commons-io:commons-io:2.6");

    Model model = loadPom(testDir);
    Dependency expected1 = new Dependency();
    expected1.setGroupId(QUARKUS_GROUPID);
    expected1.setArtifactId(VERTX_ARTIFACT_ID);
    Dependency expected2 = new Dependency();
    expected2.setGroupId(COMMONS_IO);
    expected2.setArtifactId(COMMONS_IO);
    expected2.setVersion("2.6");
    assertThat(contains(model.getDependencies(), expected1)).isTrue();
    assertThat(contains(model.getDependencies(), expected2)).isTrue();
}
 
Example 7
Source File: PomUpdater.java    From multi-module-maven-release-plugin with 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 8
Source File: MavenHelper.java    From sarl with 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 9
Source File: LocalWorkspaceDiscoveryTest.java    From quarkus with 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 10
Source File: RunEpisodesBPlugin.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Validate the generation of a java files from purchaseorder.xsd.
 * 
 * @throws MojoExecutionException
 */
public void testExecute() throws Exception {

	final File pom = new File(getBaseDir(), "pom.xml");

	final MavenProject mavenProject = mavenProjectBuilder.build(pom,
			localRepository, null);

	mojo.setSchemaDirectory(new File(getBaseDir(), "src/main/resources/"));
	mojo.setSchemaIncludes(new String[] { "*.xsd" });
	mojo.setBindingIncludes(new String[] { "*.xjb" });
	mojo.setGenerateDirectory(new File(getBaseDir(),
			"target/generated-sources/xjc-test"));
	mojo.setVerbose(true);
	mojo.setRemoveOldOutput(true);

	mojo.setProject(mavenProject);
	mojo.setLocalRepository(localRepository);
	mojo.setExtension(true);
	mojo.setDebug(false);
	// mojo.setSchemaLanguage("XMLSCHEMA");
	mojo.roundtripTestClassName = getClass().getPackage().getName()
			+ ".RoundtripTest";
	mojo.setForceRegenerate(true);

	final Dependency episode = new Dependency();

	episode.setGroupId("org.jvnet.hyperjaxb3");
	episode.setArtifactId("hyperjaxb3-ejb-tests-episodes-a");
	episode.setVersion("0.5.5-SNAPSHOT");
	mojo.setEpisodes(new Dependency[] { episode });

	mojo.execute();
}
 
Example 11
Source File: QuarkusTestPlatformDescriptorLoader.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public static void addExtension(String groupId, String artifactId, String version, String name, String guide,
        List<Extension> extensions, List<Dependency> bomDeps) {
    extensions.add(new Extension(groupId, artifactId, version).setName(name).setGuide(guide));

    final Dependency d = new Dependency();
    d.setGroupId(groupId);
    d.setArtifactId(artifactId);
    d.setVersion(version);
    bomDeps.add(d);
}
 
Example 12
Source File: ResolverTest.java    From migration-tooling with Apache License 2.0 5 votes vote down vote up
private Dependency getDependency(String coordinates, String scope) {
  String[] coordinateArray = coordinates.split(":");
  Preconditions.checkState(coordinateArray.length == 3);
  Dependency dependency = new Dependency();
  dependency.setGroupId(coordinateArray[0]);
  dependency.setArtifactId(coordinateArray[1]);
  dependency.setVersion(coordinateArray[2]);
  dependency.setScope(scope);
  return dependency;
}
 
Example 13
Source File: MavenBuildFile.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
protected void addDependencyInBuildFile(AppArtifactCoords coords) throws IOException {
    if (getModel() != null) {
        final Dependency d = new Dependency();
        d.setGroupId(coords.getGroupId());
        d.setArtifactId(coords.getArtifactId());
        d.setVersion(coords.getVersion());
        // When classifier is empty, you get  <classifier></classifier> in the pom.xml
        if (coords.getClassifier() != null && !coords.getClassifier().isEmpty()) {
            d.setClassifier(coords.getClassifier());
        }
        d.setType(coords.getType());
        getModel().addDependency(d);
    }
}
 
Example 14
Source File: RangeResolver.java    From pom-manipulation-ext with Apache License 2.0 5 votes vote down vote up
private void handleVersionWithRange( Dependency d )
{
    try
    {
        VersionRange versionRange = VersionRange.createFromVersionSpec( d.getVersion() );

        // If its a range then try to use a matching version...
        if ( versionRange.hasRestrictions() )
        {
            final List<ArtifactVersion> versions = getVersions( new SimpleProjectRef( d.getGroupId(), d.getArtifactId() ) );
            final ArtifactVersion result = versionRange.matchVersion( versions );

            logger.debug( "Resolved range for dependency {} got versionRange {} and potential replacement of {} ", d, versionRange, result );

            if ( result != null )
            {
                d.setVersion( result.toString() );
            }
            else
            {
                logger.warn( "Unable to find replacement for range." );
            }
        }
    }
    catch ( InvalidVersionSpecificationException e )
    {
        throw new ManipulationUncheckedException( new ManipulationException( "Invalid range", e ) );
    }
}
 
Example 15
Source File: MavenUtil.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
public static Dependency newDependency(final String groupId, final String artifactId, final String version, final String classifier, final String type) {
  final Dependency dependency = new Dependency();
  dependency.setGroupId(groupId);
  dependency.setArtifactId(artifactId);
  dependency.setVersion(version);
  dependency.setClassifier(classifier);
  if (type != null)
    dependency.setType(type);

  return dependency;
}
 
Example 16
Source File: IsSnapshotDependencyTest.java    From unleash-maven-plugin with Eclipse Public License 1.0 5 votes vote down vote up
private static Dependency createDependencyAndInitPropertyResolver(String version, String resolverOutput) {
  Mockito.when(propertyResolver.expandPropertyReferences(version)).thenReturn(resolverOutput);

  Dependency d = new Dependency();
  d.setVersion(version);
  return d;
}
 
Example 17
Source File: BOMBuilderManipulator.java    From pom-manipulation-ext with Apache License 2.0 5 votes vote down vote up
private List<Dependency> getArtifacts( List<Project> projects )
{
    List<Dependency> results = new ArrayList<>(  );

    for ( Project p : projects )
    {
        Dependency d = new Dependency();
        d.setGroupId( p.getGroupId() );
        d.setArtifactId( p.getArtifactId() );
        d.setVersion( p.getVersion() );
        d.setType( p.getModel().getPackaging() );
        results.add( d );
    }
    return results;
}
 
Example 18
Source File: Pom.java    From buck with Apache License 2.0 4 votes vote down vote up
private static void updateDependency(Dependency dependency, Artifact providedMavenCoordinates) {
  dependency.setVersion(providedMavenCoordinates.getVersion());
  dependency.setClassifier(providedMavenCoordinates.getClassifier());
}
 
Example 19
Source File: PomReplaceDependency.java    From butterfly with MIT License 4 votes vote down vote up
@Override
protected TOExecutionResult pomExecution(String relativePomFile, Model model) {
    TOExecutionResult result = null;
    String details;

    Dependency oldDependency = getDependency(model, groupId, artifactId);
    if (oldDependency != null) {
        model.removeDependency(oldDependency);

        Dependency newDependency = new Dependency();
        newDependency.setGroupId(newGroupId);
        newDependency.setArtifactId(newArtifactId);
        if (newVersion != null) {
            newDependency.setVersion(newVersion);
        }
        if (newScope != null) {
            newDependency.setScope(newScope);
        } else {
            newDependency.setScope(oldDependency.getScope());
        }
        model.addDependency(newDependency);

        details = String.format("Dependency %s:%s has been replaced by %s:%s in POM file %s", groupId, artifactId, newGroupId, newArtifactId, relativePomFile);
        result = TOExecutionResult.success(this, details);
    } else {
        details = String.format("Dependency %s:%s has not been replaced by %s:%s in POM file %s because it is not present", groupId, artifactId, newGroupId, newArtifactId, relativePomFile);
        switch (ifNotPresent) {
            case Warn:
                result = TOExecutionResult.warning(this, new TransformationOperationException(details));
                break;
            case NoOp:
                result = TOExecutionResult.noOp(this, details);
                break;
            case Fail:
                // Fail is the default
            default:
                result = TOExecutionResult.error(this, new TransformationOperationException(details));
                break;
        }
    }

    return result;
}
 
Example 20
Source File: PomUtil.java    From unleash-maven-plugin with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Changes the reactor dependency version of the POM as well as directly in the XML document preserving the whole
 * document formatting.
 *
 * @param dependency the reactor dependency where to adapt the project version.
 * @param document the POM as an XML document in which the project version shall be adapted.
 * @param dependenciesPath the XPath to the {@code dependencies} starting from {@code /project/}.
 *          e.g. {@code /profiles/profile[id[text()='release']]/dependencyManagement}.
 * @param newVersion the new dependency version to set.
 */
public static void setDependencyVersion(Dependency dependency, Document document, String dependenciesPath,
    String newVersion) {
  Preconditions.checkArgument(hasChildNode(document, NODE_NAME_PROJECT),
      "The document doesn't seem to be a POM model, project element is missing.");

  // first step: update dependency version of the in-memory model
  dependency.setVersion(newVersion);

  // second step: update the dependency version in the DOM document that is then serialized for later building
  NodeList dependencyNodes;
  try {
    List<String> xPathParts = new ArrayList<>();
    xPathParts.add(NODE_NAME_PROJECT);
    if (dependenciesPath.startsWith("/")) {
      dependenciesPath = dependenciesPath.substring("/".length());
    }
    if (!dependenciesPath.isEmpty()) {
      xPathParts.add(dependenciesPath);
    }
    xPathParts.add(NODE_NAME_DEPENDENCIES);
    xPathParts.add(NODE_NAME_DEPENDENCY + "[groupId[text()='" + dependency.getGroupId() + "']"
        + " and artifactId[text()='" + dependency.getArtifactId() + "']]");
    String expression = "/" + Joiner.on("/").skipNulls().join(xPathParts);

    XPath xPath = XPathFactory.newInstance().newXPath();
    dependencyNodes = (NodeList) xPath.evaluate(expression, document.getDocumentElement(), XPathConstants.NODESET);

  } catch (XPathExpressionException e) {
    String message = "Cannot evaluate xPath against '" + dependenciesPath + "'.";
    throw new RuntimeException(message, e);
  }

  for (int i = 0; i < dependencyNodes.getLength(); i++) {
    Node dependencyNode = dependencyNodes.item(i);
    NodeList childNodes = dependencyNode.getChildNodes();
    for (int j = 0; j < childNodes.getLength(); j++) {
      Node childNode = childNodes.item(j);
      if (Objects.equal(childNode.getNodeName(), PomUtil.NODE_NAME_VERSION)) {
        childNode.setTextContent(newVersion);
      }
    }
  }
}