Search in sources :

Example 41 with Xpp3Dom

use of org.codehaus.plexus.util.xml.Xpp3Dom in project pom-manipulation-ext by release-engineering.

the class PluginManipulator method applyOverrides.

/**
 * Set the versions of any plugins which match the contents of the list of plugin overrides.
 *
 * Currently this method takes the remote plugin type (note that remote plugins are deprecated) and the local plugin type.
 * It will ONLY apply configurations, executions and dependencies from the remote pluginMgmt to the local pluginMgmt.
 *   If the local pluginMgmt does not have a matching plugin then, if {@link CommonState#getOverrideTransitive()} is true
 * then it will inject a new plugin into the local pluginMgmt.
 *   It will however apply version changes to both local pluginMgmt and local plugins.
 * Note that if the deprecated injectRemotePlugins is enabled then remote plugin version, executions, dependencies and
 * configurations will also be applied to the local plugins.
 *
 * @param project the current project
 * @param remotePluginType The type of the remote plugin (mgmt or plugins)
 * @param localPluginType The type of local block (mgmt or plugins). Only used to determine whether to inject configs/deps/executions.
 * @param plugins The list of plugins to modify
 * @param pluginVersionOverrides The list of version overrides to apply to the plugins
 * @throws ManipulationException if an error occurs.
 */
