Search in sources :

Example 16 with ManipulationException

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

the class PropertiesUtilsTest method testUpdateNestedProperties3.

@Test
public void testUpdateNestedProperties3() throws Exception {
    // io.hawt:project:1.4.9
    final Model modelParent = TestUtils.resolveModelResource(RESOURCE_BASE, "project-1.4.9.pom");
    Project pP = new Project(modelParent);
    ManipulationSession session = createUpdateSession();
    assertTrue(updateProperties(session, pP, false, "perfectus-build", "610379.redhat-1") == PropertiesUtils.PropertyUpdate.FOUND);
    try {
        assertTrue(updateProperties(session, pP, false, "perfectus-build", "610.NOTTHEVALUE.redhat-1") == PropertiesUtils.PropertyUpdate.FOUND);
    } catch (ManipulationException e) {
        e.printStackTrace();
    // Pass.
    }
    try {
        assertTrue(updateProperties(session, pP, true, "perfectus-build", "610.NOTTHEVALUE.redhat-1") == PropertiesUtils.PropertyUpdate.FOUND);
    } catch (ManipulationException e) {
        e.printStackTrace();
    // Pass.
    }
}
Also used : Project(org.commonjava.maven.ext.common.model.Project) Model(org.apache.maven.model.Model) ManipulationSession(org.commonjava.maven.ext.core.ManipulationSession) ManipulationException(org.commonjava.maven.ext.common.ManipulationException) Test(org.junit.Test)

Example 17 with ManipulationException

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

the class ManipulatingEventSpy method onEvent.

@Override
public void onEvent(final Object event) throws Exception {
    boolean required = false;
    try {
        if (event instanceof ExecutionEvent) {
            final ExecutionEvent ee = (ExecutionEvent) event;
            required = Boolean.parseBoolean(ee.getSession().getRequest().getUserProperties().getProperty(REQUIRE_EXTENSION, "false"));
            final ExecutionEvent.Type type = ee.getType();
            if (type == Type.ProjectDiscoveryStarted) {
                if (ee.getSession() != null) {
                    if (ee.getSession().getRequest().getLoggingLevel() == 0) {
                        final ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
                        root.setLevel(Level.DEBUG);
                    }
                    session.setMavenSession(ee.getSession());
                    if (ee.getSession().getRequest().getPom() != null) {
                        Properties config = configIO.parse(ee.getSession().getRequest().getPom().getParentFile());
                        String value = session.getUserProperties().getProperty("allowConfigFilePrecedence");
                        if (isNotEmpty(value) && "true".equalsIgnoreCase(value)) {
                            session.getUserProperties().putAll(config);
                        } else {
                            for (String key : config.stringPropertyNames()) {
                                if (!session.getUserProperties().containsKey(key)) {
                                    session.getUserProperties().setProperty(key, config.getProperty(key));
                                }
                            }
                        }
                    }
                    manipulationManager.init(session);
                } else {
                    logger.error("Null session ; unable to continue");
                    return;
                }
                if (!session.isEnabled()) {
                    logger.info("Manipulation engine disabled via command-line option");
                    return;
                } else if (ee.getSession().getRequest().getPom() == null) {
                    logger.info("Manipulation engine disabled. No project found.");
                    return;
                } else if (new File(ee.getSession().getRequest().getPom().getParentFile(), ManipulationManager.MARKER_FILE).exists()) {
                    logger.info("Skipping manipulation as previous execution found.");
                    return;
                }
                manipulationManager.scanAndApply(session);
            }
        }
    } catch (final ManipulationException e) {
        logger.error("Extension failure", e);
        if (required) {
            throw e;
        } else {
            session.setError(e);
        }
    }// Catch any runtime exceptions and mark them to fail the build as well.
     catch (final RuntimeException e) {
        logger.error("Extension failure", e);
        if (required) {
            throw e;
        } else {
            session.setError(new ManipulationException("Caught runtime exception", e));
        }
    } finally {
        super.onEvent(event);
    }
}
Also used : Logger(org.slf4j.Logger) Properties(java.util.Properties) Type(org.apache.maven.execution.ExecutionEvent.Type) ExecutionEvent(org.apache.maven.execution.ExecutionEvent) ManipulationException(org.commonjava.maven.ext.common.ManipulationException) File(java.io.File)

