Search in sources :

Example 21 with EnforcerRuleException

use of org.apache.maven.enforcer.rule.api.EnforcerRuleException in project admin-console-beta by connexta.

the class ArtifactSizeEnforcerRule method getArtifactPath.

private String getArtifactPath(EnforcerRuleHelper helper) throws EnforcerRuleException {
    String convertedArtifactLocation = artifactLocation;
    if (StringUtils.isNotEmpty(convertedArtifactLocation)) {
        helper.getLog().info(String.format("Using specified artifactLocation %s", convertedArtifactLocation));
    } else {
        try {
            helper.getLog().info("artifactLocation property not specified. Looking up artifact using maven properties.");
            String artifactId = (String) helper.evaluate(PROJECT_ARTIFACT_ID_PROP);
            String version = (String) helper.evaluate(PROJECT_VERSION_PROP);
            String packaging = getPackaging(helper);
            String buildDir = (String) helper.evaluate(PROJECT_BUILD_DIR_PROP);
            helper.getLog().debug(String.format(DEFAULT_ARTIFACT_INFO_MSG, artifactId, version, packaging, buildDir));
            convertedArtifactLocation = buildDir + File.separator + artifactId + "-" + version + "." + packaging;
            helper.getLog().debug(String.format("Complete generated artifact path: %s", convertedArtifactLocation));
        } catch (ExpressionEvaluationException e) {
            throw new EnforcerRuleException(e.getMessage());
        }
    }
    return convertedArtifactLocation;
}
Also used : ExpressionEvaluationException(org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException) EnforcerRuleException(org.apache.maven.enforcer.rule.api.EnforcerRuleException)

Example 22 with EnforcerRuleException

use of org.apache.maven.enforcer.rule.api.EnforcerRuleException in project semantic-versioning by jeluard.

the class RequireBackwardCompatibility method enforce.

@Override
protected void enforce(final EnforcerRuleHelper helper, final Delta delta, final Version previous, final Version current) throws EnforcerRuleException {
    if (this.compatibilityType == null) {
        throw new IllegalArgumentException("A value for compatibilityType attribute must be provided.");
    }
    final Delta.CompatibilityType expectedCompatibilityType;
    try {
        expectedCompatibilityType = Delta.CompatibilityType.valueOf(this.compatibilityType);
    } catch (IllegalStateException e) {
        throw new EnforcerRuleException("Compatibility type value must be one of " + Delta.CompatibilityType.values());
    }
    final Delta.CompatibilityType detectedCompatibilityType = delta.computeCompatibilityType();
    if (this.strictChecking) {
        if (detectedCompatibilityType != expectedCompatibilityType) {
            fail(delta, "Current codebase is not strictly backward compatible (" + this.compatibilityType + ") with version <" + previous + ">. Compatibility type has been detected as <" + detectedCompatibilityType + ">");
        }
    } else {
        if (expectedCompatibilityType == Delta.CompatibilityType.NON_BACKWARD_COMPATIBLE) {
            helper.getLog().warn("Rule will never fail as compatibility type " + Delta.CompatibilityType.NON_BACKWARD_COMPATIBLE + " is used with non-strict checking.");
        }
        if (detectedCompatibilityType.compareTo(expectedCompatibilityType) > 0) {
            fail(delta, "Current codebase is not backward compatible (" + this.compatibilityType + ") with version <" + previous + ">. Compatibility type has been detected as <" + detectedCompatibilityType + ">");
        }
    }
}
Also used : Delta(org.semver.Delta) EnforcerRuleException(org.apache.maven.enforcer.rule.api.EnforcerRuleException)

Example 23 with EnforcerRuleException

use of org.apache.maven.enforcer.rule.api.EnforcerRuleException in project semantic-versioning by jeluard.

the class AbstractEnforcerRule method compareJars.

private void compareJars(final EnforcerRuleHelper helper, final Version previous, final File previousJar, final Version current, final File currentJar) throws EnforcerRuleException {
    helper.getLog().info("Using <" + previousJar + "> as previous JAR");
    helper.getLog().info("Using <" + currentJar + "> as current JAR");
    try {
        final DiffCriteria diffCriteria = publicOnly ? new PublicDiffCriteria() : new SimpleDiffCriteria();
        final Comparer comparer = new Comparer(diffCriteria, previousJar, currentJar, extractFilters(this.includes), extractFilters(this.excludes));
        final Delta delta = comparer.diff();
        enforce(helper, delta, previous, current);
    } catch (IOException e) {
        throw new EnforcerRuleException("Exception while checking compatibility: " + e.toString(), e);
    }
}
Also used : PublicDiffCriteria(org.osjava.jardiff.PublicDiffCriteria) Delta(org.semver.Delta) Comparer(org.semver.Comparer) EnforcerRuleException(org.apache.maven.enforcer.rule.api.EnforcerRuleException) SimpleDiffCriteria(org.osjava.jardiff.SimpleDiffCriteria) IOException(java.io.IOException) SimpleDiffCriteria(org.osjava.jardiff.SimpleDiffCriteria) PublicDiffCriteria(org.osjava.jardiff.PublicDiffCriteria) DiffCriteria(org.osjava.jardiff.DiffCriteria)