private void applyOverrides(Project project, PluginType remotePluginType, final PluginType localPluginType, final HashMap<ProjectVersionRef, Plugin> plugins, final Set<Plugin> pluginVersionOverrides) throws ManipulationException {
    if (plugins == null) {
        throw new ManipulationException("Original plugins should not be null");
    }
    final PluginState pluginState = session.getState(PluginState.class);
    final CommonState commonState = session.getState(CommonState.class);
    final HashMap<String, ProjectVersionRef> pluginsByGA = new LinkedHashMap<>();
    // Secondary map of original plugins group:artifact to pvr mapping.
    for (ProjectVersionRef pvr : plugins.keySet()) {
        // We should NEVER have multiple group:artifact with different versions in the same project. If we do,
        // like with dependencies, the behaviour is undefined - although its most likely the last-wins.
        pluginsByGA.put(pvr.asProjectRef().toString(), pvr);
    }
    for (final Plugin override : pluginVersionOverrides) {
        Plugin plugin = null;
        String newValue = override.getVersion();
        // override version.
        if (pluginsByGA.containsKey(override.getKey())) {
            // Potential match of override group:artifact to original plugin group:artifact.
            String oldValue = pluginsByGA.get(override.getKey()).getVersionString();
            plugin = plugins.get(pluginsByGA.get(override.getKey()));
            if (commonState.getStrict()) {
                if (!PropertiesUtils.checkStrictValue(session, oldValue, newValue)) {
                    if (commonState.getFailOnStrictViolation()) {
                        throw new ManipulationException("Plugin reference {} replacement: {} of original version: {} violates the strict version-alignment rule!", plugin.getId(), newValue, oldValue);
                    } else {
                        logger.warn("Plugin reference {} replacement: {} of original version: {} violates the strict version-alignment rule!", plugin.getId(), newValue, oldValue);
                        // a new property either.
                        continue;
                    }
                }
            }
        }
        logger.debug("Plugin override {} and local plugin {} with remotePluginType {} / localPluginType {}", override.getId(), plugin, remotePluginType, localPluginType);
        if (plugin != null) {
            if (localPluginType == PluginType.LocalPM) {
                if (override.getConfiguration() != null) {
                    logger.debug("Injecting plugin configuration" + override.getConfiguration());
                    if (plugin.getConfiguration() == null) {
                        plugin.setConfiguration(override.getConfiguration());
                        logger.debug("Altered plugin configuration: " + plugin.getKey() + "=" + plugin.getConfiguration());
                    } else if (plugin.getConfiguration() != null) {
                        logger.debug("Existing plugin configuration: " + plugin.getConfiguration());
                        if (!(plugin.getConfiguration() instanceof Xpp3Dom) || !(override.getConfiguration() instanceof Xpp3Dom)) {
                            throw new ManipulationException("Incorrect DOM type " + plugin.getConfiguration().getClass().getName() + " and" + override.getConfiguration().getClass().getName());
                        }
                        if (pluginState.getConfigPrecedence() == Precedence.REMOTE) {
                            plugin.setConfiguration(Xpp3DomUtils.mergeXpp3Dom((Xpp3Dom) override.getConfiguration(), (Xpp3Dom) plugin.getConfiguration()));
                        } else if (pluginState.getConfigPrecedence() == Precedence.LOCAL) {
                            plugin.setConfiguration(Xpp3DomUtils.mergeXpp3Dom((Xpp3Dom) plugin.getConfiguration(), (Xpp3Dom) override.getConfiguration()));
                        }
                        logger.debug("Altered plugin configuration: " + plugin.getKey() + "=" + plugin.getConfiguration());
                    }
                } else {
                    logger.debug("No remote configuration to inject from " + override.toString());
                }
                if (override.getExecutions() != null) {
                    Map<String, PluginExecution> newExecutions = override.getExecutionsAsMap();
                    Map<String, PluginExecution> originalExecutions = plugin.getExecutionsAsMap();
                    for (PluginExecution pe : newExecutions.values()) {
                        if (originalExecutions.containsKey(pe.getId())) {
                            logger.warn("Unable to inject execution " + pe.getId() + " as it clashes with an existing execution");
                        } else {
                            logger.debug("Injecting execution {} ", pe);
                            plugin.getExecutions().add(pe);
                        }
                    }
                } else {
                    logger.debug("No remote executions to inject from " + override.toString());
                }
                if (!override.getDependencies().isEmpty()) {
                    // TODO: ### Review this - is it still required?
                    logger.debug("Checking original plugin dependencies versus override");
                    // First, remove any Dependency from the original Plugin if the GA exists in the override.
                    Iterator<Dependency> originalIt = plugin.getDependencies().iterator();
                    while (originalIt.hasNext()) {
                        Dependency originalD = originalIt.next();
                        Iterator<Dependency> overrideIt = override.getDependencies().iterator();
                        while (overrideIt.hasNext()) {
                            Dependency newD = overrideIt.next();
                            if (originalD.getGroupId().equals(newD.getGroupId()) && originalD.getArtifactId().equals(newD.getArtifactId())) {
                                logger.debug("Removing original dependency {} in favour of {} ", originalD, newD);
                                originalIt.remove();
                                break;
                            }
                        }
                    }
                    // Now merge them together. Only inject dependencies in the management block.
                    logger.debug("Adding in plugin dependencies {}", override.getDependencies());
                    plugin.getDependencies().addAll(override.getDependencies());
                }
            }
            // Explicitly using the original non-resolved original version.
            String oldVersion = plugin.getVersion();
            // will never be null.
            if (!PropertiesUtils.cacheProperty(project, commonState, versionPropertyUpdateMap, oldVersion, newValue, plugin, false)) {
                if (oldVersion != null && oldVersion.equals("${project.version}")) {
                    logger.debug("For plugin {} ; version is built in {} so skipping inlining {}", plugin, oldVersion, newValue);
                } else if (oldVersion != null && oldVersion.contains("${")) {
                    throw new ManipulationException("NYI : Multiple embedded properties for plugins.");
                } else {
                    plugin.setVersion(newValue);
                    logger.info("Altered plugin version: " + override.getKey() + "=" + newValue);
                }
            }
        } else // get the correct config.
        if (remotePluginType == PluginType.RemotePM && localPluginType == PluginType.LocalPM && commonState.getOverrideTransitive() && (override.getConfiguration() != null || override.getExecutions().size() > 0)) {
            project.getModel().getBuild().getPluginManagement().getPlugins().add(override);
            logger.info("Added plugin version: " + override.getKey() + "=" + newValue);
        } else // TODO: Deprecated section.
        if (remotePluginType == PluginType.RemoteP && localPluginType == PluginType.LocalP && pluginState.getInjectRemotePlugins() && (override.getConfiguration() != null || override.getExecutions().size() > 0)) {
            project.getModel().getBuild().getPlugins().add(override);
            logger.info("For non-pluginMgmt, added plugin version : " + override.getKey() + "=" + newValue);
        }
    }
}
Also used : PluginState(org.commonjava.maven.ext.core.state.PluginState) CommonState(org.commonjava.maven.ext.core.state.CommonState) PluginExecution(org.apache.maven.model.PluginExecution) Xpp3Dom(org.codehaus.plexus.util.xml.Xpp3Dom) Dependency(org.apache.maven.model.Dependency) LinkedHashMap(java.util.LinkedHashMap) ProjectVersionRef(org.commonjava.maven.atlas.ident.ref.ProjectVersionRef) ManipulationException(org.commonjava.maven.ext.common.ManipulationException) Plugin(org.apache.maven.model.Plugin)

