Search in sources :

Example 36 with ManipulationException

use of org.commonjava.maven.ext.common.ManipulationException in project pom-manipulation-ext by release-engineering.

the class JSONIO method writeJSON.

public void writeJSON(File target, String contents) throws ManipulationException {
    try {
        String pretty = mapper.writer(dpp).writeValueAsString(mapper.readValue(contents, Object.class));
        FileOutputStream fileOutputStream = new FileOutputStream(target);
        try (OutputStreamWriter p = new OutputStreamWriter(fileOutputStream, StandardCharsets.UTF_8)) {
            p.write(pretty);
            p.append('\n');
        }
    } catch (IOException e) {
        logger.error("Unable to write JSON string:  ", e);
        throw new ManipulationException("Unable to write JSON string", e);
    }
}
Also used : FileOutputStream(java.io.FileOutputStream) ManipulationException(org.commonjava.maven.ext.common.ManipulationException) OutputStreamWriter(java.io.OutputStreamWriter) IOException(java.io.IOException)

Example 37 with ManipulationException

use of org.commonjava.maven.ext.common.ManipulationException in project pom-manipulation-ext by release-engineering.

the class DependencyManipulator method apply.

/**
 * Applies dependency overrides to the project.
 */
private void apply(final Project project, final Model model, final Map<ArtifactRef, String> overrides) throws ManipulationException {
    // Map of Group : Map of artifactId [ may be wildcard ] : value
    final WildcardMap<String> explicitOverrides = new WildcardMap<>();
    final String projectGA = ga(project);
    final DependencyState dependencyState = session.getState(DependencyState.class);
    final CommonState commonState = session.getState(CommonState.class);
    logger.info("Processing project {} ", projectGA);
    Map<ArtifactRef, String> moduleOverrides = new LinkedHashMap<>(overrides);
    moduleOverrides = removeReactorGAs(moduleOverrides);
    try {
        moduleOverrides = applyModuleVersionOverrides(projectGA, dependencyState.getDependencyExclusions(), moduleOverrides, explicitOverrides);
        logger.debug("Module overrides are:\n{}", moduleOverrides);
        logger.debug("Explicit overrides are:\n{}", explicitOverrides);
    } catch (InvalidRefException e) {
        logger.error("Invalid module exclusion override {} : {} ", moduleOverrides, explicitOverrides);
        throw e;
    }
    if (project.isInheritanceRoot()) {
        // Handle the situation where the top level parent refers to a prior build that is in the BOM.
        if (project.getModelParent() != null) {
            for (Map.Entry<ArtifactRef, String> entry : moduleOverrides.entrySet()) {
                String oldValue = project.getModelParent().getVersion();
                String newValue = entry.getValue();
                if (entry.getKey().asProjectRef().equals(SimpleProjectRef.parse(ga(project.getModelParent())))) {
                    if (commonState.getStrict()) {
                        if (!PropertiesUtils.checkStrictValue(session, oldValue, newValue)) {
                            if (commonState.getFailOnStrictViolation()) {
                                throw new ManipulationException("Parent reference {} replacement: {} of original version: {} violates the strict version-alignment rule!", ga(project.getModelParent()), newValue, oldValue);
                            } else {
                                logger.warn("Parent reference {} replacement: {} of original version: {} violates the strict version-alignment rule!", ga(project.getModelParent()), newValue, oldValue);
                                // a new property either.
                                continue;
                            }
                        }
                    }
                    logger.debug(" Modifying parent reference from {} to {} for {} ", model.getParent().getVersion(), newValue, ga(project.getModelParent()));
                    model.getParent().setVersion(newValue);
                    break;
                }
            }
            // Apply any explicit overrides to the top level parent. Convert it to a simulated
            // dependency so we can reuse applyExplicitOverrides.
            HashMap<ArtifactRef, Dependency> pDepMap = new HashMap<>();
            Dependency d = new Dependency();
            d.setGroupId(project.getModelParent().getGroupId());
            d.setArtifactId(project.getModelParent().getArtifactId());
            d.setVersion(project.getModelParent().getVersion());
            pDepMap.put(SimpleArtifactRef.parse(d.getManagementKey()), d);
            applyExplicitOverrides(project, pDepMap, explicitOverrides, commonState, explicitVersionPropertyUpdateMap);
            project.getModelParent().setVersion(d.getVersion());
        }
        if (session.getState(DependencyState.class).getOverrideDependencies()) {
            // Apply overrides to project dependency management
            logger.debug("Applying overrides to managed dependencies for: {}", projectGA);
            final Map<ArtifactRef, String> nonMatchingVersionOverrides = applyOverrides(project, project.getResolvedManagedDependencies(session), explicitOverrides, moduleOverrides);
            final Map<ArtifactRef, String> matchedOverrides = new LinkedHashMap<>(moduleOverrides);
            matchedOverrides.keySet().removeAll(nonMatchingVersionOverrides.keySet());
            applyExplicitOverrides(project, project.getResolvedManagedDependencies(session), explicitOverrides, commonState, explicitVersionPropertyUpdateMap);
            if (commonState.getOverrideTransitive()) {
                final List<Dependency> extraDeps = new ArrayList<>();
                // Add dependencies to Dependency Management which did not match any existing dependency
                for (final ArtifactRef var : overrides.keySet()) {
                    if (!nonMatchingVersionOverrides.containsKey(var)) {
                        // This one in the remote pom was already dealt with ; continue.
                        continue;
                    }
                    final Dependency newDependency = new Dependency();
                    newDependency.setGroupId(var.getGroupId());
                    newDependency.setArtifactId(var.getArtifactId());
                    newDependency.setType(var.getType());
                    newDependency.setClassifier(var.getClassifier());
                    final String artifactVersion = moduleOverrides.get(var);
                    newDependency.setVersion(artifactVersion);
                    extraDeps.add(newDependency);
                    logger.debug("New entry added to <DependencyManagement/> - {} : {} ", var, artifactVersion);
                }
                // If the model doesn't have any Dependency Management set by default, create one for it
                DependencyManagement dependencyManagement = model.getDependencyManagement();
                if (extraDeps.size() > 0) {
                    if (dependencyManagement == null) {
                        dependencyManagement = new DependencyManagement();
                        model.setDependencyManagement(dependencyManagement);
                        logger.debug("Added <DependencyManagement/> for current project");
                    }
                    dependencyManagement.getDependencies().addAll(0, extraDeps);
                }
            } else {
                logger.debug("Non-matching dependencies ignored.");
            }
        } else {
            logger.debug("NOT applying overrides to managed dependencies for top-pom: {}", projectGA);
        }
    } else {
        // If a child module has a depMgmt section we'll change that as well.
        if (session.getState(DependencyState.class).getOverrideDependencies()) {
            logger.debug("Applying overrides to managed dependencies for: {}", projectGA);
            applyOverrides(project, project.getResolvedManagedDependencies(session), explicitOverrides, moduleOverrides);
            applyExplicitOverrides(project, project.getResolvedManagedDependencies(session), explicitOverrides, commonState, explicitVersionPropertyUpdateMap);
        } else {
            logger.debug("NOT applying overrides to managed dependencies for: {}", projectGA);
        }
    }
    if (session.getState(DependencyState.class).getOverrideDependencies()) {
        logger.debug("Applying overrides to concrete dependencies for: {}", projectGA);
        // Apply overrides to project direct dependencies
        applyOverrides(project, project.getResolvedDependencies(session), explicitOverrides, moduleOverrides);
        applyExplicitOverrides(project, project.getResolvedDependencies(session), explicitOverrides, commonState, explicitVersionPropertyUpdateMap);
        final HashMap<Profile, HashMap<ArtifactRef, Dependency>> pd = project.getResolvedProfileDependencies(session);
        final HashMap<Profile, HashMap<ArtifactRef, Dependency>> pmd = project.getResolvedProfileManagedDependencies(session);
        for (Profile p : pd.keySet()) {
            applyOverrides(project, pd.get(p), explicitOverrides, moduleOverrides);
            applyExplicitOverrides(project, pd.get(p), explicitOverrides, commonState, explicitVersionPropertyUpdateMap);
        }
        for (Profile p : pmd.keySet()) {
            applyOverrides(project, pmd.get(p), explicitOverrides, moduleOverrides);
            applyExplicitOverrides(project, pmd.get(p), explicitOverrides, commonState, explicitVersionPropertyUpdateMap);
        }
    } else {
        logger.debug("NOT applying overrides to concrete dependencies for: {}", projectGA);
    }
}
Also used : CommonState(org.commonjava.maven.ext.core.state.CommonState) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) InvalidRefException(org.commonjava.maven.atlas.ident.ref.InvalidRefException) ArrayList(java.util.ArrayList) Dependency(org.apache.maven.model.Dependency) Profile(org.apache.maven.model.Profile) ArtifactRef(org.commonjava.maven.atlas.ident.ref.ArtifactRef) SimpleArtifactRef(org.commonjava.maven.atlas.ident.ref.SimpleArtifactRef) LinkedHashMap(java.util.LinkedHashMap) WildcardMap(org.commonjava.maven.ext.core.util.WildcardMap) DependencyState(org.commonjava.maven.ext.core.state.DependencyState) ManipulationException(org.commonjava.maven.ext.common.ManipulationException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) WildcardMap(org.commonjava.maven.ext.core.util.WildcardMap) DependencyManagement(org.apache.maven.model.DependencyManagement)