Example 24 with EnforcerRuleException

use of org.apache.maven.enforcer.rule.api.EnforcerRuleException in project cloud-opensource-java by GoogleCloudPlatform.

the class LinkageCheckerRule method execute.

@Override
public void execute(@Nonnull EnforcerRuleHelper helper) throws EnforcerRuleException {
    logger = helper.getLog();
    try {
        MavenProject project = (MavenProject) helper.evaluate("${project}");
        MavenSession session = (MavenSession) helper.evaluate("${session}");
        MojoExecution execution = (MojoExecution) helper.evaluate("${mojoExecution}");
        RepositorySystemSession repositorySystemSession = session.getRepositorySession();
        ImmutableList<String> repositoryUrls = project.getRemoteProjectRepositories().stream().map(RemoteRepository::getUrl).collect(toImmutableList());
        DependencyGraphBuilder dependencyGraphBuilder = new DependencyGraphBuilder(repositoryUrls);
        classPathBuilder = new ClassPathBuilder(dependencyGraphBuilder);
        boolean readingDependencyManagementSection = dependencySection == DependencySection.DEPENDENCY_MANAGEMENT;
        if (readingDependencyManagementSection && (project.getDependencyManagement() == null || project.getDependencyManagement().getDependencies() == null || project.getDependencyManagement().getDependencies().isEmpty())) {
            logger.warn("The rule is set to read dependency management section but it is empty.");
        }
        String projectType = project.getArtifact().getType();
        if (readingDependencyManagementSection) {
            if (!"pom".equals(projectType)) {
                logger.warn("A BOM should have packaging pom");
                return;
            }
        } else {
            if (UNSUPPORTED_NONBOM_PACKAGING.contains(projectType)) {
                return;
            }
            if (!"verify".equals(execution.getLifecyclePhase())) {
                throw new EnforcerRuleException("To run the check on the compiled class files, the linkage checker enforcer rule" + " should be bound to the 'verify' phase. Current phase: " + execution.getLifecyclePhase());
            }
            if (project.getArtifact().getFile() == null) {
                // https://github.com/GoogleCloudPlatform/cloud-opensource-java/issues/850
                return;
            }
        }
        ClassPathResult classPathResult = readingDependencyManagementSection ? findBomClasspath(project, repositorySystemSession) : findProjectClasspath(project, repositorySystemSession, helper);
        ImmutableList<ClassPathEntry> classPath = classPathResult.getClassPath();
        if (classPath.isEmpty()) {
            logger.warn("Class path is empty.");
            return;
        }
        List<ClassPathEntry> entryPoints = entryPoints(project, classPath);
        try {
            // TODO LinkageChecker.create and LinkageChecker.findLinkageProblems
            // should not be two separate public methods since we always call
            // findLinkageProblems immediately after create.
            Path exclusionFile = this.exclusionFile == null ? null : Paths.get(this.exclusionFile);
            LinkageChecker linkageChecker = LinkageChecker.create(classPath, entryPoints, exclusionFile);
            ImmutableSet<LinkageProblem> linkageProblems = linkageChecker.findLinkageProblems();
            if (reportOnlyReachable) {
                ClassReferenceGraph classReferenceGraph = linkageChecker.getClassReferenceGraph();
                linkageProblems = linkageProblems.stream().filter(entry -> classReferenceGraph.isReachable(entry.getSourceClass().getBinaryName())).collect(toImmutableSet());
            }
            if (classPathResult != null) {
                LinkageProblemCauseAnnotator.annotate(classPathBuilder, classPathResult, linkageProblems);
            }
            // Count unique LinkageProblems by their symbols
            long errorCount = linkageProblems.stream().map(LinkageProblem::formatSymbolProblem).distinct().count();
            String foundError = reportOnlyReachable ? "reachable error" : "error";
            if (errorCount > 1) {
                foundError += "s";
            }
            if (errorCount > 0) {
                String message = String.format("Linkage Checker rule found %d %s:\n%s", errorCount, foundError, LinkageProblem.formatLinkageProblems(linkageProblems, classPathResult));
                if (getLevel() == WARN) {
                    logger.warn(message);
                } else {
                    logger.error(message);
                    logger.info("For the details of the linkage errors, see " + "https://github.com/GoogleCloudPlatform/cloud-opensource-java/wiki/Linkage-Checker-Messages");
                    throw new EnforcerRuleException("Failed while checking class path. See above error report.");
                }
            } else {
                // arguably shouldn't log anything on success
                logger.info("No " + foundError + " found");
            }
        } catch (IOException ex) {
            // Maven's "-e" flag does not work for EnforcerRuleException. Print stack trace here.
            logger.warn("Failed to run Linkage Checker:" + ex.getMessage(), ex);
            throw new EnforcerRuleException("Failed to run Linkage Checker", ex);
        }
    } catch (ExpressionEvaluationException ex) {
        throw new EnforcerRuleException("Unable to lookup an expression " + ex.getMessage(), ex);
    }
}
Also used : Path(java.nio.file.Path) DependencyPath(com.google.cloud.tools.opensource.dependencies.DependencyPath) AnnotatedClassPath(com.google.cloud.tools.opensource.classpath.AnnotatedClassPath) RepositorySystemSession(org.eclipse.aether.RepositorySystemSession) DefaultRepositorySystemSession(org.eclipse.aether.DefaultRepositorySystemSession) ExpressionEvaluationException(org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException) LinkageProblem(com.google.cloud.tools.opensource.classpath.LinkageProblem) EnforcerRuleException(org.apache.maven.enforcer.rule.api.EnforcerRuleException) ClassPathBuilder(com.google.cloud.tools.opensource.classpath.ClassPathBuilder) ClassPathResult(com.google.cloud.tools.opensource.classpath.ClassPathResult) IOException(java.io.IOException) ClassPathEntry(com.google.cloud.tools.opensource.classpath.ClassPathEntry) ClassReferenceGraph(com.google.cloud.tools.opensource.classpath.ClassReferenceGraph) MavenSession(org.apache.maven.execution.MavenSession) MavenProject(org.apache.maven.project.MavenProject) MojoExecution(org.apache.maven.plugin.MojoExecution) DependencyGraphBuilder(com.google.cloud.tools.opensource.dependencies.DependencyGraphBuilder) LinkageChecker(com.google.cloud.tools.opensource.classpath.LinkageChecker)