Example 42 with Xpp3Dom

use of org.codehaus.plexus.util.xml.Xpp3Dom in project revapi by revapi.

the class ReportAggregateMojo method getRunConfig.

private ProjectVersions getRunConfig(MavenProject project) {
    ProjectVersions ret = new ProjectVersions();
    Plugin revapiPlugin = findRevapi(project);
    if (revapiPlugin == null) {
        return ret;
    }
    Xpp3Dom pluginConfig = (Xpp3Dom) revapiPlugin.getConfiguration();
    String[] oldArtifacts = getArtifacts(pluginConfig, "oldArtifacts");
    String[] newArtifacts = getArtifacts(pluginConfig, "newArtifacts");
    String oldVersion = getValueOfChild(pluginConfig, "oldVersion");
    if (oldVersion == null) {
        oldVersion = System.getProperties().getProperty(Props.oldVersion.NAME, Props.oldVersion.DEFAULT_VALUE);
    }
    String newVersion = getValueOfChild(pluginConfig, "newVersion");
    if (newVersion == null) {
        newVersion = System.getProperties().getProperty(Props.newVersion.NAME, project.getVersion());
    }
    String defaultOldArtifact = Analyzer.getProjectArtifactCoordinates(project, oldVersion);
    String defaultNewArtifact = Analyzer.getProjectArtifactCoordinates(project, newVersion);
    if (oldArtifacts == null || oldArtifacts.length == 0) {
        if (!project.getArtifact().getArtifactHandler().isAddedToClasspath()) {
            return ret;
        }
        oldArtifacts = new String[] { defaultOldArtifact };
    }
    if (newArtifacts == null || newArtifacts.length == 0) {
        if (!project.getArtifact().getArtifactHandler().isAddedToClasspath()) {
            return ret;
        }
        newArtifacts = new String[] { defaultNewArtifact };
    }
    String versionRegexString = getValueOfChild(pluginConfig, "versionFormat");
    Pattern versionRegex = versionRegexString == null ? null : Pattern.compile(versionRegexString);
    DefaultRepositorySystemSession session = new DefaultRepositorySystemSession(repositorySystemSession);
    session.setDependencySelector(new ScopeDependencySelector("compile", "provided"));
    session.setDependencyTraverser(new ScopeDependencyTraverser("compile", "provided"));
    if (alwaysCheckForReleaseVersion) {
        session.setUpdatePolicy(RepositoryPolicy.UPDATE_POLICY_ALWAYS);
    }
    ArtifactResolver resolver = new ArtifactResolver(repositorySystem, session, mavenSession.getCurrentProject().getRemoteProjectRepositories());
    Function<String, Artifact> resolve = gav -> {
        try {
            return Analyzer.resolveConstrained(project, gav, versionRegex, resolver);
        } catch (VersionRangeResolutionException | ArtifactResolutionException e) {
            getLog().warn("Could not resolve artifact '" + gav + "' with message: " + e.getMessage());
            return null;
        }
    };
    ret.oldGavs = Stream.of(oldArtifacts).map(resolve).filter(f -> f != null).toArray(Artifact[]::new);
    ret.newGavs = Stream.of(newArtifacts).map(resolve).filter(f -> f != null).toArray(Artifact[]::new);
    return ret;
}
Also used : Component(org.apache.maven.plugins.annotations.Component) HashMap(java.util.HashMap) Xpp3Dom(org.codehaus.plexus.util.xml.Xpp3Dom) Function(java.util.function.Function) Sink(org.apache.maven.doxia.sink.Sink) MessageFormat(java.text.MessageFormat) Execute(org.apache.maven.plugins.annotations.Execute) Mojo(org.apache.maven.plugins.annotations.Mojo) VersionRangeResolutionException(org.eclipse.aether.resolution.VersionRangeResolutionException) ResourceBundle(java.util.ResourceBundle) MavenProject(org.apache.maven.project.MavenProject) Locale(java.util.Locale) Map(java.util.Map) ArtifactResolver(org.revapi.maven.utils.ArtifactResolver) SITE(org.apache.maven.plugins.annotations.LifecyclePhase.SITE) ArtifactResolutionException(org.eclipse.aether.resolution.ArtifactResolutionException) API(org.revapi.API) MavenSession(org.apache.maven.execution.MavenSession) RepositoryPolicy(org.eclipse.aether.repository.RepositoryPolicy) MavenReportException(org.apache.maven.reporting.MavenReportException) Artifact(org.eclipse.aether.artifact.Artifact) AnalysisResult(org.revapi.AnalysisResult) Collectors(java.util.stream.Collectors) Revapi(org.revapi.Revapi) File(java.io.File) DefaultRepositorySystemSession(org.eclipse.aether.DefaultRepositorySystemSession) PACKAGE(org.apache.maven.plugins.annotations.LifecyclePhase.PACKAGE) List(java.util.List) Plugin(org.apache.maven.model.Plugin) Stream(java.util.stream.Stream) ScopeDependencyTraverser(org.revapi.maven.utils.ScopeDependencyTraverser) Pattern(java.util.regex.Pattern) Collections(java.util.Collections) ScopeDependencySelector(org.revapi.maven.utils.ScopeDependencySelector) Pattern(java.util.regex.Pattern) Xpp3Dom(org.codehaus.plexus.util.xml.Xpp3Dom) ArtifactResolver(org.revapi.maven.utils.ArtifactResolver) Artifact(org.eclipse.aether.artifact.Artifact) ScopeDependencyTraverser(org.revapi.maven.utils.ScopeDependencyTraverser) DefaultRepositorySystemSession(org.eclipse.aether.DefaultRepositorySystemSession) Plugin(org.apache.maven.model.Plugin) ScopeDependencySelector(org.revapi.maven.utils.ScopeDependencySelector)