Example 38 with ManipulationException

use of org.commonjava.maven.ext.common.ManipulationException in project pom-manipulation-ext by release-engineering.

the class DependencyManipulator method applyModuleVersionOverrides.

/**
 * Remove module overrides which do not apply to the current module. Searches the full list of version overrides
 * for any keys which contain the '@' symbol.  Removes these from the version overrides list, and add them back
 * without the '@' symbol only if they apply to the current module.
 *
 * @param projectGA the current project group : artifact
 * @param originalOverrides The full list of version overrides, both global and module specific
 * @param moduleOverrides are individual overrides e.g. group:artifact@groupId:artifactId :: value
 * @param explicitOverrides a custom map to handle wildcard overrides
 * @return The map of global and module specific overrides which apply to the given module
 * @throws ManipulationException if an error occurs
 */
private Map<ArtifactRef, String> applyModuleVersionOverrides(final String projectGA, final Map<String, String> moduleOverrides, Map<ArtifactRef, String> originalOverrides, final WildcardMap explicitOverrides) throws ManipulationException {
    final Map<ArtifactRef, String> remainingOverrides = new LinkedHashMap<>(originalOverrides);
    logger.debug("Calculating module-specific version overrides. Starting with:\n  {}", join(remainingOverrides.entrySet(), "\n  "));
    // These modes correspond to two different kinds of passes over the available override properties:
    // 1. Module-specific: Don't process wildcard overrides here, allow module-specific settings to take precedence.
    // 2. Wildcards: Add these IF there is no corresponding module-specific override.
    final boolean[] wildcardMode = { false, true };
    for (boolean aWildcardMode : wildcardMode) {
        for (final String currentKey : new HashSet<>(moduleOverrides.keySet())) {
            final String currentValue = moduleOverrides.get(currentKey);
            logger.debug("Processing key {} for override with value {}", currentKey, currentValue);
            if (!currentKey.contains("@")) {
                logger.debug("Not an override. Skip.");
                continue;
            }
            final boolean isModuleWildcard = currentKey.endsWith("@*");
            logger.debug("Is wildcard? {} and in module wildcard mode? {} ", isModuleWildcard, aWildcardMode);
            // process module-specific overrides (first)
            if (!aWildcardMode) {
                // skip wildcard overrides in this mode
                if (isModuleWildcard) {
                    logger.debug("Not currently in wildcard mode. Skip.");
                    continue;
                }
                final String[] artifactAndModule = currentKey.split("@");
                if (artifactAndModule.length != 2) {
                    throw new ManipulationException("Invalid format for exclusion key " + currentKey);
                }
                final String artifactGA = artifactAndModule[0];
                final ProjectRef moduleGA = SimpleProjectRef.parse(artifactAndModule[1]);
                logger.debug("For artifact override: {}, comparing parsed module: {} to current project: {}", artifactGA, moduleGA, projectGA);
                if (moduleGA.toString().equals(projectGA) || (moduleGA.getArtifactId().equals("*") && SimpleProjectRef.parse(projectGA).getGroupId().equals(moduleGA.getGroupId()))) {
                    if (currentValue != null && !currentValue.isEmpty()) {
                        explicitOverrides.put(SimpleProjectRef.parse(artifactGA), currentValue);
                        logger.debug("Overriding module dependency for {} with {} : {}", moduleGA, artifactGA, currentValue);
                    } else {
                        // Override prevention...
                        removeGA(remainingOverrides, SimpleProjectRef.parse(artifactGA));
                        logger.debug("For module {}, ignoring dependency override for {} ", moduleGA, artifactGA);
                    }
                }
            } else // process wildcard overrides (second)
            {
                // skip module-specific overrides in this mode i.e. format of groupdId:artifactId@*=
                if (!isModuleWildcard) {
                    logger.debug("Currently in wildcard mode. Skip.");
                    continue;
                }
                final String artifactGA = currentKey.substring(0, currentKey.length() - 2);
                logger.debug("For artifact override: {}, checking if current overrides already contain a module-specific version.", artifactGA);
                if (explicitOverrides.containsKey(SimpleProjectRef.parse(artifactGA))) {
                    logger.debug("For artifact override: {}, current overrides already contain a module-specific version. Skip.", artifactGA);
                    continue;
                }
                // I think this is only used for e.g. dependencyExclusion.groupId:artifactId@*=<explicitVersion>
                if (currentValue != null && !currentValue.isEmpty()) {
                    logger.debug("Overriding module dependency for {} with {} : {}", projectGA, artifactGA, currentValue);
                    explicitOverrides.put(SimpleProjectRef.parse(artifactGA), currentValue);
                } else {
                    // If we have a wildcard artifact we want to replace any prior explicit overrides
                    // with this one i.e. this takes precedence.
                    removeGA(remainingOverrides, SimpleProjectRef.parse(artifactGA));
                    logger.debug("Removing artifactGA " + artifactGA + " from overrides");
                }
            }
        }
    }
    return remainingOverrides;
}
Also used : ManipulationException(org.commonjava.maven.ext.common.ManipulationException) SimpleProjectRef(org.commonjava.maven.atlas.ident.ref.SimpleProjectRef) ProjectRef(org.commonjava.maven.atlas.ident.ref.ProjectRef) ArtifactRef(org.commonjava.maven.atlas.ident.ref.ArtifactRef) SimpleArtifactRef(org.commonjava.maven.atlas.ident.ref.SimpleArtifactRef) LinkedHashMap(java.util.LinkedHashMap) HashSet(java.util.HashSet)

