List of usage examples for org.apache.maven.artifact.versioning VersionRange createFromVersionSpec
public static VersionRange createFromVersionSpec(String spec) throws InvalidVersionSpecificationException
Create a version range from a string representation
Some spec examples are:1.0
Version 1.0[1.0,2.0)
Versions 1.0 (included) to 2.0 (not included)[1.0,2.0]
Versions 1.0 to 2.0 (both included)[1.5,)
Versions 1.5 and higher(,1.0],[1.2,)
Versions up to 1.0 (included) and 1.2 or higherFrom source file:org.codehaus.mojo.versions.api.PropertyVersions.java
License:Apache License
public ArtifactVersion getNewestVersion(String currentVersion, Property property, Boolean allowSnapshots, List reactorProjects, VersionsHelper helper) throws MojoExecutionException { final boolean includeSnapshots = !property.isBanSnapshots() && Boolean.TRUE.equals(allowSnapshots); helper.getLog().debug("Property ${" + property.getName() + "}: Set of valid available versions is " + Arrays.asList(getVersions(includeSnapshots))); VersionRange range;// www .j a va 2s .co m try { if (property.getVersion() != null) { range = VersionRange.createFromVersionSpec(property.getVersion()); helper.getLog().debug("Property ${" + property.getName() + "}: Restricting results to " + range); } else { range = null; helper.getLog().debug("Property ${" + property.getName() + "}: Restricting results to " + range); } } catch (InvalidVersionSpecificationException e) { throw new MojoExecutionException(e.getMessage(), e); } ArtifactVersion result = getNewestVersion(range, helper.createArtifactVersion(currentVersion), null, includeSnapshots, false, true); helper.getLog().debug("Property ${" + property.getName() + "}: Current winner is: " + result); if (property.isSearchReactor()) { helper.getLog() .debug("Property ${" + property.getName() + "}: Searching reactor for a valid version..."); Collection reactorArtifacts = helper.extractArtifacts(reactorProjects); ArtifactVersion[] reactorVersions = getVersions(reactorArtifacts); helper.getLog().debug("Property ${" + property.getName() + "}: Set of valid available versions from the reactor is " + Arrays.asList(reactorVersions)); ArtifactVersion fromReactor = null; if (reactorVersions.length > 0) { for (int j = reactorVersions.length - 1; j >= 0; j--) { if (range == null || ArtifactVersions.isVersionInRange(reactorVersions[j], range)) { fromReactor = reactorVersions[j]; helper.getLog().debug( "Property ${" + property.getName() + "}: Reactor has version " + fromReactor); break; } } } if (fromReactor != null && (result != null || !currentVersion.equals(fromReactor.toString()))) { if (property.isPreferReactor()) { helper.getLog().debug("Property ${" + property.getName() + "}: Reactor has a version and we prefer the reactor"); result = fromReactor; } else { if (result == null) { helper.getLog() .debug("Property ${" + property.getName() + "}: Reactor has the only version"); result = fromReactor; } else if (getVersionComparator().compare(result, fromReactor) < 0) { helper.getLog() .debug("Property ${" + property.getName() + "}: Reactor has a newer version"); result = fromReactor; } else { helper.getLog().debug( "Property ${" + property.getName() + "}: Reactor has the same or older version"); } } } } return result; }
From source file:org.codehaus.mojo.versions.DisplayParentUpdateMojo.java
License:Apache License
protected void update(ModifiedPomXMLEventReader pom) throws MojoExecutionException, MojoFailureException, XMLStreamException { if (hasParentPom() && !isPartOfReactorProject()) { String currentVersion = getProject().getParent().getVersion(); String version = currentVersion; if (parentVersion != null) { version = parentVersion;/*from w w w. j a v a2 s .c om*/ } VersionRange versionRange; try { versionRange = VersionRange.createFromVersionSpec(version); } catch (InvalidVersionSpecificationException e) { throw new MojoExecutionException("Invalid version range specification: " + version, e); } Artifact artifact = artifactFactory.createDependencyArtifact(getProject().getParent().getGroupId(), getProject().getParent().getArtifactId(), versionRange, "pom", null, null); ArtifactVersion latestVersion; try { latestVersion = findLatestVersion(artifact, versionRange, null, false); } catch (ArtifactMetadataRetrievalException e) { throw new MojoExecutionException(e.getMessage(), e); } final Artifact parentArtifact = getProject().getParentArtifact(); final Dependency dependency = new Dependency(); dependency.setGroupId(parentArtifact.getGroupId()); dependency.setArtifactId(parentArtifact.getArtifactId()); dependency.setVersion(currentVersion); final ArtifactUpdate update = new ArtifactUpdate(); update.setDependency(dependency); update.setVersionUpdate(null == latestVersion ? null : latestVersion.toString()); DisplayParentUpdateReport report = new DisplayParentUpdateReport(); report.setUpdate(update); ObjectToXmlWriter.writeXmlReport(xmlReport, report); } }
From source file:org.codehaus.mojo.versions.DisplayPluginUpdatesMojo.java
License:Apache License
/** * @throws MojoExecutionException when things go wrong * @throws MojoFailureException when things go wrong in a very bad way * @see AbstractVersionsUpdaterMojo#execute() * @since 1.0-alpha-1//from w ww. j a va 2s . com */ public void execute() throws MojoExecutionException, MojoFailureException { logInit(); Set<String> pluginsWithVersionsSpecified; try { pluginsWithVersionsSpecified = findPluginsWithVersionsSpecified(getProject()); } catch (XMLStreamException e) { throw new MojoExecutionException(e.getMessage(), e); } catch (IOException e) { throw new MojoExecutionException(e.getMessage(), e); } Map<String, String> superPomPluginManagement = getSuperPomPluginManagement(); getLog().debug("superPom plugins = " + superPomPluginManagement); Map<String, String> parentPluginManagement = new HashMap<String, String>(); Map<String, String> parentBuildPlugins = new HashMap<String, String>(); Map<String, String> parentReportPlugins = new HashMap<String, String>(); List<MavenProject> parents = getParentProjects(getProject()); for (MavenProject parentProject : parents) { getLog().debug("Processing parent: " + parentProject.getGroupId() + ":" + parentProject.getArtifactId() + ":" + parentProject.getVersion() + " -> " + parentProject.getFile()); StringWriter writer = new StringWriter(); boolean havePom = false; Model interpolatedModel; try { Model originalModel = parentProject.getOriginalModel(); if (originalModel == null) { getLog().warn("project.getOriginalModel()==null for " + parentProject.getGroupId() + ":" + parentProject.getArtifactId() + ":" + parentProject.getVersion() + " is null, substituting project.getModel()"); originalModel = parentProject.getModel(); } try { new MavenXpp3Writer().write(writer, originalModel); writer.close(); havePom = true; } catch (IOException e) { // ignore } interpolatedModel = modelInterpolator.interpolate(originalModel, null, new DefaultProjectBuilderConfiguration() .setExecutionProperties(getProject().getProperties()), false); } catch (ModelInterpolationException e) { throw new MojoExecutionException(e.getMessage(), e); } if (havePom) { try { Set<String> withVersionSpecified = findPluginsWithVersionsSpecified( new StringBuilder(writer.toString())); Map<String, String> map = getPluginManagement(interpolatedModel); map.keySet().retainAll(withVersionSpecified); parentPluginManagement.putAll(map); map = getBuildPlugins(interpolatedModel, true); map.keySet().retainAll(withVersionSpecified); parentPluginManagement.putAll(map); map = getReportPlugins(interpolatedModel, true); map.keySet().retainAll(withVersionSpecified); parentPluginManagement.putAll(map); } catch (IOException e) { throw new MojoExecutionException(e.getMessage(), e); } catch (XMLStreamException e) { throw new MojoExecutionException(e.getMessage(), e); } } else { parentPluginManagement.putAll(getPluginManagement(interpolatedModel)); parentPluginManagement.putAll(getBuildPlugins(interpolatedModel, true)); parentPluginManagement.putAll(getReportPlugins(interpolatedModel, true)); } } Set<Plugin> plugins = getProjectPlugins(superPomPluginManagement, parentPluginManagement, parentBuildPlugins, parentReportPlugins, pluginsWithVersionsSpecified); List<String> updates = new ArrayList<String>(); List<String> lockdowns = new ArrayList<String>(); Map<ArtifactVersion, Map<String, String>> upgrades = new TreeMap<ArtifactVersion, Map<String, String>>( new MavenVersionComparator()); ArtifactVersion curMavenVersion = runtimeInformation.getApplicationVersion(); ArtifactVersion specMavenVersion = new DefaultArtifactVersion(getRequiredMavenVersion(getProject(), "2.0")); ArtifactVersion minMavenVersion = null; boolean superPomDrivingMinVersion = false; Iterator<Plugin> i = plugins.iterator(); while (i.hasNext()) { Object plugin = i.next(); String groupId = getPluginGroupId(plugin); String artifactId = getPluginArtifactId(plugin); String version = getPluginVersion(plugin); String coords = ArtifactUtils.versionlessKey(groupId, artifactId); if (version == null) { version = parentPluginManagement.get(coords); } getLog().debug(new StringBuilder().append("Checking ").append(coords).append(" for updates newer than ") .append(version).toString()); String effectiveVersion = version; VersionRange versionRange; boolean unspecified = version == null; try { versionRange = unspecified ? VersionRange.createFromVersionSpec("[0,)") : VersionRange.createFromVersionSpec(version); } catch (InvalidVersionSpecificationException e) { throw new MojoExecutionException("Invalid version range specification: " + version, e); } Artifact artifact = artifactFactory.createPluginArtifact(groupId, artifactId, versionRange); ArtifactVersion artifactVersion = null; try { // now we want to find the newest version that is compatible with the invoking version of Maven ArtifactVersions artifactVersions = getHelper().lookupArtifactVersions(artifact, true); ArtifactVersion[] newerVersions = artifactVersions .getVersions(Boolean.TRUE.equals(this.allowSnapshots)); ArtifactVersion minRequires = null; for (int j = newerVersions.length - 1; j >= 0; j--) { Artifact probe = artifactFactory.createDependencyArtifact(groupId, artifactId, VersionRange.createFromVersion(newerVersions[j].toString()), "pom", null, "runtime"); try { getHelper().resolveArtifact(probe, true); MavenProject mavenProject = projectBuilder.buildFromRepository(probe, remotePluginRepositories, localRepository); ArtifactVersion requires = new DefaultArtifactVersion( getRequiredMavenVersion(mavenProject, "2.0")); if (specMavenVersion.compareTo(requires) >= 0 && artifactVersion == null) { artifactVersion = newerVersions[j]; } if (effectiveVersion == null && curMavenVersion.compareTo(requires) >= 0) { // version was unspecified, current version of maven thinks it should use this effectiveVersion = newerVersions[j].toString(); } if (artifactVersion != null && effectiveVersion != null) { // no need to look at any older versions. break; } if (minRequires == null || minRequires.compareTo(requires) > 0) { Map<String, String> upgradePlugins = upgrades.get(requires); if (upgradePlugins == null) { upgrades.put(requires, upgradePlugins = new LinkedHashMap<String, String>()); } String upgradePluginKey = compactKey(groupId, artifactId); if (!upgradePlugins.containsKey(upgradePluginKey)) { upgradePlugins.put(upgradePluginKey, newerVersions[j].toString()); } minRequires = requires; } } catch (ArtifactResolutionException e) { // ignore bad version } catch (ArtifactNotFoundException e) { // ignore bad version } catch (ProjectBuildingException e) { // ignore bad version } } if (effectiveVersion != null) { VersionRange currentVersionRange = VersionRange.createFromVersion(effectiveVersion); Artifact probe = artifactFactory.createDependencyArtifact(groupId, artifactId, currentVersionRange, "pom", null, "runtime"); try { getHelper().resolveArtifact(probe, true); MavenProject mavenProject = projectBuilder.buildFromRepository(probe, remotePluginRepositories, localRepository); ArtifactVersion requires = new DefaultArtifactVersion( getRequiredMavenVersion(mavenProject, "2.0")); if (minMavenVersion == null || minMavenVersion.compareTo(requires) < 0) { minMavenVersion = requires; } } catch (ArtifactResolutionException e) { // ignore bad version } catch (ArtifactNotFoundException e) { // ignore bad version } catch (ProjectBuildingException e) { // ignore bad version } } } catch (ArtifactMetadataRetrievalException e) { throw new MojoExecutionException(e.getMessage(), e); } String newVersion; if (version == null && pluginsWithVersionsSpecified.contains(coords)) { // Hack ALERT! // // All this should be re-written in a less "pom is xml" way... but it'll // work for now :-( // // we have removed the version information, as it was the same as from // the super-pom... but it actually was specified. version = artifactVersion != null ? artifactVersion.toString() : null; } getLog().debug("[" + coords + "].version=" + version); getLog().debug("[" + coords + "].artifactVersion=" + artifactVersion); getLog().debug("[" + coords + "].effectiveVersion=" + effectiveVersion); getLog().debug("[" + coords + "].specified=" + pluginsWithVersionsSpecified.contains(coords)); if (version == null || !pluginsWithVersionsSpecified.contains(coords)) { version = (String) superPomPluginManagement.get(ArtifactUtils.versionlessKey(artifact)); getLog().debug("[" + coords + "].superPom.version=" + version); newVersion = artifactVersion != null ? artifactVersion.toString() : (version != null ? version : (effectiveVersion != null ? effectiveVersion : "(unknown)")); StringBuilder buf = new StringBuilder(compactKey(groupId, artifactId)); buf.append(' '); int padding = WARN_PAD_SIZE - newVersion.length() - (version != null ? FROM_SUPER_POM.length() : 0); while (buf.length() < padding) { buf.append('.'); } buf.append(' '); if (version != null) { buf.append(FROM_SUPER_POM); superPomDrivingMinVersion = true; } buf.append(newVersion); lockdowns.add(buf.toString()); } else if (artifactVersion != null) { newVersion = artifactVersion.toString(); } else { newVersion = null; } if (version != null && artifactVersion != null && newVersion != null && effectiveVersion != null && new DefaultArtifactVersion(effectiveVersion) .compareTo(new DefaultArtifactVersion(newVersion)) < 0) { StringBuilder buf = new StringBuilder(compactKey(groupId, artifactId)); buf.append(' '); int padding = INFO_PAD_SIZE - version.length() - newVersion.length() - 4; while (buf.length() < padding) { buf.append('.'); } buf.append(' '); buf.append(effectiveVersion); buf.append(" -> "); buf.append(newVersion); updates.add(buf.toString()); } } logLine(false, ""); if (updates.isEmpty()) { logLine(false, "All plugins with a version specified are using the latest versions."); } else { logLine(false, "The following plugin updates are available:"); for (String update : updates) { logLine(false, " " + update); } } logLine(false, ""); if (lockdowns.isEmpty()) { logLine(false, "All plugins have a version specified."); } else { getLog().warn("The following plugins do not have their version specified:"); for (String lockdown : lockdowns) { getLog().warn(" " + lockdown); } } logLine(false, ""); boolean noMavenMinVersion = getRequiredMavenVersion(getProject(), null) == null; boolean noExplicitMavenMinVersion = getProject().getPrerequisites() == null || getProject().getPrerequisites().getMaven() == null; if (noMavenMinVersion) { getLog().warn("Project does not define minimum Maven version, default is: 2.0"); } else if (noExplicitMavenMinVersion) { logLine(false, "Project inherits minimum Maven version as: " + specMavenVersion); } else { ArtifactVersion explicitMavenVersion = new DefaultArtifactVersion( getProject().getPrerequisites().getMaven()); if (explicitMavenVersion.compareTo(specMavenVersion) < 0) { logLine(true, "Project's effective minimum Maven (from parent) is: " + specMavenVersion); logLine(true, "Project defines minimum Maven version as: " + explicitMavenVersion); } else { logLine(false, "Project defines minimum Maven version as: " + specMavenVersion); } } logLine(false, "Plugins require minimum Maven version of: " + minMavenVersion); if (superPomDrivingMinVersion) { logLine(false, "Note: the super-pom from Maven " + curMavenVersion + " defines some of the plugin"); logLine(false, " versions and may be influencing the plugins required minimum Maven"); logLine(false, " version."); } logLine(false, ""); if ("maven-plugin".equals(getProject().getPackaging())) { if (noMavenMinVersion) { getLog().warn( "Project (which is a Maven Plugin) does not define required minimum version of Maven."); getLog().warn("Update the pom.xml to contain"); getLog().warn(" <prerequisites>"); getLog().warn(" <maven><!-- minimum version of Maven that the plugin works with --></maven>"); getLog().warn(" </prerequisites>"); getLog().warn("To build this plugin you need at least Maven " + minMavenVersion); getLog().warn( "A Maven Enforcer rule can be used to enforce this if you have not already set one up"); } else if (minMavenVersion != null && specMavenVersion.compareTo(minMavenVersion) < 0) { getLog().warn("Project (which is a Maven Plugin) targets Maven " + specMavenVersion + " or newer"); getLog().warn("but requires Maven " + minMavenVersion + " or newer to build."); getLog().warn("This may or may not be a problem. A Maven Enforcer rule can help "); getLog().warn("enforce that the correct version of Maven is used to build this plugin."); } else { logLine(false, "No plugins require a newer version of Maven than specified by the pom."); } } else { if (noMavenMinVersion) { logLine(true, "Project does not define required minimum version of Maven."); logLine(true, "Update the pom.xml to contain"); logLine(true, " <prerequisites>"); logLine(true, " <maven>" + minMavenVersion + "</maven>"); logLine(true, " </prerequisites>"); } else if (minMavenVersion != null && specMavenVersion.compareTo(minMavenVersion) < 0) { logLine(true, "Project requires an incorrect minimum version of Maven."); logLine(true, "Either change plugin versions to those compatible with " + specMavenVersion); logLine(true, "or update the pom.xml to contain"); logLine(true, " <prerequisites>"); logLine(true, " <maven>" + minMavenVersion + "</maven>"); logLine(true, " </prerequisites>"); } else { logLine(false, "No plugins require a newer version of Maven than specified by the pom."); } } for (Map.Entry<ArtifactVersion, Map<String, String>> mavenUpgrade : upgrades.entrySet()) { ArtifactVersion mavenUpgradeVersion = (ArtifactVersion) mavenUpgrade.getKey(); Map<String, String> upgradePlugins = mavenUpgrade.getValue(); if (upgradePlugins.isEmpty() || specMavenVersion.compareTo(mavenUpgradeVersion) >= 0) { continue; } logLine(false, ""); logLine(false, "Require Maven " + mavenUpgradeVersion + " to use the following plugin updates:"); for (Map.Entry<String, String> entry : upgradePlugins.entrySet()) { StringBuilder buf = new StringBuilder(" "); buf.append(entry.getKey()); buf.append(' '); String s = entry.getValue(); int padding = INFO_PAD_SIZE - s.length() + 2; while (buf.length() < padding) { buf.append('.'); } buf.append(' '); buf.append(s); logLine(false, buf.toString()); } } logLine(false, ""); }
From source file:org.codehaus.mojo.versions.RewitePomToLatestVersionsMojo.java
License:Apache License
private void useLatestVersionsFromPlugins(ModifiedPomXMLEventReader pom, Collection<?> plugins) throws XMLStreamException, MojoExecutionException, ArtifactMetadataRetrievalException { int segment = determineUnchangedSegment(allowMajorUpdates, allowMinorUpdates, allowIncrementalUpdates); Iterator<?> i = plugins.iterator(); while (i.hasNext()) { Plugin plugin = (Plugin) i.next(); if ((plugin.getGroupId() != null) && (plugin.getArtifactId()) != null && (plugin.getVersion() != null)) { Artifact pluginArtifact = null; try { pluginArtifact = new DefaultArtifact(plugin.getGroupId(), plugin.getArtifactId(), VersionRange.createFromVersionSpec(plugin.getVersion()), "", "", "", null); } catch (InvalidVersionSpecificationException e) { pluginArtifact = null;/*from w ww . j av a 2s . c om*/ } if (pluginArtifact != null) { getLog().info("Try to update pluginArtifact " + pluginArtifact); useLatestVersionsForArtifact(pom, pluginArtifact, segment, UpdateType.UpdatePlugin); } } List<Dependency> dependencies = plugin.getDependencies(); if (dependencies != null) { Iterator<Dependency> j = dependencies.iterator(); while (j.hasNext()) { Dependency dep = (Dependency) j.next(); if (isExcludeReactor() && isProducedByReactor(dep)) { getLog().debug("Ignoring reactor dependency: " + toString(dep)); continue; } Artifact artifact = this.toArtifact(dep); useLatestVersionsForArtifact(pom, artifact, segment, UpdateType.UpdateDependency); } } } }
From source file:org.codehaus.mojo.versions.UpdateParentMojo.java
License:Apache License
/** * @param pom the pom to update./*from w w w . j a v a2 s . c o m*/ * @throws MojoExecutionException when things go wrong * @throws MojoFailureException when things go wrong in a very bad way * @throws XMLStreamException when things go wrong with XML streaming * @see AbstractVersionsUpdaterMojo#update(ModifiedPomXMLEventReader) * @since 1.0-alpha-1 */ protected void update(ModifiedPomXMLEventReader pom) throws MojoExecutionException, MojoFailureException, XMLStreamException { if (getProject().getParent() == null) { getLog().info("Project does not have a parent"); return; } if (reactorProjects.contains(getProject().getParent())) { getLog().info("Project's parent is part of the reactor"); return; } String currentVersion = getProject().getParent().getVersion(); String version = currentVersion; if (parentVersion != null) { version = parentVersion; } VersionRange versionRange; try { versionRange = VersionRange.createFromVersionSpec(version); } catch (InvalidVersionSpecificationException e) { throw new MojoExecutionException("Invalid version range specification: " + version, e); } Artifact artifact = artifactFactory.createDependencyArtifact(getProject().getParent().getGroupId(), getProject().getParent().getArtifactId(), versionRange, "pom", null, null); ArtifactVersion artifactVersion; try { artifactVersion = findLatestVersion(artifact, versionRange, null, false); } catch (ArtifactMetadataRetrievalException e) { throw new MojoExecutionException(e.getMessage(), e); } if (!shouldApplyUpdate(artifact, currentVersion, artifactVersion)) { return; } getLog().info("Updating parent from " + currentVersion + " to " + artifactVersion.toString()); if (PomHelper.setProjectParentVersion(pom, artifactVersion.toString())) { getLog().debug("Made an update from " + currentVersion + " to " + artifactVersion.toString()); } }
From source file:org.eclipse.m2e.core.internal.embedder.AbstractWorkspaceRuntime.java
License:Open Source License
protected IMavenProjectFacade getMavenDistribution() { try {/* ww w .ja v a 2s.c o m*/ VersionRange range = VersionRange.createFromVersionSpec(getDistributionArtifactKey().getVersion()); for (IMavenProjectFacade facade : projectManager.getProjects()) { ArtifactKey artifactKey = facade.getArtifactKey(); if (getDistributionArtifactKey().getGroupId().equals(artifactKey.getGroupId()) // && getDistributionArtifactKey().getArtifactId().equals(artifactKey.getArtifactId())// && range.containsVersion(new DefaultArtifactVersion(artifactKey.getVersion()))) { return facade; } } } catch (InvalidVersionSpecificationException e) { // can't happen } return null; }
From source file:org.eclipse.m2e.core.internal.embedder.MavenWorkspaceRuntime.java
License:Open Source License
private IMavenProjectFacade getMavenDistribution() { try {/*from www .j a va2 s.c o m*/ VersionRange range = VersionRange.createFromVersionSpec(MAVEN_DISTRIBUTION.getVersion()); for (IMavenProjectFacade facade : projectManager.getProjects()) { ArtifactKey artifactKey = facade.getArtifactKey(); if (MAVEN_DISTRIBUTION.getGroupId().equals(artifactKey.getGroupId()) // && MAVEN_DISTRIBUTION.getArtifactId().equals(artifactKey.getArtifactId())// && range.containsVersion(new DefaultArtifactVersion(artifactKey.getVersion()))) { return facade; } } } catch (InvalidVersionSpecificationException e) { // can't happen } return null; }
From source file:org.eclipse.m2e.core.internal.project.registry.MavenRequiredCapability.java
License:Open Source License
public boolean isPotentialMatch(Capability capability) { if (capability instanceof MavenCapability && getVersionlessKey().equals(capability.getVersionlessKey())) { try {/* ww w .j av a 2 s. co m*/ // TODO may need to cache parsed version and versionRange for performance reasons ArtifactVersion version = new DefaultArtifactVersion(((MavenCapability) capability).getVersion()); VersionRange range = VersionRange.createFromVersionSpec(versionRange); return range.containsVersion(version); } catch (InvalidVersionSpecificationException ex) { return true; // better safe than sorry } } return false; }
From source file:org.eclipse.m2e.core.ui.internal.editing.LifecycleMappingOperation.java
License:Open Source License
public void process(Document document) { Element root = document.getDocumentElement(); Element pluginExecutions; // add the new plugins here //now find the lifecycle stuff if it's there. if (createAtTopLevel) { if (root == null) { // probably an empty document root = document.createElement("lifecycleMappingMetadata"); //$NON-NLS-1$ document.appendChild(root);/*from w ww. j a v a2s .c o m*/ } pluginExecutions = getChild(root, "pluginExecutions"); //$NON-NLS-1$ } else { Element managedPlugins = getChild(root, BUILD, PLUGIN_MANAGEMENT, PLUGINS); Element lifecyclePlugin = findChild(managedPlugins, PLUGIN, childEquals(GROUP_ID, LIFECYCLE_PLUGIN_GROUPID), childEquals(ARTIFACT_ID, LIFECYCLE_PLUGIN_ARTIFACTID)); if (lifecyclePlugin == null) { //not found, create lifecyclePlugin = PomHelper.createPlugin(managedPlugins, LIFECYCLE_PLUGIN_GROUPID, LIFECYCLE_PLUGIN_ARTIFACTID, LIFECYCLE_PLUGIN_VERSION); //mkleint: a bit scared to have this text localized, with chinese/japanese locales, it could write garbage into the pom file.. Comment comment = document.createComment( "This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself."); //$NON-NLS-1$ managedPlugins.insertBefore(comment, lifecyclePlugin); format(comment); } pluginExecutions = getChild(lifecyclePlugin, CONFIGURATION, "lifecycleMappingMetadata", //$NON-NLS-1$ "pluginExecutions"); //$NON-NLS-1$ } //now find the plugin execution for the plugin we have.. Element execution = null; for (Element exec : findChilds(pluginExecutions, "pluginExecution")) { //$NON-NLS-1$ Element filter = findChild(exec, "pluginExecutionFilter", //$NON-NLS-1$ childEquals(GROUP_ID, groupId), childEquals(ARTIFACT_ID, artifactId)); //the action needs to match the action we want.. Element actionEl = findChild(findChild(exec, "action"), action.toString()); //$NON-NLS-1$ if (filter != null && actionEl != null) { String versionRange = getTextValue(getChild(filter, "versionRange")); //$NON-NLS-1$ if (versionRange != null) { // paranoid null check //now we shall do some smart matching on the existing versionRange and our version.. //so far the "smart" thing involves just overwriting the range. try { VersionRange range = VersionRange.createFromVersionSpec(versionRange); if (!range.containsVersion(new DefaultArtifactVersion(version))) { Element rangeEl = findChild(filter, "versionRange"); //$NON-NLS-1$ setText(rangeEl, "[" + version + ",)"); //$NON-NLS-1$ //$NON-NLS-2$ } } catch (InvalidVersionSpecificationException e) { log.error("Failed to parse version range:" + versionRange, e); //$NON-NLS-1$ } } execution = exec; break; } } if (execution == null) { execution = createPluginExecution(document, pluginExecutions); } //now enter/update the goal(s).. Element goalsEl = getChild(execution, "pluginExecutionFilter", GOALS); //$NON-NLS-1$ List<String> toAddGoals = new ArrayList<String>(Arrays.asList(goals)); for (Element existingGoal : findChilds(goalsEl, GOAL)) { String glValue = getTextValue(existingGoal); if (glValue != null && toAddGoals.contains(glValue)) { toAddGoals.remove(glValue); } } if (toAddGoals.size() > 0) { for (String goal : toAddGoals) { format(createElementWithText(goalsEl, GOAL, goal)); } } }
From source file:org.eclipse.m2e.editor.xml.internal.lifecycle.LifecycleMappingOperation.java
License:Open Source License
public void process(Document document) { Element root = document.getDocumentElement(); Element managedPlugins = getChild(root, BUILD, PLUGIN_MANAGEMENT, PLUGINS); //now find the lifecycle stuff if it's there. Element lifecyclePlugin = findChild(managedPlugins, PLUGIN, childEquals(GROUP_ID, LIFECYCLE_PLUGIN_GROUPID), childEquals(ARTIFACT_ID, LIFECYCLE_PLUGIN_ARTIFACTID)); if (lifecyclePlugin == null) { //not found, create lifecyclePlugin = PomHelper.createPlugin(managedPlugins, LIFECYCLE_PLUGIN_GROUPID, LIFECYCLE_PLUGIN_ARTIFACTID, LIFECYCLE_PLUGIN_VERSION); Comment comment = document.createComment("TODO TEXT. This plugin's configuration is used in m2e only."); managedPlugins.insertBefore(comment, lifecyclePlugin); format(comment);/*from w w w . j a v a 2 s. co m*/ } Element pluginExecutions = getChild(lifecyclePlugin, CONFIGURATION, "lifecycleMappingMetadata", "pluginExecutions"); //now find the plugin execution for the plugin we have.. Element execution = null; for (Element exec : findChilds(pluginExecutions, "pluginExecution")) { Element filter = findChild(exec, "pluginExecutionFilter", childEquals("groupId", groupId), childEquals("artifactId", artifactId)); //the action needs to match the action we want.. Element actionEl = findChild(findChild(exec, "action"), action.toString()); if (filter != null && actionEl != null) { String versionRange = getTextValue(getChild(filter, "versionRange")); if (versionRange != null) { // paranoid null check //now we shall do some smart matching on the existing versionRange and our version.. //so far the "smart" thing involves just overwriting the range. try { VersionRange range = VersionRange.createFromVersionSpec(versionRange); if (!range.containsVersion(new DefaultArtifactVersion(version))) { Element rangeEl = findChild(filter, "versionRange"); setText(rangeEl, "[" + version + ",)"); } } catch (InvalidVersionSpecificationException e) { log.error("Failed to parse version range:" + versionRange, e); } } execution = exec; break; } } if (execution == null) { execution = createPluginExecution(document, pluginExecutions); } //now enter/update the goal(s).. Element goalsEl = getChild(execution, "pluginExecutionFilter", "goals"); List<String> toAddGoals = new ArrayList<String>(Arrays.asList(goals)); for (Element existingGoal : findChilds(goalsEl, "goal")) { String glValue = getTextValue(existingGoal); if (glValue != null && toAddGoals.contains(glValue)) { toAddGoals.remove(glValue); } } if (toAddGoals.size() > 0) { for (String goal : toAddGoals) { format(createElementWithText(goalsEl, "goal", goal)); } } }