Example 43 with Xpp3Dom

use of org.codehaus.plexus.util.xml.Xpp3Dom in project custom-war-packager by jenkinsci.

the class MavenWARPackagePOMGenerator method generateCustomWarGoalConfiguration.

private Xpp3Dom generateCustomWarGoalConfiguration(Map<String, String> manifestEntries) {
    Xpp3Dom filteringDeploymentDescriptors = new Xpp3Dom("filteringDeploymentDescriptors");
    filteringDeploymentDescriptors.setValue("true");
    Xpp3Dom webResources = new Xpp3Dom("webResources");
    Xpp3Dom directory = new Xpp3Dom("directory");
    directory.setValue(sourceWar.getAbsolutePath());
    Xpp3Dom resource = new Xpp3Dom("resource");
    resource.addChild(directory);
    webResources.addChild(resource);
    // 
    Xpp3Dom archive = new Xpp3Dom("archive");
    Xpp3Dom manifest = new Xpp3Dom("manifest");
    Xpp3Dom mainClass = new Xpp3Dom("mainClass");
    mainClass.setValue("Main");
    manifest.addChild(mainClass);
    archive.addChild(manifest);
    Xpp3Dom manifestEntriesNode = addKeyValueMapArray("manifestEntries", manifestEntries);
    archive.addChild(manifestEntriesNode);
    Xpp3Dom dom = new Xpp3Dom("configuration");
    dom.addChild(filteringDeploymentDescriptors);
    dom.addChild(webResources);
    dom.addChild(archive);
    return dom;
}
Also used : Xpp3Dom(org.codehaus.plexus.util.xml.Xpp3Dom)

Example 44 with Xpp3Dom

use of org.codehaus.plexus.util.xml.Xpp3Dom in project maven-archetype by apache.

the class ArchetypeDescriptorBuilder method build.