Example 18 with ManipulationException

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

the class ManipulationManager method scanAndApply.

/**
 * Encapsulates {@link #applyManipulations(List)}
 *
 * @param session the container session for manipulation.
 * @throws ManipulationException if an error occurs.
 */
public void scanAndApply(final ManipulationSession session) throws ManipulationException {
    final List<Project> projects = pomIO.parseProject(session.getPom());
    session.setProjects(projects);
    for (final Project project : projects) {
        logger.debug("Got " + project + " (POM: " + project.getPom() + ")");
    }
    Set<Project> changed = applyManipulations(projects);
    // Create a marker file if we made some changes to prevent duplicate runs.
    if (!changed.isEmpty()) {
        logger.info("Maven-Manipulation-Extension: Rewrite changed: " + projects);
        GAV gav = pomIO.rewritePOMs(changed);
        try {
            final VersioningState state = session.getState(VersioningState.class);
            state.setExecutionRootModified(gav);
            new File(session.getTargetDir().getParentFile(), ManipulationManager.MARKER_PATH).mkdirs();
            new File(session.getTargetDir().getParentFile(), ManipulationManager.MARKER_FILE).createNewFile();
            try (FileWriter writer = new FileWriter(new File(session.getTargetDir().getParentFile(), RESULT_FILE))) {
                writer.write(collectResults(session));
            }
        } catch (IOException e) {
            logger.error("Unable to create marker or result file", e);
            throw new ManipulationException("Marker/result file creation failed", e);
        }
    }
    // Ensure shutdown of GalleyInfrastructure Executor Service
    for (ExtensionInfrastructure e : infrastructure.values()) {
        e.finish();
    }
    logger.info("Maven-Manipulation-Extension: Finished.");
}
Also used : Project(org.commonjava.maven.ext.common.model.Project) ExtensionInfrastructure(org.commonjava.maven.ext.io.resolver.ExtensionInfrastructure) FileWriter(java.io.FileWriter) ManipulationException(org.commonjava.maven.ext.common.ManipulationException) VersioningState(org.commonjava.maven.ext.core.state.VersioningState) IOException(java.io.IOException) GAV(org.commonjava.maven.ext.common.model.GAV) File(java.io.File)

Example 19 with ManipulationException

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

the class GroovyManipulator method parseGroovyScripts.

/**
 * Splits the value on ',', then wraps each value in {@link SimpleArtifactRef#parse(String)} and prints a warning / skips in the event of a
 * parsing error. Returns null if the input value is null.
 * @param value a comma separated list of GAVTC to parse
 * @return a collection of parsed ArtifactRef.
 */
public List<File> parseGroovyScripts(final String value) throws ManipulationException {
    if (isEmpty(value)) {
        return Collections.emptyList();
    } else {
        final List<File> result = new ArrayList<>();
        logger.debug("Processing groovy scripts {} ", value);
        try {
            final String[] scripts = value.split(",");
            for (final String script : scripts) {
                File found;
                if (script.startsWith("http")) {
                    logger.info("Attempting to read URL {} ", script);
                    found = fileIO.resolveURL(new URL(script));
                } else {
                    final ArtifactRef ar = SimpleArtifactRef.parse(script);
                    logger.info("Attempting to read GAV {} with classifier {} and type {} ", ar.asProjectVersionRef(), ar.getClassifier(), ar.getType());
                    found = modelBuilder.resolveRawFile(ar);
                }
                result.add(found);
            }
        } catch (IOException e) {
            throw new ManipulationException("Unable to parse groovyScripts", e);
        }
        return result;
    }
}
Also used : ArrayList(java.util.ArrayList) ManipulationException(org.commonjava.maven.ext.common.ManipulationException) IOException(java.io.IOException) File(java.io.File) URL(java.net.URL) ArtifactRef(org.commonjava.maven.atlas.ident.ref.ArtifactRef) SimpleArtifactRef(org.commonjava.maven.atlas.ident.ref.SimpleArtifactRef)

Example 20 with ManipulationException

use of org.commonjava.maven.ext.common.ManipulationException 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)

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