Example 25 with EnforcerRuleException

use of org.apache.maven.enforcer.rule.api.EnforcerRuleException in project xwiki-commons by xwiki.

the class ValidateDependencyVersion method validateDependencies.

/**
 * @param dependencies the list of dependencies to validate
 * @throws EnforcerRuleException if a dependency doesn't validate
 */
private void validateDependencies(List dependencies) throws EnforcerRuleException {
    for (Object object : dependencies) {
        Dependency dependency = (Dependency) object;
        for (VersionCheck versionCheck : this.checks) {
            // Note: the version will be null if defined in a parent.
            if (dependency.getVersion() != null && dependency.getGroupId().startsWith(versionCheck.getGroupIdPrefix())) {
                Pattern pattern = Pattern.compile(versionCheck.getAllowedVersionRegex());
                Matcher matcher = pattern.matcher(dependency.getVersion());
                if (!matcher.matches()) {
                    throw new EnforcerRuleException("Was expecting a dependency version matching [" + versionCheck.getAllowedVersionRegex() + "] but got instead [" + dependency.getVersion() + "] for " + dependency);
                }
            }
        }
    }
}
Also used : Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) EnforcerRuleException(org.apache.maven.enforcer.rule.api.EnforcerRuleException) Dependency(org.apache.maven.model.Dependency)

Aggregations

EnforcerRuleException (org.apache.maven.enforcer.rule.api.EnforcerRuleException)35 ExpressionEvaluationException (org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException)17 File (java.io.File)12 MavenProject (org.apache.maven.project.MavenProject)12 IOException (java.io.IOException)11 Artifact (org.apache.maven.artifact.Artifact)7 Log (org.apache.maven.plugin.logging.Log)6 ComponentLookupException (org.codehaus.plexus.component.repository.exception.ComponentLookupException)6 Path (java.nio.file.Path)4 Matcher (java.util.regex.Matcher)4 DependencyResolutionResult (org.apache.maven.project.DependencyResolutionResult)4 DependencyNode (org.eclipse.aether.graph.DependencyNode)4 AnnotatedClassPath (com.google.cloud.tools.opensource.classpath.AnnotatedClassPath)3 ClassPathEntry (com.google.cloud.tools.opensource.classpath.ClassPathEntry)3 ClassPathResult (com.google.cloud.tools.opensource.classpath.ClassPathResult)3 DependencyGraph (com.google.cloud.tools.opensource.dependencies.DependencyGraph)3 DependencyPath (com.google.cloud.tools.opensource.dependencies.DependencyPath)3 HashMap (java.util.HashMap)3 List (java.util.List)3 Map (java.util.Map)3