public ArchetypeDescriptor build(Reader reader) throws IOException, XmlPullParserException {
    ArchetypeDescriptor descriptor = new ArchetypeDescriptor();
    Xpp3Dom dom = Xpp3DomBuilder.build(reader);
    descriptor.setId(dom.getChild("id").getValue());
    Xpp3Dom allowPartialDom = dom.getChild("allowPartial");
    if (allowPartialDom != null) {
        String allowPartial = allowPartialDom.getValue();
        if ("true".equals(allowPartial) || "1".equals(allowPartial) || "on".equals(allowPartial)) {
            descriptor.setAllowPartial(true);
        }
    }
    // ----------------------------------------------------------------------
    // Main
    // ----------------------------------------------------------------------
    Xpp3Dom sources = dom.getChild("sources");
    if (sources != null) {
        Xpp3Dom[] sourceList = sources.getChildren("source");
        for (int i = 0; i < sourceList.length; i++) {
            addSourceToDescriptor(sourceList[i], descriptor);
        }
    }
    Xpp3Dom resources = dom.getChild("resources");
    if (resources != null) {
        Xpp3Dom[] resourceList = resources.getChildren("resource");
        for (int i = 0; i < resourceList.length; i++) {
            addResourceToDescriptor(resourceList[i], descriptor);
        }
    }
    // ----------------------------------------------------------------------
    // Test
    // ----------------------------------------------------------------------
    Xpp3Dom testSources = dom.getChild("testSources");
    if (testSources != null) {
        Xpp3Dom[] testSourceList = testSources.getChildren("source");
        for (int i = 0; i < testSourceList.length; i++) {
            addTestSourceToDescriptor(testSourceList[i], descriptor);
        }
    }
    Xpp3Dom testResources = dom.getChild("testResources");
    if (testResources != null) {
        Xpp3Dom[] testResourceList = testResources.getChildren("resource");
        for (int i = 0; i < testResourceList.length; i++) {
            addTestResourceToDescriptor(testResourceList[i], descriptor);
        }
    }
    // ----------------------------------------------------------------------
    // Site
    // ----------------------------------------------------------------------
    Xpp3Dom siteResources = dom.getChild("siteResources");
    if (siteResources != null) {
        Xpp3Dom[] siteResourceList = siteResources.getChildren("resource");
        for (int i = 0; i < siteResourceList.length; i++) {
            addSiteResourceToDescriptor(siteResourceList[i], descriptor);
        }
    }
    return descriptor;
}
Also used : Xpp3Dom(org.codehaus.plexus.util.xml.Xpp3Dom)

Example 45 with Xpp3Dom

use of org.codehaus.plexus.util.xml.Xpp3Dom in project maven-archetype by apache.

the class DefaultPomManager method mergeBuildPlugins.

private void mergeBuildPlugins(BuildBase modelBuild, BuildBase generatedModelBuild) {
    @SuppressWarnings("unchecked") Map<String, Plugin> pluginsByIds = modelBuild.getPluginsAsMap();
    @SuppressWarnings("unchecked") List<Plugin> generatedPlugins = generatedModelBuild.getPlugins();
    for (Plugin generatedPlugin : generatedPlugins) {
        String generatedPluginsId = generatedPlugin.getKey();
        if (!pluginsByIds.containsKey(generatedPluginsId)) {
            modelBuild.addPlugin(generatedPlugin);
        } else {
            getLogger().info("Try to merge plugin configuration of plugins with id: " + generatedPluginsId);
            Plugin modelPlugin = (Plugin) pluginsByIds.get(generatedPluginsId);
            modelPlugin.setConfiguration(Xpp3DomUtils.mergeXpp3Dom((Xpp3Dom) generatedPlugin.getConfiguration(), (Xpp3Dom) modelPlugin.getConfiguration()));
        }
    }
}
Also used : Xpp3Dom(org.codehaus.plexus.util.xml.Xpp3Dom) ReportPlugin(org.apache.maven.model.ReportPlugin) Plugin(org.apache.maven.model.Plugin)

Aggregations

Xpp3Dom (org.codehaus.plexus.util.xml.Xpp3Dom)156 Plugin (org.apache.maven.model.Plugin)39 File (java.io.File)26 ArrayList (java.util.ArrayList)18 PluginExecution (org.apache.maven.model.PluginExecution)18 IOException (java.io.IOException)13 HashMap (java.util.HashMap)11 Test (org.junit.Test)11 MavenSession (org.apache.maven.execution.MavenSession)10 MavenProject (org.apache.maven.project.MavenProject)10 Model (org.apache.maven.model.Model)9 Reader (java.io.Reader)8 Build (org.apache.maven.model.Build)8 TargetPlatformConfiguration (org.eclipse.tycho.core.TargetPlatformConfiguration)8 BuildFailureException (org.eclipse.tycho.core.shared.BuildFailureException)8 MojoExecution (org.apache.maven.plugin.MojoExecution)7 XmlPullParserException (org.codehaus.plexus.util.xml.pull.XmlPullParserException)7 Map (java.util.Map)6 Dependency (org.apache.maven.model.Dependency)6 StringReader (java.io.StringReader)5