Example 39 with ManipulationException

use of org.commonjava.maven.ext.common.ManipulationException in project pom-manipulation-ext by release-engineering.

the class DistributionEnforcingManipulator method findSkipRefs.

/**
 * Go through the plugin / plugin-execution configurations and find references to the <code>skip</code> parameter for the given Maven plugin
 * instance.
 */
private List<SkipReference> findSkipRefs(final Plugin plugin, final Project project) throws ManipulationException {
    if (plugin == null) {
        return Collections.emptyList();
    }
    final Map<ConfigurationContainer, String> configs = new LinkedHashMap<>();
    Object configuration = plugin.getConfiguration();
    if (configuration != null) {
        configs.put(plugin, configuration.toString());
    }
    final List<PluginExecution> executions = plugin.getExecutions();
    if (executions != null) {
        for (final PluginExecution execution : executions) {
            configuration = execution.getConfiguration();
            if (configuration != null) {
                configs.put(execution, configuration.toString());
            }
        }
    }
    final List<SkipReference> result = new ArrayList<>();
    for (final Map.Entry<ConfigurationContainer, String> entry : configs.entrySet()) {
        try {
            final Document doc = galleyWrapper.parseXml(entry.getValue());
            final NodeList children = doc.getDocumentElement().getChildNodes();
            if (children != null) {
                for (int i = 0; i < children.getLength(); i++) {
                    final Node n = children.item(i);
                    if (n.getNodeName().equals(SKIP_NODE)) {
                        result.add(new SkipReference(entry.getKey(), n));
                    }
                }
            }
        } catch (final GalleyMavenXMLException e) {
            throw new ManipulationException("Unable to parse config for plugin: %s in: %s", e, plugin.getId(), project.getId());
        }
    }
    return result;
}
Also used : PluginExecution(org.apache.maven.model.PluginExecution) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) ArrayList(java.util.ArrayList) GalleyMavenXMLException(org.commonjava.maven.galley.maven.parse.GalleyMavenXMLException) Document(org.w3c.dom.Document) LinkedHashMap(java.util.LinkedHashMap) ConfigurationContainer(org.apache.maven.model.ConfigurationContainer) ManipulationException(org.commonjava.maven.ext.common.ManipulationException) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 40 with ManipulationException

use of org.commonjava.maven.ext.common.ManipulationException in project pom-manipulation-ext by release-engineering.

the class GroovyManipulator method applyChanges.

/**
 * Apply the groovy script changes to the top level pom.
 */
@Override
public Set<Project> applyChanges(final List<Project> projects) throws ManipulationException {
    final GroovyState state = session.getState(GroovyState.class);
    if (!session.isEnabled() || !state.isEnabled()) {
        logger.debug(getClass().getSimpleName() + ": Nothing to do!");
        return Collections.emptySet();
    }
    final Set<Project> changed = new HashSet<>();
    for (File groovyScript : parseGroovyScripts(state.getGroovyScripts())) {
        GroovyShell shell = new GroovyShell();
        Script script;
        for (final Project project : projects) {
            if (project.isExecutionRoot()) {
                logger.info("Executing {} on {}", groovyScript, project);
                try {
                    script = shell.parse(groovyScript);
                    if (script instanceof BaseScript) {
                        ((BaseScript) script).setValues(session.getUserProperties(), projects, project);
                    } else {
                        throw new ManipulationException("Cannot cast " + groovyScript + " to a BaseScript to set values.");
                    }
                } catch (MissingMethodException e) {
                    try {
                        logger.debug("Failure when injecting into script {} ", FileUtils.readFileToString(groovyScript), e);
                    } catch (IOException e1) {
                        logger.debug("Unable to read script file {} for debugging! {} ", groovyScript, e1);
                    }
                    throw new ManipulationException("Unable to inject values into base script", e);
                } catch (CompilationFailedException e) {
                    try {
                        logger.debug("Failure when parsing script {} ", FileUtils.readFileToString(groovyScript), e);
                    } catch (IOException e1) {
                        logger.debug("Unable to read script file {} for debugging! {} ", groovyScript, e1);
                    }
                    throw new ManipulationException("Unable to parse script", e);
                } catch (IOException e) {
                    throw new ManipulationException("Unable to parse script", e);
                }
                try {
                    script.run();
                } catch (Exception e) {
                    throw new ManipulationException("Unable to parse script", e);
                }
                changed.add(project);
            }
        }
    }
    return changed;
}
Also used : Script(groovy.lang.Script) BaseScript(org.commonjava.maven.ext.core.groovy.BaseScript) CompilationFailedException(org.codehaus.groovy.control.CompilationFailedException) IOException(java.io.IOException) GroovyShell(groovy.lang.GroovyShell) MissingMethodException(groovy.lang.MissingMethodException) IOException(java.io.IOException) ManipulationException(org.commonjava.maven.ext.common.ManipulationException) CompilationFailedException(org.codehaus.groovy.control.CompilationFailedException) GroovyState(org.commonjava.maven.ext.core.state.GroovyState) Project(org.commonjava.maven.ext.common.model.Project) MissingMethodException(groovy.lang.MissingMethodException) BaseScript(org.commonjava.maven.ext.core.groovy.BaseScript) ManipulationException(org.commonjava.maven.ext.common.ManipulationException) File(java.io.File) HashSet(java.util.HashSet)

Aggregations

ManipulationException (org.commonjava.maven.ext.common.ManipulationException)42 IOException (java.io.IOException)13 File (java.io.File)11 HashMap (java.util.HashMap)7 HashSet (java.util.HashSet)7 LinkedHashMap (java.util.LinkedHashMap)7 Project (org.commonjava.maven.ext.common.model.Project)7 ArrayList (java.util.ArrayList)6 Map (java.util.Map)6 ArtifactRef (org.commonjava.maven.atlas.ident.ref.ArtifactRef)6 Properties (java.util.Properties)5 SimpleArtifactRef (org.commonjava.maven.atlas.ident.ref.SimpleArtifactRef)5 JsonPathException (com.jayway.jsonpath.JsonPathException)4 ProjectVersionRef (org.commonjava.maven.atlas.ident.ref.ProjectVersionRef)4 SimpleProjectRef (org.commonjava.maven.atlas.ident.ref.SimpleProjectRef)4 CommonState (org.commonjava.maven.ext.core.state.CommonState)4 Test (org.junit.Test)4 DocumentContext (com.jayway.jsonpath.DocumentContext)3 FileInputStream (java.io.FileInputStream)3 Dependency (org.apache.maven.model.Dependency)3