diff --git a/pom.xml b/pom.xml index 9f9d0782..5468ee4c 100644 --- a/pom.xml +++ b/pom.xml @@ -12,9 +12,7 @@ Extra Enforcer Rules - - Extra Enforcer Rules. These are extra rules for Apache Maven's Enforcer Plugin. - + Extra Enforcer Rules. These are extra rules for Apache Maven's Enforcer Plugin. https://www.mojohaus.org/extra-enforcer-rules/ 2011 @@ -27,13 +25,6 @@ - - scm:git:https://github.com/mojohaus/extra-enforcer-rules.git - scm:git:ssh://git@github.com/mojohaus/extra-enforcer-rules.git - https://github.com/mojohaus/extra-enforcer-rules/tree/master - HEAD - - Stephen Connolly @@ -58,6 +49,13 @@ + + scm:git:https://github.com/mojohaus/extra-enforcer-rules.git + scm:git:ssh://git@github.com/mojohaus/extra-enforcer-rules.git + HEAD + https://github.com/mojohaus/extra-enforcer-rules/tree/master + + 11 @@ -159,12 +157,12 @@ - - - org.apache.maven.plugins - maven-invoker-plugin - - + + + org.apache.maven.plugins + maven-invoker-plugin + + @@ -220,6 +218,10 @@ [11,) + + MagicNumber + + diff --git a/src/main/java/org/apache/maven/plugins/enforcer/AbstractMojoHausEnforcerRule.java b/src/main/java/org/apache/maven/plugins/enforcer/AbstractMojoHausEnforcerRule.java index 42f0b66e..73ea0097 100644 --- a/src/main/java/org/apache/maven/plugins/enforcer/AbstractMojoHausEnforcerRule.java +++ b/src/main/java/org/apache/maven/plugins/enforcer/AbstractMojoHausEnforcerRule.java @@ -22,19 +22,15 @@ import org.apache.maven.enforcer.rule.api.EnforcerLevel; import org.apache.maven.enforcer.rule.api.EnforcerRule2; -abstract class AbstractMojoHausEnforcerRule - implements EnforcerRule2 -{ +abstract class AbstractMojoHausEnforcerRule implements EnforcerRule2 { private EnforcerLevel level = EnforcerLevel.ERROR; @Override - public EnforcerLevel getLevel() - { + public EnforcerLevel getLevel() { return level; } - public void setLevel( EnforcerLevel level ) - { + public void setLevel(EnforcerLevel level) { this.level = level; } } diff --git a/src/main/java/org/apache/maven/plugins/enforcer/AbstractRequireRoles.java b/src/main/java/org/apache/maven/plugins/enforcer/AbstractRequireRoles.java index 2c619f34..2581bbfa 100644 --- a/src/main/java/org/apache/maven/plugins/enforcer/AbstractRequireRoles.java +++ b/src/main/java/org/apache/maven/plugins/enforcer/AbstractRequireRoles.java @@ -40,8 +40,7 @@ * @author Mirko Friedenhagen * @since 1.0-alpha-3 */ -abstract class AbstractRequireRoles extends AbstractMojoHausEnforcerRule -{ +abstract class AbstractRequireRoles extends AbstractMojoHausEnforcerRule { /** * Specify the required roles as comma separated list. */ @@ -54,51 +53,45 @@ abstract class AbstractRequireRoles extends AbstractMojoH /** * Execute the rule. - * + * * @param helper the helper * @throws EnforcerRuleException the enforcer rule exception */ - public void execute( EnforcerRuleHelper helper ) - throws EnforcerRuleException - { - MavenProject mavenProject = getMavenProject( helper ); + public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException { + MavenProject mavenProject = getMavenProject(helper); // Trying to prevent side-effects with unmodifiable sets (already got burned) - final Set requiredRolesSet = Collections.unmodifiableSet( getRolesFromString( requiredRoles ) ); - final Set rolesFromProject = Collections.unmodifiableSet(getRolesFromProject( mavenProject )); + final Set requiredRolesSet = Collections.unmodifiableSet(getRolesFromString(requiredRoles)); + final Set rolesFromProject = Collections.unmodifiableSet(getRolesFromProject(mavenProject)); - checkRequiredRoles( requiredRolesSet, rolesFromProject ); - checkValidRoles( requiredRolesSet, rolesFromProject ); + checkRequiredRoles(requiredRolesSet, rolesFromProject); + checkValidRoles(requiredRolesSet, rolesFromProject); } - private void checkRequiredRoles( final Set requiredRolesSet, final Set rolesFromProject ) - throws EnforcerRuleException - { + private void checkRequiredRoles(final Set requiredRolesSet, final Set rolesFromProject) + throws EnforcerRuleException { final Set copyOfRequiredRolesSet = new LinkedHashSet<>(requiredRolesSet); - copyOfRequiredRolesSet.removeAll( rolesFromProject ); - if ( copyOfRequiredRolesSet.size() > 0 ) - { + copyOfRequiredRolesSet.removeAll(rolesFromProject); + if (copyOfRequiredRolesSet.size() > 0) { final String message = - String.format( "Found no %s representing role(s) '%s'", getRoleName(), copyOfRequiredRolesSet ); - throw new EnforcerRuleException( message ); + String.format("Found no %s representing role(s) '%s'", getRoleName(), copyOfRequiredRolesSet); + throw new EnforcerRuleException(message); } } - private void checkValidRoles( final Set requiredRolesSet, final Set rolesFromProject ) - throws EnforcerRuleException - { + private void checkValidRoles(final Set requiredRolesSet, final Set rolesFromProject) + throws EnforcerRuleException { final Set copyOfRolesFromProject = new LinkedHashSet<>(rolesFromProject); - final Set allowedRoles = getRolesFromString( validRoles ); - if ( !allowedRoles.contains( "*" ) ) - { - allowedRoles.addAll( requiredRolesSet ); + final Set allowedRoles = getRolesFromString(validRoles); + if (!allowedRoles.contains("*")) { + allowedRoles.addAll(requiredRolesSet); // results in invalid roles - copyOfRolesFromProject.removeAll( allowedRoles ); - if ( copyOfRolesFromProject.size() > 0 ) - { - final String message = String.format( "Found invalid %s role(s) '%s'", getRoleName(), copyOfRolesFromProject ); - throw new EnforcerRuleException( message ); + copyOfRolesFromProject.removeAll(allowedRoles); + if (copyOfRolesFromProject.size() > 0) { + final String message = + String.format("Found invalid %s role(s) '%s'", getRoleName(), copyOfRolesFromProject); + throw new EnforcerRuleException(message); } } } @@ -109,19 +102,16 @@ private void checkValidRoles( final Set requiredRolesSet, final Set getRolesFromProject( MavenProject mavenProject ) - { + @SuppressWarnings("unchecked") + final Set getRolesFromProject(MavenProject mavenProject) { final Set result = new HashSet<>(); - for ( final T roleFromPom : getRoles( mavenProject ) ) - { + for (final T roleFromPom : getRoles(mavenProject)) { List roles = roleFromPom.getRoles(); result.addAll(roles); } return result; } - /** * Returns the rolename. * @@ -135,7 +125,7 @@ final Set getRolesFromProject( MavenProject mavenProject ) * @param mavenProject * @return the list of {@link Contributor}s or {@link Developer}s. */ - protected abstract List getRoles( final MavenProject mavenProject ); + protected abstract List getRoles(MavenProject mavenProject); /** * Returns the set of required roles from the property. @@ -143,18 +133,15 @@ final Set getRolesFromProject( MavenProject mavenProject ) * @param csRoles comma-separated roles to be split * @return */ - Set getRolesFromString( final String csRoles ) - { - return splitCsvToSet( csRoles ); + Set getRolesFromString(final String csRoles) { + return splitCsvToSet(csRoles); } - static Set splitCsvToSet( final String csv ) - { - final String [] splitValues = StringUtils.split( csv, "," ); + static Set splitCsvToSet(final String csv) { + final String[] splitValues = StringUtils.split(csv, ","); final Set result = new HashSet<>(); - for ( String value : splitValues ) - { - result.add( value.trim() ); + for (String value : splitValues) { + result.add(value.trim()); } return result; } @@ -167,15 +154,11 @@ static Set splitCsvToSet( final String csv ) * * @throws EnforcerRuleException */ - MavenProject getMavenProject( EnforcerRuleHelper helper ) throws EnforcerRuleException - { - try - { - return ( MavenProject ) helper.evaluate( "${project}" ); - } - catch ( ExpressionEvaluationException eee ) - { - throw new EnforcerRuleException( "Unable to get project.", eee ); + MavenProject getMavenProject(EnforcerRuleHelper helper) throws EnforcerRuleException { + try { + return (MavenProject) helper.evaluate("${project}"); + } catch (ExpressionEvaluationException eee) { + throw new EnforcerRuleException("Unable to get project.", eee); } } @@ -183,40 +166,34 @@ MavenProject getMavenProject( EnforcerRuleHelper helper ) throws EnforcerRuleExc /** * @param requiredRoles the requiredRoles to set. */ - void setRequiredRoles( String requiredRoles ) - { + void setRequiredRoles(String requiredRoles) { this.requiredRoles = requiredRoles; } - - void setValidRoles( String validRoles ) - { + + void setValidRoles(String validRoles) { this.validRoles = validRoles; } - - //********************* - + // ********************* + /** * {@inheritDoc} */ - public String getCacheId() - { + public String getCacheId() { return "0"; } /** * {@inheritDoc} */ - public boolean isCacheable() - { + public boolean isCacheable() { return false; } /** * {@inheritDoc} */ - public boolean isResultValid( EnforcerRule cachedRule ) - { + public boolean isResultValid(EnforcerRule cachedRule) { return false; } -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/maven/plugins/enforcer/AbstractResolveDependencies.java b/src/main/java/org/apache/maven/plugins/enforcer/AbstractResolveDependencies.java index a267334d..84bff26d 100644 --- a/src/main/java/org/apache/maven/plugins/enforcer/AbstractResolveDependencies.java +++ b/src/main/java/org/apache/maven/plugins/enforcer/AbstractResolveDependencies.java @@ -1,272 +1,234 @@ -package org.apache.maven.plugins.enforcer; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.regex.Pattern; - -import org.apache.maven.RepositoryUtils; -import org.apache.maven.artifact.Artifact; -import org.apache.maven.enforcer.rule.api.EnforcerRule; -import org.apache.maven.enforcer.rule.api.EnforcerRuleException; -import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.plugin.logging.Log; -import org.apache.maven.project.DefaultProjectBuildingRequest; -import org.apache.maven.project.ProjectBuildingRequest; -import org.apache.maven.shared.dependency.graph.DependencyGraphBuilder; -import org.apache.maven.shared.dependency.graph.DependencyGraphBuilderException; -import org.apache.maven.shared.dependency.graph.DependencyNode; -import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; -import org.codehaus.plexus.component.repository.exception.ComponentLookupException; -import org.eclipse.aether.RepositorySystem; -import org.eclipse.aether.resolution.ArtifactRequest; -import org.eclipse.aether.resolution.ArtifactResolutionException; -import org.eclipse.aether.resolution.ArtifactResult; - -/** - * Abstract rule for when the content of the artifacts matters. - * - * @author Robert Scholte - * - */ -public abstract class AbstractResolveDependencies extends AbstractMojoHausEnforcerRule -{ - - private DependencyGraphBuilder graphBuilder; - - private MavenSession session; - private RepositorySystem repositorySystem; - - private EnforcerRuleHelper helper; - - public void execute( EnforcerRuleHelper helper ) - throws EnforcerRuleException - { - this.helper = helper; - - // Get components - try - { - repositorySystem = helper.getComponent( RepositorySystem.class ); - graphBuilder = helper.getComponent( DependencyGraphBuilder.class ); - } - catch ( ComponentLookupException e ) - { - throw new EnforcerRuleException( "Unable to lookup DependencyTreeBuilder: ", e ); - } - - // Resolve expressions - try - { - session = (MavenSession) helper.evaluate( "${session}" ); - } - catch ( ExpressionEvaluationException e ) - { - throw new EnforcerRuleException( "Unable to lookup an expression " + e.getLocalizedMessage(), e ); - } - - ProjectBuildingRequest buildingRequest = - new DefaultProjectBuildingRequest( session.getProjectBuildingRequest() ); - buildingRequest.setProject( session.getCurrentProject() ); - - handleArtifacts( getDependenciesToCheck( buildingRequest ) ); - } - - protected abstract void handleArtifacts( Set artifacts ) throws EnforcerRuleException; - - protected boolean isSearchTransitive() - { - return true; - } - - private Set getDependenciesToCheck( ProjectBuildingRequest buildingRequest ) throws EnforcerRuleException - { - Set dependencies = null; - try - { - DependencyNode node = graphBuilder.buildDependencyGraph( buildingRequest ,null ); - - if( isSearchTransitive() ) - { - dependencies = getAllDescendants( node ); - } - else if ( node.getChildren() != null ) - { - dependencies = new HashSet<>(); - for( DependencyNode depNode : node.getChildren() ) - { - dependencies.add( depNode.getArtifact() ); - } - } - } - catch ( DependencyGraphBuilderException e ) - { - throw new EnforcerRuleException( e.getMessage(), e ); - } - return dependencies; - } - - private Set getAllDescendants( DependencyNode node ) - { - Set children = null; - if( node.getChildren() != null ) - { - children = new HashSet<>(); - for( DependencyNode depNode : node.getChildren() ) - { - try - { - Artifact artifact = depNode.getArtifact(); - resolveArtifact( artifact ); - children.add( artifact ); - - Set subNodes = getAllDescendants( depNode ); - - if( subNodes != null ) - { - children.addAll( subNodes ); - } - } - catch ( ArtifactResolutionException e ) - { - getLog().warn( e.getMessage() ); - } - } - } - return children; - } - - private void resolveArtifact( Artifact artifact ) throws ArtifactResolutionException - { - ArtifactRequest request = new ArtifactRequest(); - request.setRepositories( session.getCurrentProject().getRemoteProjectRepositories() ); - request.setArtifact( RepositoryUtils.toArtifact( artifact ) ); - - ArtifactResult artifactResult = repositorySystem.resolveArtifact( session.getRepositorySession(), request ); - - artifact.setFile( artifactResult.getArtifact().getFile() ); - artifact.setVersion( artifactResult.getArtifact().getVersion() ); - artifact.setResolved( true ); - } - - protected Log getLog() - { - return helper.getLog(); - } - - /** - * {@inheritDoc} - */ - public boolean isCacheable() - { - return false; - } - - /** - * {@inheritDoc} - */ - public boolean isResultValid( EnforcerRule enforcerRule ) - { - return false; - } - - /** - * {@inheritDoc} - */ - public String getCacheId() - { - return "Does not matter as not cacheable"; - } - - - /** - * Convert a wildcard into a regex. - * - * @param wildcard the wildcard to convert. - * @return the equivalent regex. - */ - protected static String asRegex(String wildcard) - { - StringBuilder result = new StringBuilder( wildcard.length() ); - result.append( '^' ); - for ( int index = 0; index < wildcard.length(); index++ ) - { - char character = wildcard.charAt( index ); - switch ( character ) - { - case '*': - result.append( ".*" ); - break; - case '?': - result.append( "." ); - break; - case '$': - case '(': - case ')': - case '.': - case '[': - case '\\': - case ']': - case '^': - case '{': - case '|': - case '}': - result.append( "\\" ); - default: - result.append( character ); - break; - } - } - result.append( "(\\.class)?" ); - result.append( '$' ); - return result.toString(); - } - - /** - * - */ - protected class IgnorableDependency - { - public Pattern groupId; - public Pattern artifactId; - public Pattern classifier; - public Pattern type; - public List ignores = new ArrayList<>(); - - public IgnorableDependency applyIgnoreClasses( String[] ignores, boolean indent ) - { - String prefix = indent ? " " : ""; - for ( String ignore : ignores ) - { - getLog().info( prefix + "Adding ignore: " + ignore ); - ignore = ignore.replace( '.', '/' ); - String pattern = asRegex( ignore ); - getLog().debug( prefix + "Ignore: " + ignore + " maps to regex " + pattern ); - this.ignores.add( Pattern.compile( pattern ) ); - } - return this; - } - - public boolean matchesArtifact( Artifact dup ) - { - return ( artifactId == null || artifactId.matcher( dup.getArtifactId() ).matches() ) - && ( groupId == null || groupId.matcher( dup.getGroupId() ).matches() ) - && ( classifier == null || classifier.matcher( dup.getClassifier() ).matches() ) - && ( type == null || type.matcher( dup.getType() ).matches() ); - } - - public boolean matches(String className) - { - for ( Pattern p : ignores ) - { - if ( p.matcher( className ).matches() ) - { - return true; - } - } - return false; - } - } -} +package org.apache.maven.plugins.enforcer; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.regex.Pattern; + +import org.apache.maven.RepositoryUtils; +import org.apache.maven.artifact.Artifact; +import org.apache.maven.enforcer.rule.api.EnforcerRule; +import org.apache.maven.enforcer.rule.api.EnforcerRuleException; +import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper; +import org.apache.maven.execution.MavenSession; +import org.apache.maven.plugin.logging.Log; +import org.apache.maven.project.DefaultProjectBuildingRequest; +import org.apache.maven.project.ProjectBuildingRequest; +import org.apache.maven.shared.dependency.graph.DependencyGraphBuilder; +import org.apache.maven.shared.dependency.graph.DependencyGraphBuilderException; +import org.apache.maven.shared.dependency.graph.DependencyNode; +import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; +import org.codehaus.plexus.component.repository.exception.ComponentLookupException; +import org.eclipse.aether.RepositorySystem; +import org.eclipse.aether.resolution.ArtifactRequest; +import org.eclipse.aether.resolution.ArtifactResolutionException; +import org.eclipse.aether.resolution.ArtifactResult; + +/** + * Abstract rule for when the content of the artifacts matters. + * + * @author Robert Scholte + * + */ +public abstract class AbstractResolveDependencies extends AbstractMojoHausEnforcerRule { + + private DependencyGraphBuilder graphBuilder; + + private MavenSession session; + private RepositorySystem repositorySystem; + + private EnforcerRuleHelper helper; + + public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException { + this.helper = helper; + + // Get components + try { + repositorySystem = helper.getComponent(RepositorySystem.class); + graphBuilder = helper.getComponent(DependencyGraphBuilder.class); + } catch (ComponentLookupException e) { + throw new EnforcerRuleException("Unable to lookup DependencyTreeBuilder: ", e); + } + + // Resolve expressions + try { + session = (MavenSession) helper.evaluate("${session}"); + } catch (ExpressionEvaluationException e) { + throw new EnforcerRuleException("Unable to lookup an expression " + e.getLocalizedMessage(), e); + } + + ProjectBuildingRequest buildingRequest = new DefaultProjectBuildingRequest(session.getProjectBuildingRequest()); + buildingRequest.setProject(session.getCurrentProject()); + + handleArtifacts(getDependenciesToCheck(buildingRequest)); + } + + protected abstract void handleArtifacts(Set artifacts) throws EnforcerRuleException; + + protected boolean isSearchTransitive() { + return true; + } + + private Set getDependenciesToCheck(ProjectBuildingRequest buildingRequest) throws EnforcerRuleException { + Set dependencies = null; + try { + DependencyNode node = graphBuilder.buildDependencyGraph(buildingRequest, null); + + if (isSearchTransitive()) { + dependencies = getAllDescendants(node); + } else if (node.getChildren() != null) { + dependencies = new HashSet<>(); + for (DependencyNode depNode : node.getChildren()) { + dependencies.add(depNode.getArtifact()); + } + } + } catch (DependencyGraphBuilderException e) { + throw new EnforcerRuleException(e.getMessage(), e); + } + return dependencies; + } + + private Set getAllDescendants(DependencyNode node) { + Set children = null; + if (node.getChildren() != null) { + children = new HashSet<>(); + for (DependencyNode depNode : node.getChildren()) { + try { + Artifact artifact = depNode.getArtifact(); + resolveArtifact(artifact); + children.add(artifact); + + Set subNodes = getAllDescendants(depNode); + + if (subNodes != null) { + children.addAll(subNodes); + } + } catch (ArtifactResolutionException e) { + getLog().warn(e.getMessage()); + } + } + } + return children; + } + + private void resolveArtifact(Artifact artifact) throws ArtifactResolutionException { + ArtifactRequest request = new ArtifactRequest(); + request.setRepositories(session.getCurrentProject().getRemoteProjectRepositories()); + request.setArtifact(RepositoryUtils.toArtifact(artifact)); + + ArtifactResult artifactResult = repositorySystem.resolveArtifact(session.getRepositorySession(), request); + + artifact.setFile(artifactResult.getArtifact().getFile()); + artifact.setVersion(artifactResult.getArtifact().getVersion()); + artifact.setResolved(true); + } + + protected Log getLog() { + return helper.getLog(); + } + + /** + * {@inheritDoc} + */ + public boolean isCacheable() { + return false; + } + + /** + * {@inheritDoc} + */ + public boolean isResultValid(EnforcerRule enforcerRule) { + return false; + } + + /** + * {@inheritDoc} + */ + public String getCacheId() { + return "Does not matter as not cacheable"; + } + + /** + * Convert a wildcard into a regex. + * + * @param wildcard the wildcard to convert. + * @return the equivalent regex. + */ + protected static String asRegex(String wildcard) { + StringBuilder result = new StringBuilder(wildcard.length()); + result.append('^'); + for (int index = 0; index < wildcard.length(); index++) { + char character = wildcard.charAt(index); + switch (character) { + case '*': + result.append(".*"); + break; + case '?': + result.append("."); + break; + case '$': + case '(': + case ')': + case '.': + case '[': + case '\\': + case ']': + case '^': + case '{': + case '|': + case '}': + result.append("\\"); + default: + result.append(character); + break; + } + } + result.append("(\\.class)?"); + result.append('$'); + return result.toString(); + } + + /** + * + */ + @SuppressWarnings("checkstyle:VisibilityModifier") + protected class IgnorableDependency { + // TODO should be private, fix and remove SuppressWarnings + public Pattern groupId; + public Pattern artifactId; + public Pattern classifier; + public Pattern type; + public List ignores = new ArrayList<>(); + + public IgnorableDependency applyIgnoreClasses(String[] ignores, boolean indent) { + String prefix = indent ? " " : ""; + for (String ignore : ignores) { + getLog().info(prefix + "Adding ignore: " + ignore); + ignore = ignore.replace('.', '/'); + String pattern = asRegex(ignore); + getLog().debug(prefix + "Ignore: " + ignore + " maps to regex " + pattern); + this.ignores.add(Pattern.compile(pattern)); + } + return this; + } + + public boolean matchesArtifact(Artifact dup) { + return (artifactId == null + || artifactId.matcher(dup.getArtifactId()).matches()) + && (groupId == null || groupId.matcher(dup.getGroupId()).matches()) + && (classifier == null + || classifier.matcher(dup.getClassifier()).matches()) + && (type == null || type.matcher(dup.getType()).matches()); + } + + public boolean matches(String className) { + for (Pattern p : ignores) { + if (p.matcher(className).matches()) { + return true; + } + } + return false; + } + } +} diff --git a/src/main/java/org/apache/maven/plugins/enforcer/BanCircularDependencies.java b/src/main/java/org/apache/maven/plugins/enforcer/BanCircularDependencies.java index 3c7d4c39..9d83058f 100644 --- a/src/main/java/org/apache/maven/plugins/enforcer/BanCircularDependencies.java +++ b/src/main/java/org/apache/maven/plugins/enforcer/BanCircularDependencies.java @@ -39,133 +39,107 @@ /** * Bans circular dependencies on the classpath. - * + * * @since 1.0-alpha-4 */ -public class BanCircularDependencies - extends AbstractMojoHausEnforcerRule -{ - +public class BanCircularDependencies extends AbstractMojoHausEnforcerRule { + private transient DependencyGraphBuilder graphBuilder; - + private String message; - + /** * {@inheritDoc} */ - public void execute( EnforcerRuleHelper helper ) - throws EnforcerRuleException - { + public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException { Log log = helper.getLog(); - try - { - graphBuilder = helper.getComponent( DependencyGraphBuilder.class ); - } - catch ( ComponentLookupException e ) - { - throw new EnforcerRuleException( "Unable to lookup DependencyGraphBuilder: ", e ); + try { + graphBuilder = helper.getComponent(DependencyGraphBuilder.class); + } catch (ComponentLookupException e) { + throw new EnforcerRuleException("Unable to lookup DependencyGraphBuilder: ", e); } - try - { - MavenProject project = (MavenProject) helper.evaluate( "${project}" ); - MavenSession session = (MavenSession) helper.evaluate( "${session}" ); + try { + MavenProject project = (MavenProject) helper.evaluate("${project}"); + MavenSession session = (MavenSession) helper.evaluate("${session}"); ProjectBuildingRequest buildingRequest = - new DefaultProjectBuildingRequest( session.getProjectBuildingRequest() ); - buildingRequest.setProject( project ); - - Set artifacts = getDependenciesToCheck( buildingRequest ); - if ( artifacts != null ) - { - for ( Artifact artifact : artifacts ) - { - log.debug( "groupId: " + artifact.getGroupId() + project.getGroupId() ); - if ( artifact.getGroupId().equals( project.getGroupId() ) ) - { - log.debug( "artifactId: " + artifact.getArtifactId() + " " + project.getArtifactId() ); - if ( artifact.getArtifactId().equals( project.getArtifactId() ) ) - { - throw new EnforcerRuleException( getErrorMessage() + "\n " + artifact.getGroupId() - + ":" + artifact.getArtifactId() + "\n " ); + new DefaultProjectBuildingRequest(session.getProjectBuildingRequest()); + buildingRequest.setProject(project); + + Set artifacts = getDependenciesToCheck(buildingRequest); + if (artifacts != null) { + for (Artifact artifact : artifacts) { + log.debug("groupId: " + artifact.getGroupId() + project.getGroupId()); + if (artifact.getGroupId().equals(project.getGroupId())) { + log.debug("artifactId: " + artifact.getArtifactId() + " " + project.getArtifactId()); + if (artifact.getArtifactId().equals(project.getArtifactId())) { + throw new EnforcerRuleException(getErrorMessage() + "\n " + artifact.getGroupId() + ":" + + artifact.getArtifactId() + "\n "); } } } } - } - catch ( ExpressionEvaluationException e ) - { - log.error( "Error checking for circular dependencies", e ); + } catch (ExpressionEvaluationException e) { + log.error("Error checking for circular dependencies", e); e.printStackTrace(); } } - protected Set getDependenciesToCheck( ProjectBuildingRequest buildingRequest ) - { + protected Set getDependenciesToCheck(ProjectBuildingRequest buildingRequest) { Set dependencies; - try - { - DependencyNode node = graphBuilder.buildDependencyGraph( buildingRequest, null ); - dependencies = getAllDescendants( node ); - } - catch ( DependencyGraphBuilderException e ) - { + try { + DependencyNode node = graphBuilder.buildDependencyGraph(buildingRequest, null); + dependencies = getAllDescendants(node); + } catch (DependencyGraphBuilderException e) { // otherwise we need to change the signature of this protected method - throw new RuntimeException( e ); + throw new RuntimeException(e); } return dependencies; } - private Set getAllDescendants( DependencyNode node ) - { + private Set getAllDescendants(DependencyNode node) { Set children = null; - if ( node.getChildren() != null ) - { + if (node.getChildren() != null) { children = new HashSet<>(); - for ( DependencyNode depNode : node.getChildren() ) - { - children.add( depNode.getArtifact() ); - Set subNodes = getAllDescendants( depNode ); - if ( subNodes != null ) - { - children.addAll( subNodes ); + for (DependencyNode depNode : node.getChildren()) { + children.add(depNode.getArtifact()); + Set subNodes = getAllDescendants(depNode); + if (subNodes != null) { + children.addAll(subNodes); } } } return children; } - - private String getErrorMessage() - { - if ( message == null ) + private String getErrorMessage() { + if (message == null) { return "Circular Dependency found. Your project's groupId:artifactId combination " - + "must not exist in the list of direct or transitive dependencies."; + + "must not exist in the list of direct or transitive dependencies."; + } return message; } /** * {@inheritDoc} */ - public boolean isCacheable() - { + public boolean isCacheable() { return false; } /** * {@inheritDoc} */ - public boolean isResultValid( EnforcerRule enforcerRule ) - { + public boolean isResultValid(EnforcerRule enforcerRule) { return false; } /** * {@inheritDoc} */ - public String getCacheId() - { + public String getCacheId() { return "Does not matter as not cacheable"; } -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/maven/plugins/enforcer/BanDuplicateClasses.java b/src/main/java/org/apache/maven/plugins/enforcer/BanDuplicateClasses.java index a527e8e7..5ae78e47 100644 --- a/src/main/java/org/apache/maven/plugins/enforcer/BanDuplicateClasses.java +++ b/src/main/java/org/apache/maven/plugins/enforcer/BanDuplicateClasses.java @@ -44,22 +44,20 @@ /** * Bans duplicate classes on the classpath. */ -public class BanDuplicateClasses - extends AbstractResolveDependencies -{ +public class BanDuplicateClasses extends AbstractResolveDependencies { /** * Default ignores which are needed for JDK 9, cause in JDK 9 and above the module-info.class will be * duplicated in any jar file. Furthermore in use cases for multi release jars the module-info.class is * also contained several times. */ - private static final String[] DEFAULT_CLASSES_IGNORES = { "module-info", "META-INF/versions/*/module-info" }; + private static final String[] DEFAULT_CLASSES_IGNORES = {"module-info", "META-INF/versions/*/module-info"}; /** * The failure message */ private String message; - + /** * List of classes to ignore. Wildcard at the end accepted */ @@ -75,7 +73,7 @@ public class BanDuplicateClasses * List of dependencies for which you want to ignore specific classes. */ private List dependencies; - + /** * Only verify dependencies with one of these scopes */ @@ -88,191 +86,163 @@ public class BanDuplicateClasses private boolean ignoreWhenIdentical; @Override - protected void handleArtifacts( Set artifacts ) throws EnforcerRuleException - { + protected void handleArtifacts(Set artifacts) throws EnforcerRuleException { List ignorableDependencies = new ArrayList<>(); IgnorableDependency ignoreableClasses = new IgnorableDependency(); - ignoreableClasses.applyIgnoreClasses( DEFAULT_CLASSES_IGNORES, false ); - if ( ignoreClasses != null ) - { - ignoreableClasses.applyIgnoreClasses( ignoreClasses, false ); + ignoreableClasses.applyIgnoreClasses(DEFAULT_CLASSES_IGNORES, false); + if (ignoreClasses != null) { + ignoreableClasses.applyIgnoreClasses(ignoreClasses, false); } - ignorableDependencies.add( ignoreableClasses ); + ignorableDependencies.add(ignoreableClasses); - if ( dependencies != null ) - { - for ( Dependency dependency : dependencies ) - { - getLog().info( "Adding ignorable dependency: " + dependency ); + if (dependencies != null) { + for (Dependency dependency : dependencies) { + getLog().info("Adding ignorable dependency: " + dependency); IgnorableDependency ignorableDependency = new IgnorableDependency(); - if ( dependency.getGroupId() != null ) - { - ignorableDependency.groupId = Pattern.compile( asRegex( dependency.getGroupId() ) ); + if (dependency.getGroupId() != null) { + ignorableDependency.groupId = Pattern.compile(asRegex(dependency.getGroupId())); } - if ( dependency.getArtifactId() != null ) - { - ignorableDependency.artifactId = Pattern.compile( asRegex( dependency.getArtifactId() ) ); + if (dependency.getArtifactId() != null) { + ignorableDependency.artifactId = Pattern.compile(asRegex(dependency.getArtifactId())); } - if ( dependency.getType() != null ) - { - ignorableDependency.type = Pattern.compile( asRegex( dependency.getType() ) ); + if (dependency.getType() != null) { + ignorableDependency.type = Pattern.compile(asRegex(dependency.getType())); } - if ( dependency.getClassifier() != null ) - { - ignorableDependency.classifier = Pattern.compile( asRegex( dependency.getClassifier() ) ); + if (dependency.getClassifier() != null) { + ignorableDependency.classifier = Pattern.compile(asRegex(dependency.getClassifier())); } - ignorableDependency.applyIgnoreClasses( dependency.getIgnoreClasses(), true ); - ignorableDependencies.add( ignorableDependency ); + ignorableDependency.applyIgnoreClasses(dependency.getIgnoreClasses(), true); + ignorableDependencies.add(ignorableDependency); } } Map classesSeen = new HashMap<>(); Set duplicateClassNames = new HashSet<>(); - for ( Artifact o : artifacts ) - { - if( scopes != null && !scopes.contains( o.getScope() ) ) - { - if( getLog().isDebugEnabled() ) - { - getLog().debug( "Skipping " + o + " due to scope" ); + for (Artifact o : artifacts) { + if (scopes != null && !scopes.contains(o.getScope())) { + if (getLog().isDebugEnabled()) { + getLog().debug("Skipping " + o + " due to scope"); } continue; } File file = o.getFile(); - getLog().debug( "Searching for duplicate classes in " + file ); - if ( file == null || !file.exists() ) - { - getLog().warn( "Could not find " + o + " at " + file ); - } - else if ( file.isDirectory() ) - { - try - { - for ( String name : FileUtils.getFileNames( file, null, null, false ) ) - { - getLog().debug( " " + name ); - checkAndAddName( o, name, () -> Files.newInputStream( file.toPath().resolve( name ) ), - classesSeen, duplicateClassNames, ignorableDependencies ); + getLog().debug("Searching for duplicate classes in " + file); + if (file == null || !file.exists()) { + getLog().warn("Could not find " + o + " at " + file); + } else if (file.isDirectory()) { + try { + for (String name : FileUtils.getFileNames(file, null, null, false)) { + getLog().debug(" " + name); + checkAndAddName( + o, + name, + () -> Files.newInputStream(file.toPath().resolve(name)), + classesSeen, + duplicateClassNames, + ignorableDependencies); } - } - catch ( IOException e ) - { + } catch (IOException e) { throw new EnforcerRuleException( - "Unable to process dependency " + o + " due to " + e.getLocalizedMessage(), e ); + "Unable to process dependency " + o + " due to " + e.getLocalizedMessage(), e); } - } - else if ( isJarFile( o ) ) - { - try - { - //@todo use UnArchiver as defined per type - try ( JarFile jar = new JarFile( file ) ) - { - for ( JarEntry entry : Collections.list( jar.entries() ) ) - { + } else if (isJarFile(o)) { + try { + // @todo use UnArchiver as defined per type + try (JarFile jar = new JarFile(file)) { + for (JarEntry entry : Collections.list(jar.entries())) { String fileName = entry.getName(); - checkAndAddName( o, fileName, () -> jar.getInputStream( entry ), - classesSeen, duplicateClassNames, ignorableDependencies ); + checkAndAddName( + o, + fileName, + () -> jar.getInputStream(entry), + classesSeen, + duplicateClassNames, + ignorableDependencies); } } - } - catch ( IOException e ) - { + } catch (IOException e) { throw new EnforcerRuleException( - "Unable to process dependency " + o + " due to " + e.getLocalizedMessage(), e ); + "Unable to process dependency " + o + " due to " + e.getLocalizedMessage(), e); } } } - if ( !duplicateClassNames.isEmpty() ) - { + if (!duplicateClassNames.isEmpty()) { Map, List> inverted = new HashMap<>(); - for ( String className : duplicateClassNames ) - { - ClassesWithSameName classesWithSameName = classesSeen.get( className ); + for (String className : duplicateClassNames) { + ClassesWithSameName classesWithSameName = classesSeen.get(className); Set artifactsOfDuplicateClass = classesWithSameName.getAllArtifactsThisClassWasFoundIn(); - List s = inverted.get( artifactsOfDuplicateClass ); - if ( s == null ) - { + List s = inverted.get(artifactsOfDuplicateClass); + if (s == null) { s = new ArrayList<>(); } - s.add( classesWithSameName.toOutputString( ignoreWhenIdentical ) ); - inverted.put( artifactsOfDuplicateClass, s ); + s.add(classesWithSameName.toOutputString(ignoreWhenIdentical)); + inverted.put(artifactsOfDuplicateClass, s); } - StringBuilder buf = new StringBuilder( message == null ? "Duplicate classes found:" : message ); - buf.append( '\n' ); - for ( Map.Entry, List> entry : inverted.entrySet() ) - { - buf.append( "\n Found in:" ); - for ( Artifact a : entry.getKey() ) - { - buf.append( "\n " ); - buf.append( a ); + StringBuilder buf = new StringBuilder(message == null ? "Duplicate classes found:" : message); + buf.append('\n'); + for (Map.Entry, List> entry : inverted.entrySet()) { + buf.append("\n Found in:"); + for (Artifact a : entry.getKey()) { + buf.append("\n "); + buf.append(a); } - buf.append( "\n Duplicate classes:" ); - for ( String classNameWithDuplicationInfo : entry.getValue() ) - { - buf.append( "\n " ); - buf.append( classNameWithDuplicationInfo ); + buf.append("\n Duplicate classes:"); + for (String classNameWithDuplicationInfo : entry.getValue()) { + buf.append("\n "); + buf.append(classNameWithDuplicationInfo); } - buf.append( '\n' ); + buf.append('\n'); } - throw new EnforcerRuleException( buf.toString() ); + throw new EnforcerRuleException(buf.toString()); } - } - private void checkAndAddName( Artifact artifact, String pathToClassFile, InputStreamSupplier inputStreamSupplier, Map classesSeen, Set duplicateClasses, - Collection ignores ) - throws EnforcerRuleException, IOException - { - if ( !pathToClassFile.endsWith( ".class" ) ) - { + private void checkAndAddName( + Artifact artifact, + String pathToClassFile, + InputStreamSupplier inputStreamSupplier, + Map classesSeen, + Set duplicateClasses, + Collection ignores) + throws EnforcerRuleException, IOException { + if (!pathToClassFile.endsWith(".class")) { return; } - for ( IgnorableDependency c : ignores ) - { - if ( c.matchesArtifact( artifact ) && c.matches( pathToClassFile ) ) - { - if ( classesSeen.containsKey( pathToClassFile ) ) - { - getLog().debug( "Ignoring excluded class " + pathToClassFile ); + for (IgnorableDependency c : ignores) { + if (c.matchesArtifact(artifact) && c.matches(pathToClassFile)) { + if (classesSeen.containsKey(pathToClassFile)) { + getLog().debug("Ignoring excluded class " + pathToClassFile); } return; } } - ClassesWithSameName classesWithSameName = classesSeen.get( pathToClassFile ); - boolean isFirstTimeSeeingThisClass = ( classesWithSameName == null ); + ClassesWithSameName classesWithSameName = classesSeen.get(pathToClassFile); + boolean isFirstTimeSeeingThisClass = (classesWithSameName == null); - ClassFile classFile = new ClassFile( pathToClassFile, artifact, inputStreamSupplier ); + ClassFile classFile = new ClassFile(pathToClassFile, artifact, inputStreamSupplier); - if ( isFirstTimeSeeingThisClass ) - { - classesSeen.put( pathToClassFile, new ClassesWithSameName( getLog(), classFile ) ); + if (isFirstTimeSeeingThisClass) { + classesSeen.put(pathToClassFile, new ClassesWithSameName(getLog(), classFile)); return; } - classesWithSameName.add( classFile ); + classesWithSameName.add(classFile); - if ( !classesWithSameName.hasDuplicates( ignoreWhenIdentical ) ) - { + if (!classesWithSameName.hasDuplicates(ignoreWhenIdentical)) { return; } - if ( findAllDuplicates ) - { - duplicateClasses.add( pathToClassFile ); - } - else - { + if (findAllDuplicates) { + duplicateClasses.add(pathToClassFile); + } else { Artifact previousArtifact = classesWithSameName.previous().getArtifactThisClassWasFoundIn(); - String buf = ( message == null ? "Duplicate class found:" : message ) + '\n' + String buf = (message == null ? "Duplicate class found:" : message) + '\n' + "\n Found in:" + "\n " + previousArtifact @@ -283,7 +253,7 @@ private void checkAndAddName( Artifact artifact, String pathToClassFile, InputSt + pathToClassFile + '\n' + "There may be others but was set to false, so failing fast"; - throw new EnforcerRuleException( buf ); + throw new EnforcerRuleException(buf); } } } diff --git a/src/main/java/org/apache/maven/plugins/enforcer/ClassFile.java b/src/main/java/org/apache/maven/plugins/enforcer/ClassFile.java index 18ca1e49..bb6ec8e8 100644 --- a/src/main/java/org/apache/maven/plugins/enforcer/ClassFile.java +++ b/src/main/java/org/apache/maven/plugins/enforcer/ClassFile.java @@ -43,10 +43,10 @@ * of the directory/jar is not included in the class file path. Rather, * it's included in the Artifact. See {@link Artifact#getFile()} */ -public class ClassFile -{ +public class ClassFile { /** the path to the .class file. Example: org/apache/maven/Stuff.class */ private final String classFilePath; + private final Artifact artifactThisClassWasFoundIn; private String hash; @@ -56,35 +56,31 @@ public class ClassFile * @param artifactThisClassWasFoundIn the maven artifact the class appeared in (example: a jar file) * @param inputStreamSupplier a supplier for class content input stream */ - public ClassFile( String classFilePath, Artifact artifactThisClassWasFoundIn, InputStreamSupplier inputStreamSupplier ) - throws IOException - { + public ClassFile( + String classFilePath, Artifact artifactThisClassWasFoundIn, InputStreamSupplier inputStreamSupplier) + throws IOException { this.classFilePath = classFilePath; this.artifactThisClassWasFoundIn = artifactThisClassWasFoundIn; this.hash = computeHash(inputStreamSupplier); } - private String computeHash( InputStreamSupplier inputStreamSupplier ) throws IOException - { - try (InputStream inputStream = inputStreamSupplier.get()) - { - return DigestUtils.md5Hex( inputStream ); + private String computeHash(InputStreamSupplier inputStreamSupplier) throws IOException { + try (InputStream inputStream = inputStreamSupplier.get()) { + return DigestUtils.md5Hex(inputStream); } } /** * @return the path to the .class file. Example: org/apache/maven/Stuff.class */ - public String getClassFilePath() - { + public String getClassFilePath() { return classFilePath; } /** * @return the maven artifact the class appeared in (example: a jar file) */ - public Artifact getArtifactThisClassWasFoundIn() - { + public Artifact getArtifactThisClassWasFoundIn() { return artifactThisClassWasFoundIn; } @@ -92,9 +88,7 @@ public Artifact getArtifactThisClassWasFoundIn() * @return a hash or checksum of the binary file. If two files have the same hash * then they are the same binary file. */ - public String getHash() - { + public String getHash() { return hash; } - } diff --git a/src/main/java/org/apache/maven/plugins/enforcer/ClassesWithSameName.java b/src/main/java/org/apache/maven/plugins/enforcer/ClassesWithSameName.java index 5f5dc924..c7456b4d 100644 --- a/src/main/java/org/apache/maven/plugins/enforcer/ClassesWithSameName.java +++ b/src/main/java/org/apache/maven/plugins/enforcer/ClassesWithSameName.java @@ -44,11 +44,11 @@ * you'd choose the maven way (mockito-core) or the convenient-for-non-maven-users * way (mockito-all) but not both. */ -public class ClassesWithSameName -{ +public class ClassesWithSameName { private final Log log; /** the path to the .class file. Example: org/apache/maven/Stuff.class */ private final String classFilePath; + private final List list = new ArrayList<>(); /** @@ -57,16 +57,14 @@ public class ClassesWithSameName * next one lets us require at least one at compile time (instead of runtime). * @param additionalClassFiles (optional) additional class files */ - public ClassesWithSameName( Log log, ClassFile initialClassFile, ClassFile... additionalClassFiles ) - { + public ClassesWithSameName(Log log, ClassFile initialClassFile, ClassFile... additionalClassFiles) { this.log = log; classFilePath = initialClassFile.getClassFilePath(); - list.add( initialClassFile ); + list.add(initialClassFile); - for ( ClassFile classFile : additionalClassFiles ) - { - throwIfClassNameDoesNotMatch( classFile, classFilePath ); - list.add( classFile ); + for (ClassFile classFile : additionalClassFiles) { + throwIfClassNameDoesNotMatch(classFile, classFilePath); + list.add(classFile); } } @@ -76,17 +74,13 @@ public ClassesWithSameName( Log log, ClassFile initialClassFile, ClassFile... ad * add("Class2.class") * previous() // returns "Class1.class" */ - public ClassFile previous() - { - if ( list.size() > 1 ) - { + public ClassFile previous() { + if (list.size() > 1) { int lastIndex = list.size() - 2; - return list.get( lastIndex ); - } - else - { - throw new IllegalArgumentException( "there was only " + list.size() - + " element(s) in the list, so there is no 2nd-to-last element to retrieve " ); + return list.get(lastIndex); + } else { + throw new IllegalArgumentException("there was only " + list.size() + + " element(s) in the list, so there is no 2nd-to-last element to retrieve "); } } @@ -95,23 +89,20 @@ public ClassFile previous() * (though the artifact can be different). * @param classFile The path to the .class file. Example: org/apache/maven/Stuff.class */ - public void add( ClassFile classFile ) - { - throwIfClassNameDoesNotMatch( classFile, classFilePath ); - list.add( classFile ); + public void add(ClassFile classFile) { + throwIfClassNameDoesNotMatch(classFile, classFilePath); + list.add(classFile); } /** * @return Return a Set rather than a List so we can use this as the key in another Map. * List.of(3,2,1) doesn't equal List.of(1,2,3) but Set.of(3,2,1) equals Set.of(1,2,3) */ - public Set getAllArtifactsThisClassWasFoundIn() - { + public Set getAllArtifactsThisClassWasFoundIn() { Set result = new HashSet<>(); - for ( ClassFile classFile : list ) - { - result.add( classFile.getArtifactThisClassWasFoundIn() ); + for (ClassFile classFile : list) { + result.add(classFile.getArtifactThisClassWasFoundIn()); } return result; @@ -125,30 +116,25 @@ public Set getAllArtifactsThisClassWasFoundIn() * one of the same class, regardless of bytecode. * @return true if there are duplicates, false if not. */ - public boolean hasDuplicates( boolean ignoreWhenIdentical ) - { + public boolean hasDuplicates(boolean ignoreWhenIdentical) { boolean compareJustClassNames = !ignoreWhenIdentical; - if ( compareJustClassNames ) - { + if (compareJustClassNames) { return list.size() > 1; } - if ( list.size() <= 1 ) - { + if (list.size() <= 1) { return false; } - String previousHash = list.get( 0 ).getHash(); - for ( int i = 1; i < list.size(); i++ ) - { - String currentHash = list.get( i ).getHash(); - if ( !previousHash.equals( currentHash ) ) - { + String previousHash = list.get(0).getHash(); + for (int i = 1; i < list.size(); i++) { + String currentHash = list.get(i).getHash(); + if (!previousHash.equals(currentHash)) { return true; } } - log.debug( "ignoring duplicates of class " + classFilePath + " since the bytecode matches exactly" ); + log.debug("ignoring duplicates of class " + classFilePath + " since the bytecode matches exactly"); return false; } @@ -165,30 +151,24 @@ public boolean hasDuplicates( boolean ignoreWhenIdentical ) * Example (ignoreWhenIdentical = true): * org/apache/maven/Stuff.class -- the bytecode exactly matches in these: a.jar and b.jar */ - public String toOutputString( boolean ignoreWhenIdentical ) - { + public String toOutputString(boolean ignoreWhenIdentical) { String result = classFilePath; - if ( list.size() >= 2 && ignoreWhenIdentical ) - { + if (list.size() >= 2 && ignoreWhenIdentical) { StringBuilder duplicationInfo = new StringBuilder(); - for ( Set groupedArtifacts : groupArtifactsWhoseClassesAreExactMatch().values() ) - { - if ( groupedArtifacts.size() <= 1 ) - { + for (Set groupedArtifacts : + groupArtifactsWhoseClassesAreExactMatch().values()) { + if (groupedArtifacts.size() <= 1) { continue; } - if ( duplicationInfo.length() == 0 ) - { - duplicationInfo.append( " -- the bytecode exactly matches in these: " ); - } - else - { - duplicationInfo.append( "; and more exact matches in these: " ); + if (duplicationInfo.length() == 0) { + duplicationInfo.append(" -- the bytecode exactly matches in these: "); + } else { + duplicationInfo.append("; and more exact matches in these: "); } - duplicationInfo.append( joinWithSeparator( groupedArtifacts, " and " ) ); + duplicationInfo.append(joinWithSeparator(groupedArtifacts, " and ")); } result += duplicationInfo.toString(); @@ -197,50 +177,40 @@ public String toOutputString( boolean ignoreWhenIdentical ) return result; } - private static void throwIfClassNameDoesNotMatch( ClassFile classFile, String otherClassFilePath ) - { - if ( !classFile.getClassFilePath().equals( otherClassFilePath ) ) - { - throw new IllegalArgumentException( "Expected class " + otherClassFilePath - + " but got " + classFile.getClassFilePath() ); + private static void throwIfClassNameDoesNotMatch(ClassFile classFile, String otherClassFilePath) { + if (!classFile.getClassFilePath().equals(otherClassFilePath)) { + throw new IllegalArgumentException( + "Expected class " + otherClassFilePath + " but got " + classFile.getClassFilePath()); } } - private String joinWithSeparator( Set artifacts, String separator ) - { + private String joinWithSeparator(Set artifacts, String separator) { StringBuilder result = new StringBuilder(); boolean first = true; - for ( Artifact artifact : artifacts ) - { - if ( first ) - { + for (Artifact artifact : artifacts) { + if (first) { first = false; - } - else - { - result.append( separator ); + } else { + result.append(separator); } - result.append( artifact ); + result.append(artifact); } return result.toString(); } - private Map> groupArtifactsWhoseClassesAreExactMatch() - { + private Map> groupArtifactsWhoseClassesAreExactMatch() { Map> groupedArtifacts = new LinkedHashMap<>(); - for ( ClassFile classFile : list ) - { - Set artifacts = groupedArtifacts.get( classFile.getHash() ); - if ( artifacts == null ) - { + for (ClassFile classFile : list) { + Set artifacts = groupedArtifacts.get(classFile.getHash()); + if (artifacts == null) { artifacts = new LinkedHashSet<>(); } - artifacts.add( classFile.getArtifactThisClassWasFoundIn() ); + artifacts.add(classFile.getArtifactThisClassWasFoundIn()); - groupedArtifacts.put( classFile.getHash(), artifacts ); + groupedArtifacts.put(classFile.getHash(), artifacts); } return groupedArtifacts; diff --git a/src/main/java/org/apache/maven/plugins/enforcer/EnforceBytecodeVersion.java b/src/main/java/org/apache/maven/plugins/enforcer/EnforceBytecodeVersion.java index ea17062d..c7c29d51 100644 --- a/src/main/java/org/apache/maven/plugins/enforcer/EnforceBytecodeVersion.java +++ b/src/main/java/org/apache/maven/plugins/enforcer/EnforceBytecodeVersion.java @@ -1,492 +1,424 @@ -package org.apache.maven.plugins.enforcer; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.io.File; -import java.io.EOFException; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.artifact.resolver.filter.AndArtifactFilter; -import org.apache.maven.enforcer.rule.api.EnforcerRuleException; -import org.apache.maven.plugin.logging.Log; -import org.apache.maven.shared.artifact.filter.AbstractStrictPatternArtifactFilter; -import org.apache.maven.shared.artifact.filter.StrictPatternExcludesArtifactFilter; -import org.apache.maven.shared.artifact.filter.StrictPatternIncludesArtifactFilter; -import org.codehaus.plexus.util.IOUtil; - -/** - * Enforcer rule that will check the bytecode version of each class of each dependency. - * - * @see Java class file general layout - * @since 1.0-alpha-4 - */ -public class EnforceBytecodeVersion - extends AbstractResolveDependencies -{ - private static final Map JDK_TO_MAJOR_VERSION_NUMBER_MAPPING = new LinkedHashMap<>(); - /** - * Default ignores when validating against jdk < 9 because module-info.class will always have level 1.9. - */ - private static final String[] DEFAULT_CLASSES_IGNORE_BEFORE_JDK_9 = {"module-info"}; - - private final Pattern MULTIRELEASE = Pattern.compile( "META-INF/versions/(\\d+)/.*" ); - - static - { - JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put( "1.1", 45 ); - JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put( "1.2", 46 ); - JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put( "1.3", 47 ); - JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put( "1.4", 48 ); - JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put( "1.5", 49 ); - // Java6 - JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put( "1.6", 50 ); - JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put( "6", 50 ); - // Java7 - JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put( "1.7", 51 ); - JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put( "7", 51 ); - // Java8 - JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put( "8", 52 ); - JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put( "1.8", 52 ); - // Java9 - JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put( "9", 53 ); - JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put( "1.9", 53 ); - - // Java10 - JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put( "10", 54 ); - JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put( "1.10", 54 ); - - // Java11 - JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put( "11", 55 ); - JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put( "1.11", 55 ); - - // Java 12 - JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put( "12", 56 ); - JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put( "1.12", 56 ); - - // Java 13 - JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put( "13", 57 ); - JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put( "1.13", 57 ); - - // Java 14 - JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put( "14", 58 ); - JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put( "1.14", 58 ); - - // Java 15 - JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put( "15", 59 ); - JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put( "1.15", 59 ); - - // Java 16 - JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put( "16", 60 ); - JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put( "1.16", 60 ); - - // Java 17 - JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put( "17", 61 ); - JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put( "1.17", 61 ); - - // Java 18 - JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put( "18", 62 ); - - // Java 19 - JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put( "19", 63 ); - - // Java 20 - JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put( "20", 64 ); - } - - static String renderVersion( int major, int minor ) - { - if ( minor == 0 ) - { - for ( Map.Entry entry : JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.entrySet() ) - { - if ( major == entry.getValue() ) - { - return "JDK " + entry.getKey(); - } - } - } - return major + "." + minor; - } - - private String message; - - /** - * JDK version as used for example in the maven-compiler-plugin: 1.5, 1.6 and so on. If in need of more precise - * configuration please see {@link #maxJavaMajorVersionNumber} and {@link #maxJavaMinorVersionNumber} Mandatory if - * {@link #maxJavaMajorVersionNumber} not specified. - */ - private String maxJdkVersion; - - /** - * If unsure, don't use that parameter. Better look at {@link #maxJdkVersion}. Mandatory if {@link #maxJdkVersion} - * is not specified. see http://en.wikipedia.org/wiki/Java_class_file#General_layout - */ - int maxJavaMajorVersionNumber = -1; - - /** - * This parameter is here for potentially advanced use cases, but it seems like it is actually always 0. - * - * @see #maxJavaMajorVersionNumber - * @see Java class file general layout - */ - int maxJavaMinorVersionNumber = 0; - - /** Specify if transitive dependencies should be searched (default) or only look at direct dependencies. */ - private boolean searchTransitive = true; - - /** - * @see AbstractStrictPatternArtifactFilter - */ - private List includes, excludes; - - /** - * List of classes to ignore. Wildcard at the end accepted - */ - private String[] ignoreClasses; - - /** - * Process module-info and Multi-Release JAR classes if true - */ - private boolean strict = false; - - /** - * Optional list of dependency scopes to ignore. {@code test} and {@code provided} make sense here. - */ - private String[] ignoredScopes; - - /** - * Ignore all dependencies which have {@code <optional>true</optional>}. - * @since 1.2 - */ - private boolean ignoreOptionals = false; - - private List ignorableDependencies = new ArrayList<>(); - - @Override - protected void handleArtifacts( Set artifacts ) - throws EnforcerRuleException - { - computeParameters(); - - // look for banned dependencies - Set foundExcludes = checkDependencies( filterArtifacts( artifacts ), getLog() ); - - // if any are found, fail the check but list all of them - if ( foundExcludes != null && !foundExcludes.isEmpty() ) - { - StringBuilder buf = new StringBuilder(); - if ( message != null ) - { - buf.append(message).append("\n"); - } - for ( Artifact artifact : foundExcludes ) - { - buf.append( getErrorMessage( artifact ) ); - } - message = buf + "Use 'mvn dependency:tree' to locate the source of the banned dependencies."; - - throw new EnforcerRuleException( message ); - } - } - - @Override - protected boolean isSearchTransitive() - { - return searchTransitive; - } - - protected CharSequence getErrorMessage( Artifact artifact ) - { - return "Found Banned Dependency: " + artifact.getId() + "\n"; - } - - private void computeParameters() - throws EnforcerRuleException - { - if ( maxJdkVersion != null && maxJavaMajorVersionNumber != -1 ) - { - throw new IllegalArgumentException( "Only maxJdkVersion or maxJavaMajorVersionNumber " - + "configuration parameters should be set. Not both." ); - } - if ( maxJdkVersion == null && maxJavaMajorVersionNumber == -1 ) - { - throw new IllegalArgumentException( "Exactly one of maxJdkVersion or " - + "maxJavaMajorVersionNumber options should be set." ); - } - if ( maxJdkVersion != null ) - { - Integer needle = JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.get( maxJdkVersion ); - if ( needle == null ) - { - throw new IllegalArgumentException( "Unknown JDK version given. Should be something like " + - "\"1.7\", \"8\", \"11\", \"12\", \"13\", \"14\", \"15\", \"16\", \"17\", \"18\", \"19\", \"20\"" ); - } - maxJavaMajorVersionNumber = needle; - if ( !strict && needle < 53 ) - { - IgnorableDependency ignoreModuleInfoDependency = new IgnorableDependency(); - ignoreModuleInfoDependency.applyIgnoreClasses(DEFAULT_CLASSES_IGNORE_BEFORE_JDK_9, false ); - ignorableDependencies.add( ignoreModuleInfoDependency ); - } - } - if ( maxJavaMajorVersionNumber == -1 ) - { - throw new EnforcerRuleException( "maxJavaMajorVersionNumber must be set in the plugin configuration" ); - } - if ( ignoreClasses != null ) - { - IgnorableDependency ignorableDependency = new IgnorableDependency(); - ignorableDependency.applyIgnoreClasses( ignoreClasses, false ); - ignorableDependencies.add( ignorableDependency ); - } - } - - protected Set checkDependencies( Set dependencies, Log log ) - throws EnforcerRuleException - { - long beforeCheck = System.currentTimeMillis(); - Set problematic = new LinkedHashSet<>(); - for ( Artifact artifact : dependencies ) - { - getLog().debug( "Analyzing artifact " + artifact ); - String problem = isBadArtifact( artifact ); - if ( problem != null ) - { - getLog().info( problem ); - problematic.add( artifact ); - } - } - getLog().debug( "Bytecode version analysis took " + ( System.currentTimeMillis() - beforeCheck ) + " ms" ); - return problematic; - } - - private String isBadArtifact( Artifact a ) - throws EnforcerRuleException - { - File f = a.getFile(); - getLog().debug( "isBadArtifact() a:" + a + " Artifact getFile():" + a.getFile() ); - if ( f == null ) - { - // This happens if someone defines dependencies instead of dependencyManagement in a pom file - // which packaging type is pom. - return null; - } - if ( !f.getName().endsWith( ".jar" ) ) - { - return null; - } - JarFile jarFile = null; - try - { - jarFile = new JarFile( f ); - getLog().debug( f.getName() + " => " + f.getPath() ); - byte[] magicAndClassFileVersion = new byte[8]; - JAR: for ( Enumeration e = jarFile.entries(); e.hasMoreElements(); ) - { - JarEntry entry = e.nextElement(); - if ( !entry.isDirectory() && entry.getName().endsWith( ".class" ) ) - { - for ( IgnorableDependency i : ignorableDependencies ) - { - if ( i.matches( entry.getName() ) ) - { - continue JAR; - } - } - - InputStream is = null; - try - { - is = jarFile.getInputStream( entry ); - int total = magicAndClassFileVersion.length; - while ( total > 0 ) - { - int read = - is.read( magicAndClassFileVersion, magicAndClassFileVersion.length - total, total ); - - if ( read == -1 ) - { - throw new EOFException( f.toString() ); - } - - total -= read; - } - - is.close(); - is = null; - } - finally - { - IOUtil.close( is ); - } - - int minor = ( magicAndClassFileVersion[4] << 8 ) + magicAndClassFileVersion[5]; - int major = ( magicAndClassFileVersion[6] << 8 ) + magicAndClassFileVersion[7]; - - // Assuming regex match is more expensive, verify bytecode versions first - - if ( ( major > maxJavaMajorVersionNumber ) - || ( major == maxJavaMajorVersionNumber && minor > maxJavaMinorVersionNumber ) ) - { - - Matcher matcher = MULTIRELEASE.matcher( entry.getName() ); - - if ( !strict && matcher.matches() ) - { - Integer maxExpectedMajor = JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.get( matcher.group( 1 ) ); - - if (maxExpectedMajor == null) { - getLog().warn( "Unknown bytecodeVersion for " + a + " : " - + entry.getName() + ": got " + maxExpectedMajor + " class-file-version" ); - } - else if ( major > maxExpectedMajor ) - { - getLog().warn( "Invalid bytecodeVersion for " + a + " : " - + entry.getName() + ": expected lower or equal to " + maxExpectedMajor + ", but was " + major ); - } - } - else - { - return "Restricted to " + renderVersion( maxJavaMajorVersionNumber, maxJavaMinorVersionNumber ) - + " yet " + a + " contains " + entry.getName() + " targeted to " - + renderVersion( major, minor ); - } - } - } - } - } - catch ( IOException e ) - { - throw new EnforcerRuleException( "IOException while reading " + f, e ); - } - catch ( IllegalArgumentException e ) - { - throw new EnforcerRuleException( "Error while reading " + f, e ); - } - finally - { - closeQuietly( jarFile ); - } - return null; - } - - private void closeQuietly( JarFile jarFile ) - { - if ( jarFile != null ) - { - try - { - jarFile.close(); - } - catch ( IOException ioe ) - { - getLog().warn( "Exception catched while closing " + jarFile.getName(), ioe ); - } - } - } - - public void setMaxJavaMajorVersionNumber( int maxJavaMajorVersionNumber ) - { - this.maxJavaMajorVersionNumber = maxJavaMajorVersionNumber; - } - - public void setMaxJavaMinorVersionNumber( int maxJavaMinorVersionNumber ) - { - this.maxJavaMinorVersionNumber = maxJavaMinorVersionNumber; - } - - /** - * Sets the search transitive. - * - * @param theSearchTransitive the searchTransitive to set - */ - public void setSearchTransitive( boolean theSearchTransitive ) - { - this.searchTransitive = theSearchTransitive; - } - - /** - * Process module-info and Multi-Release JAR classes if true - * @param strict the strictness to set - */ - public void setStrict( boolean strict ) - { - this.strict = strict; - } - - // copied from RequireReleaseDeps - /* - * Filter the dependency artifacts according to the includes and excludes If includes and excludes are both null, - * the original set is returned. - * @param dependencies the list of dependencies to filter - * @return the resulting set of dependencies - */ - private Set filterArtifacts( Set dependencies ) - { - if ( includes == null && excludes == null && ignoredScopes == null && !ignoreOptionals ) - { - return dependencies; - } - - AndArtifactFilter filter = new AndArtifactFilter(); - if ( includes != null ) - { - filter.add( new StrictPatternIncludesArtifactFilter( includes ) ); - } - if ( excludes != null ) - { - filter.add( new StrictPatternExcludesArtifactFilter( excludes ) ); - } - - Set result = new HashSet<>(); - for ( Artifact artifact : dependencies ) - { - if ( ignoredScopes != null && Arrays.asList( ignoredScopes ).contains( artifact.getScope() ) ) - { - continue; - } - if ( ignoreOptionals && artifact.isOptional() ) - { - continue; - } - if ( filter.include( artifact ) ) - { - result.add( artifact ); - } - } - return result; - } - -} +package org.apache.maven.plugins.enforcer; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import java.io.EOFException; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Enumeration; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.maven.artifact.Artifact; +import org.apache.maven.artifact.resolver.filter.AndArtifactFilter; +import org.apache.maven.enforcer.rule.api.EnforcerRuleException; +import org.apache.maven.plugin.logging.Log; +import org.apache.maven.shared.artifact.filter.AbstractStrictPatternArtifactFilter; +import org.apache.maven.shared.artifact.filter.StrictPatternExcludesArtifactFilter; +import org.apache.maven.shared.artifact.filter.StrictPatternIncludesArtifactFilter; +import org.codehaus.plexus.util.IOUtil; + +/** + * Enforcer rule that will check the bytecode version of each class of each dependency. + * + * @see Java class file general layout + * @since 1.0-alpha-4 + */ +public class EnforceBytecodeVersion extends AbstractResolveDependencies { + private static final Map JDK_TO_MAJOR_VERSION_NUMBER_MAPPING = new LinkedHashMap<>(); + /** + * Default ignores when validating against jdk < 9 because module-info.class will always have level 1.9. + */ + private static final String[] DEFAULT_CLASSES_IGNORE_BEFORE_JDK_9 = {"module-info"}; + + private static final Pattern MULTIRELEASE = Pattern.compile("META-INF/versions/(\\d+)/.*"); + + static { + JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put("1.1", 45); + JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put("1.2", 46); + JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put("1.3", 47); + JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put("1.4", 48); + JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put("1.5", 49); + // Java6 + JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put("1.6", 50); + JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put("6", 50); + // Java7 + JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put("1.7", 51); + JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put("7", 51); + // Java8 + JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put("8", 52); + JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put("1.8", 52); + // Java9 + JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put("9", 53); + JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put("1.9", 53); + + // Java10 + JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put("10", 54); + JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put("1.10", 54); + + // Java11 + JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put("11", 55); + JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put("1.11", 55); + + // Java 12 + JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put("12", 56); + JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put("1.12", 56); + + // Java 13 + JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put("13", 57); + JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put("1.13", 57); + + // Java 14 + JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put("14", 58); + JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put("1.14", 58); + + // Java 15 + JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put("15", 59); + JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put("1.15", 59); + + // Java 16 + JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put("16", 60); + JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put("1.16", 60); + + // Java 17 + JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put("17", 61); + JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put("1.17", 61); + + // Java 18 + JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put("18", 62); + + // Java 19 + JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put("19", 63); + + // Java 20 + JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put("20", 64); + } + + static String renderVersion(int major, int minor) { + if (minor == 0) { + for (Map.Entry entry : JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.entrySet()) { + if (major == entry.getValue()) { + return "JDK " + entry.getKey(); + } + } + } + return major + "." + minor; + } + + private String message; + + /** + * JDK version as used for example in the maven-compiler-plugin: 1.5, 1.6 and so on. If in need of more precise + * configuration please see {@link #maxJavaMajorVersionNumber} and {@link #maxJavaMinorVersionNumber} Mandatory if + * {@link #maxJavaMajorVersionNumber} not specified. + */ + private String maxJdkVersion; + + /** + * If unsure, don't use that parameter. Better look at {@link #maxJdkVersion}. Mandatory if {@link #maxJdkVersion} + * is not specified. see http://en.wikipedia.org/wiki/Java_class_file#General_layout + */ + int maxJavaMajorVersionNumber = -1; + + /** + * This parameter is here for potentially advanced use cases, but it seems like it is actually always 0. + * + * @see #maxJavaMajorVersionNumber + * @see Java class file general layout + */ + int maxJavaMinorVersionNumber = 0; + + /** Specify if transitive dependencies should be searched (default) or only look at direct dependencies. */ + private boolean searchTransitive = true; + + /** + * @see AbstractStrictPatternArtifactFilter + */ + private List includes, excludes; + + /** + * List of classes to ignore. Wildcard at the end accepted + */ + private String[] ignoreClasses; + + /** + * Process module-info and Multi-Release JAR classes if true + */ + private boolean strict = false; + + /** + * Optional list of dependency scopes to ignore. {@code test} and {@code provided} make sense here. + */ + private String[] ignoredScopes; + + /** + * Ignore all dependencies which have {@code <optional>true</optional>}. + * @since 1.2 + */ + private boolean ignoreOptionals = false; + + private List ignorableDependencies = new ArrayList<>(); + + @Override + protected void handleArtifacts(Set artifacts) throws EnforcerRuleException { + computeParameters(); + + // look for banned dependencies + Set foundExcludes = checkDependencies(filterArtifacts(artifacts), getLog()); + + // if any are found, fail the check but list all of them + if (foundExcludes != null && !foundExcludes.isEmpty()) { + StringBuilder buf = new StringBuilder(); + if (message != null) { + buf.append(message).append("\n"); + } + for (Artifact artifact : foundExcludes) { + buf.append(getErrorMessage(artifact)); + } + message = buf + "Use 'mvn dependency:tree' to locate the source of the banned dependencies."; + + throw new EnforcerRuleException(message); + } + } + + @Override + protected boolean isSearchTransitive() { + return searchTransitive; + } + + protected CharSequence getErrorMessage(Artifact artifact) { + return "Found Banned Dependency: " + artifact.getId() + "\n"; + } + + private void computeParameters() throws EnforcerRuleException { + if (maxJdkVersion != null && maxJavaMajorVersionNumber != -1) { + throw new IllegalArgumentException("Only maxJdkVersion or maxJavaMajorVersionNumber " + + "configuration parameters should be set. Not both."); + } + if (maxJdkVersion == null && maxJavaMajorVersionNumber == -1) { + throw new IllegalArgumentException( + "Exactly one of maxJdkVersion or " + "maxJavaMajorVersionNumber options should be set."); + } + if (maxJdkVersion != null) { + Integer needle = JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.get(maxJdkVersion); + if (needle == null) { + throw new IllegalArgumentException( + "Unknown JDK version given. Should be something like " + + "\"1.7\", \"8\", \"11\", \"12\", \"13\", \"14\", \"15\", \"16\", \"17\", \"18\", \"19\", \"20\""); + } + maxJavaMajorVersionNumber = needle; + if (!strict && needle < 53) { + IgnorableDependency ignoreModuleInfoDependency = new IgnorableDependency(); + ignoreModuleInfoDependency.applyIgnoreClasses(DEFAULT_CLASSES_IGNORE_BEFORE_JDK_9, false); + ignorableDependencies.add(ignoreModuleInfoDependency); + } + } + if (maxJavaMajorVersionNumber == -1) { + throw new EnforcerRuleException("maxJavaMajorVersionNumber must be set in the plugin configuration"); + } + if (ignoreClasses != null) { + IgnorableDependency ignorableDependency = new IgnorableDependency(); + ignorableDependency.applyIgnoreClasses(ignoreClasses, false); + ignorableDependencies.add(ignorableDependency); + } + } + + protected Set checkDependencies(Set dependencies, Log log) throws EnforcerRuleException { + long beforeCheck = System.currentTimeMillis(); + Set problematic = new LinkedHashSet<>(); + for (Artifact artifact : dependencies) { + getLog().debug("Analyzing artifact " + artifact); + String problem = isBadArtifact(artifact); + if (problem != null) { + getLog().info(problem); + problematic.add(artifact); + } + } + getLog().debug("Bytecode version analysis took " + (System.currentTimeMillis() - beforeCheck) + " ms"); + return problematic; + } + + private String isBadArtifact(Artifact a) throws EnforcerRuleException { + File f = a.getFile(); + getLog().debug("isBadArtifact() a:" + a + " Artifact getFile():" + a.getFile()); + if (f == null) { + // This happens if someone defines dependencies instead of dependencyManagement in a pom file + // which packaging type is pom. + return null; + } + if (!f.getName().endsWith(".jar")) { + return null; + } + JarFile jarFile = null; + try { + jarFile = new JarFile(f); + getLog().debug(f.getName() + " => " + f.getPath()); + byte[] magicAndClassFileVersion = new byte[8]; + JAR: + for (Enumeration e = jarFile.entries(); e.hasMoreElements(); ) { + JarEntry entry = e.nextElement(); + if (!entry.isDirectory() && entry.getName().endsWith(".class")) { + for (IgnorableDependency i : ignorableDependencies) { + if (i.matches(entry.getName())) { + continue JAR; + } + } + + InputStream is = null; + try { + is = jarFile.getInputStream(entry); + int total = magicAndClassFileVersion.length; + while (total > 0) { + int read = + is.read(magicAndClassFileVersion, magicAndClassFileVersion.length - total, total); + + if (read == -1) { + throw new EOFException(f.toString()); + } + + total -= read; + } + + is.close(); + is = null; + } finally { + IOUtil.close(is); + } + + int minor = (magicAndClassFileVersion[4] << 8) + magicAndClassFileVersion[5]; + int major = (magicAndClassFileVersion[6] << 8) + magicAndClassFileVersion[7]; + + // Assuming regex match is more expensive, verify bytecode versions first + + if ((major > maxJavaMajorVersionNumber) + || (major == maxJavaMajorVersionNumber && minor > maxJavaMinorVersionNumber)) { + + Matcher matcher = MULTIRELEASE.matcher(entry.getName()); + + if (!strict && matcher.matches()) { + Integer maxExpectedMajor = JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.get(matcher.group(1)); + + if (maxExpectedMajor == null) { + getLog().warn("Unknown bytecodeVersion for " + a + " : " + entry.getName() + ": got " + + maxExpectedMajor + " class-file-version"); + } else if (major > maxExpectedMajor) { + getLog().warn("Invalid bytecodeVersion for " + a + " : " + entry.getName() + + ": expected lower or equal to " + maxExpectedMajor + ", but was " + major); + } + } else { + return "Restricted to " + + renderVersion(maxJavaMajorVersionNumber, maxJavaMinorVersionNumber) + + " yet " + a + " contains " + entry.getName() + " targeted to " + + renderVersion(major, minor); + } + } + } + } + } catch (IOException e) { + throw new EnforcerRuleException("IOException while reading " + f, e); + } catch (IllegalArgumentException e) { + throw new EnforcerRuleException("Error while reading " + f, e); + } finally { + closeQuietly(jarFile); + } + return null; + } + + private void closeQuietly(JarFile jarFile) { + if (jarFile != null) { + try { + jarFile.close(); + } catch (IOException ioe) { + getLog().warn("Exception catched while closing " + jarFile.getName(), ioe); + } + } + } + + public void setMaxJavaMajorVersionNumber(int maxJavaMajorVersionNumber) { + this.maxJavaMajorVersionNumber = maxJavaMajorVersionNumber; + } + + public void setMaxJavaMinorVersionNumber(int maxJavaMinorVersionNumber) { + this.maxJavaMinorVersionNumber = maxJavaMinorVersionNumber; + } + + /** + * Sets the search transitive. + * + * @param theSearchTransitive the searchTransitive to set + */ + public void setSearchTransitive(boolean theSearchTransitive) { + this.searchTransitive = theSearchTransitive; + } + + /** + * Process module-info and Multi-Release JAR classes if true + * @param strict the strictness to set + */ + public void setStrict(boolean strict) { + this.strict = strict; + } + + // copied from RequireReleaseDeps + /* + * Filter the dependency artifacts according to the includes and excludes If includes and excludes are both null, + * the original set is returned. + * @param dependencies the list of dependencies to filter + * @return the resulting set of dependencies + */ + private Set filterArtifacts(Set dependencies) { + if (includes == null && excludes == null && ignoredScopes == null && !ignoreOptionals) { + return dependencies; + } + + AndArtifactFilter filter = new AndArtifactFilter(); + if (includes != null) { + filter.add(new StrictPatternIncludesArtifactFilter(includes)); + } + if (excludes != null) { + filter.add(new StrictPatternExcludesArtifactFilter(excludes)); + } + + Set result = new HashSet<>(); + for (Artifact artifact : dependencies) { + if (ignoredScopes != null && Arrays.asList(ignoredScopes).contains(artifact.getScope())) { + continue; + } + if (ignoreOptionals && artifact.isOptional()) { + continue; + } + if (filter.include(artifact)) { + result.add(artifact); + } + } + return result; + } +} diff --git a/src/main/java/org/apache/maven/plugins/enforcer/InputStreamSupplier.java b/src/main/java/org/apache/maven/plugins/enforcer/InputStreamSupplier.java index 3f9685c1..1bea54d4 100644 --- a/src/main/java/org/apache/maven/plugins/enforcer/InputStreamSupplier.java +++ b/src/main/java/org/apache/maven/plugins/enforcer/InputStreamSupplier.java @@ -28,7 +28,6 @@ * @author Slawomir Jaranowski */ @FunctionalInterface -interface InputStreamSupplier -{ +interface InputStreamSupplier { InputStream get() throws IOException; } diff --git a/src/main/java/org/apache/maven/plugins/enforcer/JarUtils.java b/src/main/java/org/apache/maven/plugins/enforcer/JarUtils.java index 60c851cf..09377b01 100644 --- a/src/main/java/org/apache/maven/plugins/enforcer/JarUtils.java +++ b/src/main/java/org/apache/maven/plugins/enforcer/JarUtils.java @@ -24,15 +24,12 @@ /** * Utility methods for working with Java jar files. */ -public class JarUtils -{ +public class JarUtils { /** * @param artifact the artifact to check (could be a jar file, directory, etc.) * @return true if the artifact is a jar file, false if it's something else (like a directory) */ - public static boolean isJarFile( Artifact artifact ) - { - return artifact.getFile().isFile() && "jar".equals( artifact.getType() ); + public static boolean isJarFile(Artifact artifact) { + return artifact.getFile().isFile() && "jar".equals(artifact.getType()); } - } diff --git a/src/main/java/org/apache/maven/plugins/enforcer/RequireContributorRoles.java b/src/main/java/org/apache/maven/plugins/enforcer/RequireContributorRoles.java index 5c176d0f..081e5540 100644 --- a/src/main/java/org/apache/maven/plugins/enforcer/RequireContributorRoles.java +++ b/src/main/java/org/apache/maven/plugins/enforcer/RequireContributorRoles.java @@ -30,18 +30,15 @@ * @author Mirko Friedenhagen * @since 1.0-alpha-3 */ -public class RequireContributorRoles extends AbstractRequireRoles -{ +public class RequireContributorRoles extends AbstractRequireRoles { @Override - protected final String getRoleName() - { + protected final String getRoleName() { return "contributor"; } @Override - protected List getRoles( MavenProject mavenProject ) - { + protected List getRoles(MavenProject mavenProject) { return mavenProject.getContributors(); } -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/maven/plugins/enforcer/RequireDeveloperRoles.java b/src/main/java/org/apache/maven/plugins/enforcer/RequireDeveloperRoles.java index 4b6a4652..73801dff 100644 --- a/src/main/java/org/apache/maven/plugins/enforcer/RequireDeveloperRoles.java +++ b/src/main/java/org/apache/maven/plugins/enforcer/RequireDeveloperRoles.java @@ -30,18 +30,15 @@ * @author Mirko Friedenhagen * @since 1.0-alpha-3 */ -public class RequireDeveloperRoles extends AbstractRequireRoles -{ +public class RequireDeveloperRoles extends AbstractRequireRoles { @Override - protected String getRoleName() - { + protected String getRoleName() { return "developer"; } @Override - protected List getRoles( MavenProject mavenProject ) - { + protected List getRoles(MavenProject mavenProject) { return mavenProject.getDevelopers(); } -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/maven/plugins/enforcer/RequireEncoding.java b/src/main/java/org/apache/maven/plugins/enforcer/RequireEncoding.java index acd3d31c..18998ca0 100644 --- a/src/main/java/org/apache/maven/plugins/enforcer/RequireEncoding.java +++ b/src/main/java/org/apache/maven/plugins/enforcer/RequireEncoding.java @@ -24,11 +24,9 @@ * @see mikedon/encoding-enforcer * @see ericbn/encoding-enforcer */ -public class RequireEncoding - extends AbstractMojoHausEnforcerRule -{ +public class RequireEncoding extends AbstractMojoHausEnforcerRule { private static final String ISO_8859_15 = "ISO-8859-15"; - + /** * Validate files match this encoding. If not specified then default to ${project.build.sourceEncoding}. */ @@ -64,95 +62,77 @@ public class RequireEncoding */ private boolean acceptIso8859Subset = false; - public void execute( EnforcerRuleHelper helper ) - throws EnforcerRuleException - { - try - { - if ( StringUtils.isBlank( encoding ) ) - { - encoding = (String) helper.evaluate( "${project.build.sourceEncoding}" ); + public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException { + try { + if (StringUtils.isBlank(encoding)) { + encoding = (String) helper.evaluate("${project.build.sourceEncoding}"); } Log log = helper.getLog(); - Set< String > acceptedEncodings = new HashSet<>(Collections.singletonList(encoding)); - if ( encoding.equals( StandardCharsets.US_ASCII.name() ) ) - { - log.warn( "Encoding US-ASCII is hard to detect. Use UTF-8 or ISO-8859-1" ); + Set acceptedEncodings = new HashSet<>(Collections.singletonList(encoding)); + if (encoding.equals(StandardCharsets.US_ASCII.name())) { + log.warn("Encoding US-ASCII is hard to detect. Use UTF-8 or ISO-8859-1"); } - if ( acceptAsciiSubset && ( encoding.equals( StandardCharsets.ISO_8859_1.name() ) || encoding.equals(ISO_8859_15) || encoding.equals( StandardCharsets.UTF_8.name() ) ) ) - { - acceptedEncodings.add( StandardCharsets.US_ASCII.name() ); + if (acceptAsciiSubset + && (encoding.equals(StandardCharsets.ISO_8859_1.name()) + || encoding.equals(ISO_8859_15) + || encoding.equals(StandardCharsets.UTF_8.name()))) { + acceptedEncodings.add(StandardCharsets.US_ASCII.name()); } - if ( acceptIso8859Subset && encoding.equals(ISO_8859_15) ) - { - acceptedEncodings.add( "ISO-8859-1" ); + if (acceptIso8859Subset && encoding.equals(ISO_8859_15)) { + acceptedEncodings.add("ISO-8859-1"); } - String basedir = (String) helper.evaluate( "${basedir}" ); + String basedir = (String) helper.evaluate("${basedir}"); DirectoryScanner ds = new DirectoryScanner(); - ds.setBasedir( basedir ); - if ( StringUtils.isNotBlank( includes ) ) - { - ds.setIncludes( includes.split( "[,|]" ) ); + ds.setBasedir(basedir); + if (StringUtils.isNotBlank(includes)) { + ds.setIncludes(includes.split("[,|]")); } - if ( StringUtils.isNotBlank( excludes ) ) - { - ds.setExcludes( excludes.split( "[,|]" ) ); + if (StringUtils.isNotBlank(excludes)) { + ds.setExcludes(excludes.split("[,|]")); } - if ( useDefaultExcludes ) - { + if (useDefaultExcludes) { ds.addDefaultExcludes(); } ds.scan(); StringBuilder filesInMsg = new StringBuilder(); - for ( String file : ds.getIncludedFiles() ) - { - String fileEncoding = getEncoding( encoding, new File( basedir, file ), log ); - if ( log.isDebugEnabled() ) - { - log.debug( file + "==>" + fileEncoding ); + for (String file : ds.getIncludedFiles()) { + String fileEncoding = getEncoding(encoding, new File(basedir, file), log); + if (log.isDebugEnabled()) { + log.debug(file + "==>" + fileEncoding); } - if ( fileEncoding != null && !acceptedEncodings.contains( fileEncoding ) ) - { - filesInMsg.append( file ); - filesInMsg.append( "==>" ); - filesInMsg.append( fileEncoding ); - filesInMsg.append( "\n" ); - if ( failFast ) - { - throw new EnforcerRuleException( filesInMsg.toString() ); + if (fileEncoding != null && !acceptedEncodings.contains(fileEncoding)) { + filesInMsg.append(file); + filesInMsg.append("==>"); + filesInMsg.append(fileEncoding); + filesInMsg.append("\n"); + if (failFast) { + throw new EnforcerRuleException(filesInMsg.toString()); } } } - if ( filesInMsg.length() > 0 ) - { - throw new EnforcerRuleException( "Files not encoded in " + encoding + ":\n" + filesInMsg ); + if (filesInMsg.length() > 0) { + throw new EnforcerRuleException("Files not encoded in " + encoding + ":\n" + filesInMsg); } - } - catch ( IOException ex ) - { - throw new EnforcerRuleException( "Reading Files", ex ); - } - catch ( ExpressionEvaluationException e ) - { - throw new EnforcerRuleException( "Unable to lookup an expression " + e.getLocalizedMessage(), e ); + } catch (IOException ex) { + throw new EnforcerRuleException("Reading Files", ex); + } catch (ExpressionEvaluationException e) { + throw new EnforcerRuleException("Unable to lookup an expression " + e.getLocalizedMessage(), e); } } - protected String getEncoding( String requiredEncoding, File file, Log log ) - throws IOException - { + protected String getEncoding(String requiredEncoding, File file, Log log) throws IOException { FileEncoding fileEncoding = new FileEncoding(); - if ( !fileEncoding.guessFileEncoding( Files.readAllBytes( file.toPath() ) ) ) - { + if (!fileEncoding.guessFileEncoding(Files.readAllBytes(file.toPath()))) { return null; } - if ( log.isDebugEnabled() ) - { - log.debug( String.format( "%s: (%s) %s; charset=%s", file, fileEncoding.getCode(), fileEncoding.getType(), fileEncoding.getCodeMime() ) ); + if (log.isDebugEnabled()) { + log.debug(String.format( + "%s: (%s) %s; charset=%s", + file, fileEncoding.getCode(), fileEncoding.getType(), fileEncoding.getCodeMime())); } return fileEncoding.getCodeMime().toUpperCase(); @@ -164,8 +144,7 @@ protected String getEncoding( String requiredEncoding, File file, Log log ) * return a hash computed from the values of your parameters. If your rule is not cacheable, then the result here is * not important, you may return anything. */ - public String getCacheId() - { + public String getCacheId() { return null; } @@ -174,8 +153,7 @@ public String getCacheId() * things, a given rule may be executed more than once for the same project. This means that even things that change * from project to project may still be cacheable in certain instances. */ - public boolean isCacheable() - { + public boolean isCacheable() { return false; } @@ -185,48 +163,39 @@ public boolean isCacheable() * the results of objects returned by the helper need to be queried. You may for example, store certain objects in * your rule and then query them later. */ - public boolean isResultValid( EnforcerRule cachedRule ) - { + public boolean isResultValid(EnforcerRule cachedRule) { return false; } - public String getEncoding() - { + public String getEncoding() { return encoding; } - public void setEncoding( String encoding ) - { + public void setEncoding(String encoding) { this.encoding = encoding; } - public String getIncludes() - { + public String getIncludes() { return includes; } - public void setIncludes( String includes ) - { + public void setIncludes(String includes) { this.includes = includes; } - public String getExcludes() - { + public String getExcludes() { return excludes; } - public void setExcludes( String excludes ) - { + public void setExcludes(String excludes) { this.excludes = excludes; } - public boolean isUseDefaultExcludes() - { + public boolean isUseDefaultExcludes() { return useDefaultExcludes; } - public void setUseDefaultExcludes( boolean useDefaultExcludes ) - { + public void setUseDefaultExcludes(boolean useDefaultExcludes) { this.useDefaultExcludes = useDefaultExcludes; } } diff --git a/src/main/java/org/apache/maven/plugins/enforcer/RequireProjectUrl.java b/src/main/java/org/apache/maven/plugins/enforcer/RequireProjectUrl.java index b400152c..be65a9dd 100644 --- a/src/main/java/org/apache/maven/plugins/enforcer/RequireProjectUrl.java +++ b/src/main/java/org/apache/maven/plugins/enforcer/RequireProjectUrl.java @@ -19,24 +19,22 @@ * under the License. */ +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; + import org.apache.maven.enforcer.rule.api.EnforcerRule; import org.apache.maven.enforcer.rule.api.EnforcerRuleException; import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.regex.PatternSyntaxException; - /** * This rule enforces the presence of an URL and optionally matches the URL against a regex - * + * * @since 1.0-beta-4 */ -public class RequireProjectUrl - extends AbstractMojoHausEnforcerRule -{ +public class RequireProjectUrl extends AbstractMojoHausEnforcerRule { /** * The regex that the url must match. Default is a non-empty URL */ @@ -59,7 +57,6 @@ public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException { } catch (PatternSyntaxException e) { throw new EnforcerRuleException("Invalid regex \"" + regex + "\": " + e.getLocalizedMessage(), e); } - } /** @@ -82,5 +79,4 @@ public boolean isResultValid(EnforcerRule enforcerRule) { public String getCacheId() { return "Does not matter as not cacheable"; } - } diff --git a/src/main/java/org/apache/maven/plugins/enforcer/RequirePropertyDiverges.java b/src/main/java/org/apache/maven/plugins/enforcer/RequirePropertyDiverges.java index 8d5f7846..c49f7c6a 100644 --- a/src/main/java/org/apache/maven/plugins/enforcer/RequirePropertyDiverges.java +++ b/src/main/java/org/apache/maven/plugins/enforcer/RequirePropertyDiverges.java @@ -47,11 +47,9 @@ * @author Mirko Friedenhagen * @since 1.0-alpha-3 */ -public class RequirePropertyDiverges - extends AbstractMojoHausEnforcerRule -{ +public class RequirePropertyDiverges extends AbstractMojoHausEnforcerRule { private String message; - + static final String MAVEN_ENFORCER_PLUGIN = "org.apache.maven.plugins:maven-enforcer-plugin"; /** * Specify the required property. Must be given. @@ -61,7 +59,8 @@ public class RequirePropertyDiverges * Match the property value to a given regular expression. Defaults to value of defining project. */ private String regex = null; - private final String ruleName = StringUtils.lowercaseFirstLetter( getClass().getSimpleName() ); + + private final String ruleName = StringUtils.lowercaseFirstLetter(getClass().getSimpleName()); /** * Execute the rule. @@ -69,38 +68,30 @@ public class RequirePropertyDiverges * @param helper the helper * @throws EnforcerRuleException the enforcer rule exception */ - public void execute( EnforcerRuleHelper helper ) throws EnforcerRuleException - { + public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException { final Log log = helper.getLog(); - Object propValue = getPropertyValue( helper ); - checkPropValueNotBlank( propValue ); + Object propValue = getPropertyValue(helper); + checkPropValueNotBlank(propValue); - final MavenProject project = getMavenProject( helper ); - log.debug( getRuleName() + ": checking property '" + property + "' for project " + project ); + final MavenProject project = getMavenProject(helper); + log.debug(getRuleName() + ": checking property '" + property + "' for project " + project); - final MavenProject parent = findDefiningParent( project ); + final MavenProject parent = findDefiningParent(project); // fail fast if the defining parent could not be found due to a bug in the rule - if ( parent == null ) - { - throw new IllegalStateException( "Failed to find parent POM which defines the current rule" ); + if (parent == null) { + throw new IllegalStateException("Failed to find parent POM which defines the current rule"); } - if ( project.equals( parent ) ) - { - log.debug( getRuleName() + ": skip for property '" + property + "' as " + project + " defines rule." ); - } - else - { - log.debug( "Check configuration defined in " + parent ); - if ( regex == null ) - { - checkAgainstParentValue( project, parent, helper, propValue ); - } - else - { - checkAgainstRegex( propValue ); + if (project.equals(parent)) { + log.debug(getRuleName() + ": skip for property '" + property + "' as " + project + " defines rule."); + } else { + log.debug("Check configuration defined in " + parent); + if (regex == null) { + checkAgainstParentValue(project, parent, helper, propValue); + } else { + checkAgainstRegex(propValue); } } } @@ -114,24 +105,22 @@ public void execute( EnforcerRuleHelper helper ) throws EnforcerRuleException * @param propValue * @throws EnforcerRuleException */ - void checkAgainstParentValue( final MavenProject project, final MavenProject parent, EnforcerRuleHelper helper, - Object propValue ) throws EnforcerRuleException - { - final StringBuilder parentHierarchy = new StringBuilder( "project." ); + void checkAgainstParentValue( + final MavenProject project, final MavenProject parent, EnforcerRuleHelper helper, Object propValue) + throws EnforcerRuleException { + final StringBuilder parentHierarchy = new StringBuilder("project."); MavenProject needle = project; - while ( !needle.equals( parent ) ) - { - parentHierarchy.append( "parent." ); + while (!needle.equals(parent)) { + parentHierarchy.append("parent."); needle = needle.getParent(); } - final String propertyNameInParent = property.replace( "project.", parentHierarchy.toString() ); - Object parentValue = getPropertyValue( helper, propertyNameInParent ); - if ( propValue.equals( parentValue ) ) - { - final String errorMessage = createResultingErrorMessage( String.format( + final String propertyNameInParent = property.replace("project.", parentHierarchy.toString()); + Object parentValue = getPropertyValue(helper, propertyNameInParent); + if (propValue.equals(parentValue)) { + final String errorMessage = createResultingErrorMessage(String.format( "Property '%s' evaluates to '%s'. This does match '%s' from parent %s", - property, propValue, parentValue, parent ) ); - throw new EnforcerRuleException( errorMessage ); + property, propValue, parentValue, parent)); + throw new EnforcerRuleException(errorMessage); } } @@ -142,16 +131,13 @@ void checkAgainstParentValue( final MavenProject project, final MavenProject par * @param propValue * @throws EnforcerRuleException */ - void checkAgainstRegex( Object propValue ) throws EnforcerRuleException - { + void checkAgainstRegex(Object propValue) throws EnforcerRuleException { // Check that the property does not match the regex. - if ( propValue.toString().matches( regex ) ) - { - final String errorMessage = createResultingErrorMessage( - String.format( + if (propValue.toString().matches(regex)) { + final String errorMessage = createResultingErrorMessage(String.format( "Property '%s' evaluates to '%s'. This does match the regular expression '%s'", - property, propValue, regex ) ); - throw new EnforcerRuleException( errorMessage ); + property, propValue, regex)); + throw new EnforcerRuleException(errorMessage); } } @@ -161,19 +147,15 @@ void checkAgainstRegex( Object propValue ) throws EnforcerRuleException * @param project to inspect * @return the defining ancestor project. */ - final MavenProject findDefiningParent( final MavenProject project ) - { + final MavenProject findDefiningParent(final MavenProject project) { final Xpp3Dom invokingRule = createInvokingRuleDom(); MavenProject parent = project; - while ( parent != null ) - { + while (parent != null) { final Model model = parent.getOriginalModel(); final Build build = model.getBuild(); - if ( build != null ) - { - final List rules = getRuleConfigurations( build ); - if ( isDefiningProject( rules, invokingRule ) ) - { + if (build != null) { + final List rules = getRuleConfigurations(build); + if (isDefiningProject(rules, invokingRule)) { break; } } @@ -187,9 +169,8 @@ final MavenProject findDefiningParent( final MavenProject project ) * * @return dom of the invoker. */ - Xpp3Dom createInvokingRuleDom() - { - return new CreateInvokingRuleDom( this ).getRuleDom(); + Xpp3Dom createInvokingRuleDom() { + return new CreateInvokingRuleDom(this).getRuleDom(); } /** @@ -199,12 +180,9 @@ Xpp3Dom createInvokingRuleDom() * @param invokingRule * @return true when the rules contain the invoking rule. */ - final boolean isDefiningProject( final List rulesFromModel, final Xpp3Dom invokingRule ) - { - for ( final Xpp3Dom rule : rulesFromModel ) - { - if ( rule.equals( invokingRule ) ) - { + final boolean isDefiningProject(final List rulesFromModel, final Xpp3Dom invokingRule) { + for (final Xpp3Dom rule : rulesFromModel) { + if (rule.equals(invokingRule)) { return true; } } @@ -216,8 +194,7 @@ final boolean isDefiningProject( final List rulesFromModel, final Xpp3D * * @return configuration name. */ - final String getRuleName() - { + final String getRuleName() { return ruleName; } @@ -228,16 +205,14 @@ final String getRuleName() * @param build the build to inspect. * @return configuration of the rules, may be an empty list. */ - final List getRuleConfigurations( final Build build ) - { + final List getRuleConfigurations(final Build build) { final Map plugins = build.getPluginsAsMap(); - final List ruleConfigurationsForPlugins = getRuleConfigurations( plugins ); + final List ruleConfigurationsForPlugins = getRuleConfigurations(plugins); final PluginManagement pluginManagement = build.getPluginManagement(); - if ( pluginManagement != null ) - { + if (pluginManagement != null) { final Map pluginsFromManagementAsMap = pluginManagement.getPluginsAsMap(); - List ruleConfigurationsFromManagement = getRuleConfigurations( pluginsFromManagementAsMap ); - ruleConfigurationsForPlugins.addAll( ruleConfigurationsFromManagement ); + List ruleConfigurationsFromManagement = getRuleConfigurations(pluginsFromManagementAsMap); + ruleConfigurationsForPlugins.addAll(ruleConfigurationsFromManagement); } return ruleConfigurationsForPlugins; } @@ -248,28 +223,23 @@ final List getRuleConfigurations( final Build build ) * @param plugins * @return list of requirePropertyDiverges configurations. */ - List getRuleConfigurations( final Map plugins ) - { - if ( plugins.containsKey( MAVEN_ENFORCER_PLUGIN ) ) - { + List getRuleConfigurations(final Map plugins) { + if (plugins.containsKey(MAVEN_ENFORCER_PLUGIN)) { final List ruleConfigurations = new ArrayList<>(); - final Plugin enforcer = plugins.get( MAVEN_ENFORCER_PLUGIN ); - final Xpp3Dom configuration = ( Xpp3Dom ) enforcer.getConfiguration(); + final Plugin enforcer = plugins.get(MAVEN_ENFORCER_PLUGIN); + final Xpp3Dom configuration = (Xpp3Dom) enforcer.getConfiguration(); // add rules from plugin configuration - addRules( configuration, ruleConfigurations ); + addRules(configuration, ruleConfigurations); // add rules from all plugin execution configurations - for ( PluginExecution execution : enforcer.getExecutions() ) - { - addRules( ( Xpp3Dom ) execution.getConfiguration(), ruleConfigurations ); + for (PluginExecution execution : enforcer.getExecutions()) { + addRules((Xpp3Dom) execution.getConfiguration(), ruleConfigurations); } return ruleConfigurations; - } - else - { + } else { return new ArrayList<>(); } } @@ -282,17 +252,14 @@ List getRuleConfigurations( final Map plugins ) * @param ruleConfigurations * List to which the rules will be added. */ - private void addRules( final Xpp3Dom configuration, final List ruleConfigurations ) - { + private void addRules(final Xpp3Dom configuration, final List ruleConfigurations) { // may be null when rules are defined in pluginManagement during invocation // for plugin section and vice versa. - if ( configuration != null ) - { - final Xpp3Dom rules = configuration.getChild( "rules" ); - if ( rules != null ) - { - final List originalListFromPom = Arrays.asList( rules.getChildren( getRuleName() ) ); - ruleConfigurations.addAll( createRuleListWithNameSortedChildren( originalListFromPom ) ); + if (configuration != null) { + final Xpp3Dom rules = configuration.getChild("rules"); + if (rules != null) { + final List originalListFromPom = Arrays.asList(rules.getChildren(getRuleName())); + ruleConfigurations.addAll(createRuleListWithNameSortedChildren(originalListFromPom)); } } } @@ -304,23 +271,19 @@ private void addRules( final Xpp3Dom configuration, final List ruleConf * @param originalListFromPom order not specified * @return a list where children's member are alphabetically sorted. */ - private List createRuleListWithNameSortedChildren( final List originalListFromPom ) - { + private List createRuleListWithNameSortedChildren(final List originalListFromPom) { final List listWithSortedEntries = new ArrayList<>(originalListFromPom.size()); - for ( Xpp3Dom unsortedXpp3Dom : originalListFromPom ) - { - final Xpp3Dom sortedXpp3Dom = new Xpp3Dom( getRuleName() ); + for (Xpp3Dom unsortedXpp3Dom : originalListFromPom) { + final Xpp3Dom sortedXpp3Dom = new Xpp3Dom(getRuleName()); final SortedMap childrenMap = new TreeMap<>(); final Xpp3Dom[] children = unsortedXpp3Dom.getChildren(); - for ( Xpp3Dom child : children ) - { - childrenMap.put( child.getName(), child ); + for (Xpp3Dom child : children) { + childrenMap.put(child.getName(), child); } - for ( Xpp3Dom entry : childrenMap.values() ) - { - sortedXpp3Dom.addChild( entry ); + for (Xpp3Dom entry : childrenMap.values()) { + sortedXpp3Dom.addChild(entry); } - listWithSortedEntries.add( sortedXpp3Dom ); + listWithSortedEntries.add(sortedXpp3Dom); } return listWithSortedEntries; } @@ -333,9 +296,8 @@ private List createRuleListWithNameSortedChildren( final List * * @throws EnforcerRuleException */ - Object getPropertyValue( EnforcerRuleHelper helper ) throws EnforcerRuleException - { - return getPropertyValue( helper, property ); + Object getPropertyValue(EnforcerRuleHelper helper) throws EnforcerRuleException { + return getPropertyValue(helper, property); } /** @@ -346,15 +308,11 @@ Object getPropertyValue( EnforcerRuleHelper helper ) throws EnforcerRuleExceptio * @return the value of the property. * @throws EnforcerRuleException */ - Object getPropertyValue( EnforcerRuleHelper helper, final String propertyName ) throws EnforcerRuleException - { - try - { - return helper.evaluate( "${" + propertyName + "}" ); - } - catch ( ExpressionEvaluationException eee ) - { - throw new EnforcerRuleException( "Unable to evaluate property: " + propertyName, eee ); + Object getPropertyValue(EnforcerRuleHelper helper, final String propertyName) throws EnforcerRuleException { + try { + return helper.evaluate("${" + propertyName + "}"); + } catch (ExpressionEvaluationException eee) { + throw new EnforcerRuleException("Unable to evaluate property: " + propertyName, eee); } } @@ -366,15 +324,11 @@ Object getPropertyValue( EnforcerRuleHelper helper, final String propertyName ) * * @throws EnforcerRuleException */ - MavenProject getMavenProject( EnforcerRuleHelper helper ) throws EnforcerRuleException - { - try - { - return ( MavenProject ) helper.evaluate( "${project}" ); - } - catch ( ExpressionEvaluationException eee ) - { - throw new EnforcerRuleException( "Unable to get project.", eee ); + MavenProject getMavenProject(EnforcerRuleHelper helper) throws EnforcerRuleException { + try { + return (MavenProject) helper.evaluate("${project}"); + } catch (ExpressionEvaluationException eee) { + throw new EnforcerRuleException("Unable to get project.", eee); } } @@ -384,13 +338,11 @@ MavenProject getMavenProject( EnforcerRuleHelper helper ) throws EnforcerRuleExc * @param propValue value of the property from the project. * @throws EnforcerRuleException */ - void checkPropValueNotBlank( Object propValue ) throws EnforcerRuleException - { + void checkPropValueNotBlank(Object propValue) throws EnforcerRuleException { - if ( propValue == null || StringUtils.isBlank( propValue.toString() ) ) - { - throw new EnforcerRuleException( String.format( - "Property '%s' is required for this build and not defined in hierarchy at all.", property ) ); + if (propValue == null || StringUtils.isBlank(propValue.toString())) { + throw new EnforcerRuleException(String.format( + "Property '%s' is required for this build and not defined in hierarchy at all.", property)); } } @@ -401,14 +353,10 @@ void checkPropValueNotBlank( Object propValue ) throws EnforcerRuleException * @param errorMessage * @return */ - String createResultingErrorMessage( String errorMessage ) - { - if ( StringUtils.isNotEmpty( message ) ) - { + String createResultingErrorMessage(String errorMessage) { + if (StringUtils.isNotEmpty(message)) { return "Property '" + property + "' must be overridden:\n" + message; - } - else - { + } else { return errorMessage; } } @@ -417,43 +365,38 @@ String createResultingErrorMessage( String errorMessage ) /** * @param property the property to set */ - void setProperty( String property ) - { + void setProperty(String property) { this.property = property; } /** * @param regex the regex to set */ - void setRegex( String regex ) - { + void setRegex(String regex) { this.regex = regex; } - + /** * @param message the message to set */ - void setMessage( String message ) - { + void setMessage(String message) { this.message = message; } /** * Creates the DOM of the invoking rule, but returns the children alphabetically sorted. */ - private static class CreateInvokingRuleDom - { + private static class CreateInvokingRuleDom { private final Xpp3Dom ruleDom; private final SortedMap map = new TreeMap<>(); /** Real work is done in the constructor */ - public CreateInvokingRuleDom( RequirePropertyDiverges rule ) - { - ruleDom = new Xpp3Dom( rule.getRuleName() ); - addToMapWhenNotNull( rule.property, "property" ); - addToMapWhenNotNull( rule.message, "message" ); - addToMapWhenNotNull( rule.regex, "regex" ); + CreateInvokingRuleDom(RequirePropertyDiverges rule) { + ruleDom = new Xpp3Dom(rule.getRuleName()); + addToMapWhenNotNull(rule.property, "property"); + addToMapWhenNotNull(rule.message, "message"); + addToMapWhenNotNull(rule.regex, "regex"); addChildrenToRuleDom(); } @@ -466,48 +409,41 @@ public Xpp3Dom getRuleDom() { return ruleDom; } - private void addToMapWhenNotNull( String member, final String memberName ) - { - if ( member != null ) - { - final Xpp3Dom memberDom = new Xpp3Dom( memberName ); - memberDom.setValue( member ); - map.put( memberName, memberDom ); + private void addToMapWhenNotNull(String member, final String memberName) { + if (member != null) { + final Xpp3Dom memberDom = new Xpp3Dom(memberName); + memberDom.setValue(member); + map.put(memberName, memberDom); } } - - private void addChildrenToRuleDom() - { - for ( Xpp3Dom entry : map.values() ) - { - ruleDom.addChild( entry ); + + private void addChildrenToRuleDom() { + for (Xpp3Dom entry : map.values()) { + ruleDom.addChild(entry); } } } - - //********************* - + + // ********************* + /** * {@inheritDoc} */ - public String getCacheId() - { + public String getCacheId() { return "0"; } /** * {@inheritDoc} */ - public boolean isCacheable() - { + public boolean isCacheable() { return false; } /** * {@inheritDoc} */ - public boolean isResultValid( EnforcerRule cachedRule ) - { + public boolean isResultValid(EnforcerRule cachedRule) { return false; } } diff --git a/src/main/java/org/codehaus/mojo/enforcer/Dependency.java b/src/main/java/org/codehaus/mojo/enforcer/Dependency.java index e2630af0..d04ebec2 100644 --- a/src/main/java/org/codehaus/mojo/enforcer/Dependency.java +++ b/src/main/java/org/codehaus/mojo/enforcer/Dependency.java @@ -24,17 +24,16 @@ * * @version $Id: $ */ -public class Dependency -{ +public class Dependency { private String groupId; - + private String artifactId; - + private String classifier; - + private String type; - + /** * List of classes to ignore. Wildcard at the end accepted */ @@ -45,8 +44,7 @@ public class Dependency * * @return a {@link java.lang.String} object. */ - public String getGroupId() - { + public String getGroupId() { return groupId; } @@ -55,8 +53,7 @@ public String getGroupId() * * @param groupId a {@link java.lang.String} object. */ - public void setGroupId( String groupId ) - { + public void setGroupId(String groupId) { this.groupId = groupId; } @@ -65,8 +62,7 @@ public void setGroupId( String groupId ) * * @return a {@link java.lang.String} object. */ - public String getArtifactId() - { + public String getArtifactId() { return artifactId; } @@ -75,8 +71,7 @@ public String getArtifactId() * * @param artifactId a {@link java.lang.String} object. */ - public void setArtifactId( String artifactId ) - { + public void setArtifactId(String artifactId) { this.artifactId = artifactId; } @@ -85,8 +80,7 @@ public void setArtifactId( String artifactId ) * * @return a {@link java.lang.String} object. */ - public String getClassifier() - { + public String getClassifier() { return classifier; } @@ -95,8 +89,7 @@ public String getClassifier() * * @param classifier a {@link java.lang.String} object. */ - public void setClassifier( String classifier ) - { + public void setClassifier(String classifier) { this.classifier = classifier; } @@ -105,8 +98,7 @@ public void setClassifier( String classifier ) * * @return a {@link java.lang.String} object. */ - public String getType() - { + public String getType() { return type; } @@ -115,8 +107,7 @@ public String getType() * * @param type a {@link java.lang.String} object. */ - public void setType( String type ) - { + public void setType(String type) { this.type = type; } @@ -125,8 +116,7 @@ public void setType( String type ) * * @return an array of {@link java.lang.String} objects. */ - public String[] getIgnoreClasses() - { + public String[] getIgnoreClasses() { return ignoreClasses; } @@ -135,20 +125,17 @@ public String[] getIgnoreClasses() * * @param ignoreClasses an array of {@link java.lang.String} objects. */ - public void setIgnoreClasses( String[] ignoreClasses ) - { + public void setIgnoreClasses(String[] ignoreClasses) { this.ignoreClasses = ignoreClasses; } - + /** {@inheritDoc} */ @Override - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); - sb.append( groupId ).append( ':' ).append( artifactId ).append( ':' ).append( type ); - if ( classifier != null ) - { - sb.append( ':' ).append( classifier ); + sb.append(groupId).append(':').append(artifactId).append(':').append(type); + if (classifier != null) { + sb.append(':').append(classifier); } return sb.toString(); } diff --git a/src/main/java/org/freebsd/file/FileEncoding.java b/src/main/java/org/freebsd/file/FileEncoding.java index b016d5a5..26800752 100644 --- a/src/main/java/org/freebsd/file/FileEncoding.java +++ b/src/main/java/org/freebsd/file/FileEncoding.java @@ -4,28 +4,26 @@ /** * Tries to guess the encoding of the byte sequence. - * * Orignial code taken from https://github.com/file/file/blob/master/src/encoding.c */ -public class FileEncoding -{ +@SuppressWarnings("checkstyle:MemberName") +public class FileEncoding { private String type = "text/plain"; + private String code = "unknown"; - private String code_mime = "binary"; - public String getCodeMime() - { - return code_mime; + private String codeMime = "binary"; + + public String getCodeMime() { + return codeMime; } - public String getType() - { + public String getType() { return type; } - public String getCode() - { + public String getCode() { return code; } @@ -35,73 +33,50 @@ public String getCode() * * @return true if it could guess an encoding. */ - public boolean guessFileEncoding( byte[] buf ) - { + @SuppressWarnings("checkstyle:InnerAssignment") + public boolean guessFileEncoding(byte[] buf) { int nbytes = buf.length; - int ucs_type; + int ucsType; - if ( looks_ascii( buf, nbytes ) ) - { - if ( looks_utf7( buf, nbytes ) ) - { + if (looksAscii(buf, nbytes)) { + if (looksUtf7(buf, nbytes)) { code = "UTF-7 Unicode"; - code_mime = "utf-7"; - } - else - { + codeMime = "utf-7"; + } else { code = "ASCII"; - code_mime = "us-ascii"; + codeMime = "us-ascii"; } - } - else if ( looks_utf8_with_BOM( buf, nbytes ) ) - { + } else if (looksUtf8WithBOM(buf, nbytes)) { code = "UTF-8 Unicode (with BOM)"; - code_mime = "utf-8"; - } - else if ( looks_utf8( buf, nbytes ) > 1 ) - { + codeMime = "utf-8"; + } else if (looksUtf8(buf, nbytes) > 1) { code = "UTF-8 Unicode"; - code_mime = "utf-8"; - } - else if ( ( ucs_type = looks_ucs16( buf, nbytes ) ) != 0 ) - { - if ( ucs_type == 1 ) - { + codeMime = "utf-8"; + } else if ((ucsType = looksUcs16(buf, nbytes)) != 0) { + if (ucsType == 1) { code = "Little-endian UTF-16 Unicode"; - code_mime = "utf-16le"; - } - else - { + codeMime = "utf-16le"; + } else { code = "Big-endian UTF-16 Unicode"; - code_mime = "utf-16be"; + codeMime = "utf-16be"; } - } - else if ( looks_latin1( buf, nbytes ) ) - { + } else if (looksLatin1(buf, nbytes)) { code = "ISO-8859"; - code_mime = "iso-8859-1"; - } - else if ( looks_extended( buf, nbytes ) ) - { + codeMime = "iso-8859-1"; + } else if (looksExtended(buf, nbytes)) { code = "Non-ISO extended-ASCII"; - code_mime = "unknown-8bit"; - } - else - { - byte[] nbuf = from_ebcdic( buf, nbytes ); + codeMime = "unknown-8bit"; + } else { + byte[] nbuf = fromEbcdic(buf, nbytes); - if ( looks_ascii( nbuf, nbytes ) ) - { + if (looksAscii(nbuf, nbytes)) { code = "EBCDIC"; - code_mime = "ebcdic"; - } - else if ( looks_latin1( nbuf, nbytes ) ) - { + codeMime = "ebcdic"; + } else if (looksLatin1(nbuf, nbytes)) { code = "International EBCDIC"; - code_mime = "ebcdic"; - } - else - { /* Doesn't look like text at all */ + codeMime = "ebcdic"; + } else { + /* Doesn't look like text at all */ type = "binary"; return false; } @@ -162,14 +137,17 @@ else if ( looks_latin1( nbuf, nbytes ) ) * consider to be printing characters. */ private static final byte F = 0; /* character never appears in text */ + private static final byte T = 1; /* character appears in plain ASCII text */ + private static final byte I = 2; /* character appears in ISO-8859 text */ + private static final byte X = 3; /* character appears in non-ISO extended ASCII (Mac, IBM PC) */ private byte[] text_chars = { - /* BEL BS HT LF VT FF CR */ + /* BEL BS HT LF VT FF CR */ F, F, F, F, F, F, F, T, T, T, T, T, T, T, F, F, /* 0x0X */ - /* ESC */ + /* ESC */ F, F, F, F, F, F, F, F, F, F, F, T, F, F, F, F, /* 0x1X */ T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, /* 0x2X */ T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, /* 0x3X */ @@ -177,7 +155,7 @@ else if ( looks_latin1( nbuf, nbytes ) ) T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, /* 0x5X */ T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, /* 0x6X */ T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, F, /* 0x7X */ - /* NEL */ + /* NEL */ X, X, X, X, X, T, X, X, X, X, X, X, X, X, X, X, /* 0x8X */ X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, /* 0x9X */ I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, /* 0xaX */ @@ -188,26 +166,20 @@ else if ( looks_latin1( nbuf, nbytes ) ) I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I /* 0xfX */ }; - private boolean looks_ascii( byte[] buf, int nbytes ) - { - for ( int i = 0; i < nbytes; i++ ) - { - if ( text_chars[ unsignedByte( buf[ i ] ) ] != T ) - { + private boolean looksAscii(byte[] buf, int nbytes) { + for (int i = 0; i < nbytes; i++) { + if (text_chars[unsignedByte(buf[i])] != T) { return false; } } return true; } - private boolean looks_latin1( byte[] buf, int nbytes ) - { - for ( int i = 0; i < nbytes; i++ ) - { - int t = text_chars[ unsignedByte( buf[ i ] ) ]; + private boolean looksLatin1(byte[] buf, int nbytes) { + for (int i = 0; i < nbytes; i++) { + int t = text_chars[unsignedByte(buf[i])]; - if ( t != T && t != I ) - { + if (t != T && t != I) { return false; } } @@ -215,13 +187,10 @@ private boolean looks_latin1( byte[] buf, int nbytes ) return true; } - private boolean looks_extended( byte[] buf, int nbytes ) - { - for ( int i = 0; i < nbytes; i++ ) - { - int t = text_chars[ unsignedByte( buf[ i ] ) ]; - if ( t != T && t != I && t != X ) - { + private boolean looksExtended(byte[] buf, int nbytes) { + for (int i = 0; i < nbytes; i++) { + int t = text_chars[unsignedByte(buf[i])]; + if (t != T && t != I && t != X) { return false; } } @@ -236,69 +205,54 @@ private boolean looks_extended( byte[] buf, int nbytes ) * 1: 7-bit text * 2: definitely UTF-8 text (valid high-bit set bytes) */ - protected int looks_utf8( byte[] buf, int nbytes ) - { + protected int looksUtf8(byte[] buf, int nbytes) { boolean gotone = false; - for ( int i = 0; i < nbytes; i++ ) - { - if ( ( unsignedByte( buf[ i ] ) & 0x80 ) == 0 ) - { /* 0xxxxxxx is plain ASCII */ + for (int i = 0; i < nbytes; i++) { + if ((unsignedByte(buf[i]) & 0x80) == 0) { + /* 0xxxxxxx is plain ASCII */ /* - * Even if the whole file is valid UTF-8 sequences, - * still reject it if it uses weird control characters. - */ + * Even if the whole file is valid UTF-8 sequences, + * still reject it if it uses weird control characters. + */ - if ( text_chars[ unsignedByte( buf[ i ] ) ] != T ) - { + if (text_chars[unsignedByte(buf[i])] != T) { return 0; } - } - else - { - if ( ( unsignedByte( buf[ i ] ) & 0x40 ) == 0 ) - { /* 10xxxxxx never 1st byte */ + } else { + if ((unsignedByte(buf[i]) & 0x40) == 0) { + /* 10xxxxxx never 1st byte */ return -1; - } - else - { /* 11xxxxxx begins UTF-8 */ + } else { + /* 11xxxxxx begins UTF-8 */ int following; - if ( ( unsignedByte( buf[ i ] ) & 0x20 ) == 0 ) - { /* 110xxxxx */ + if ((unsignedByte(buf[i]) & 0x20) == 0) { + /* 110xxxxx */ following = 1; - } - else if ( ( unsignedByte( buf[ i ] ) & 0x10 ) == 0 ) - { /* 1110xxxx */ + } else if ((unsignedByte(buf[i]) & 0x10) == 0) { + /* 1110xxxx */ following = 2; - } - else if ( ( unsignedByte( buf[ i ] ) & 0x08 ) == 0 ) - { /* 11110xxx */ + } else if ((unsignedByte(buf[i]) & 0x08) == 0) { + /* 11110xxx */ following = 3; - } - else if ( ( unsignedByte( buf[ i ] ) & 0x04 ) == 0 ) - { /* 111110xx */ + } else if ((unsignedByte(buf[i]) & 0x04) == 0) { + /* 111110xx */ following = 4; - } - else if ( ( unsignedByte( buf[ i ] ) & 0x02 ) == 0 ) - { /* 1111110x */ + } else if ((unsignedByte(buf[i]) & 0x02) == 0) { + /* 1111110x */ following = 5; - } - else - { + } else { return -1; } - for ( int n = 0; n < following; n++ ) - { + for (int n = 0; n < following; n++) { i++; - if ( i >= nbytes ) - { + if (i >= nbytes) { return gotone ? 2 : 1; } - if ( ( unsignedByte( buf[ i ] ) & 0x80 ) == 0 || ( unsignedByte( buf[ i ] ) & 0x40 ) > 0 ) - { + if ((unsignedByte(buf[i]) & 0x80) == 0 || (unsignedByte(buf[i]) & 0x40) > 0) { return -1; } } @@ -315,21 +269,19 @@ else if ( ( unsignedByte( buf[ i ] ) & 0x02 ) == 0 ) * BOM, return -1; otherwise return the result of looks_utf8 on the * rest of the text. */ - private boolean looks_utf8_with_BOM( byte[] buf, int nbytes ) - { - if ( nbytes > 3 && unsignedByte( buf[ 0 ] ) == 0xef && unsignedByte( buf[ 1 ] ) == 0xbb && unsignedByte( buf[ 2 ] ) == 0xbf ) - { - return looks_utf8( Arrays.copyOfRange( buf, 3, nbytes ), nbytes - 3 ) > 0; + private boolean looksUtf8WithBOM(byte[] buf, int nbytes) { + if (nbytes > 3 + && unsignedByte(buf[0]) == 0xef + && unsignedByte(buf[1]) == 0xbb + && unsignedByte(buf[2]) == 0xbf) { + return looksUtf8(Arrays.copyOfRange(buf, 3, nbytes), nbytes - 3) > 0; } return false; } - private boolean looks_utf7( byte[] buf, int nbytes ) - { - if ( nbytes > 4 && buf[ 0 ] == '+' && buf[ 1 ] == '/' && buf[ 2 ] == 'v' ) - { - switch ( buf[ 3 ] ) - { + private boolean looksUtf7(byte[] buf, int nbytes) { + if (nbytes > 4 && buf[0] == '+' && buf[1] == '/' && buf[2] == 'v') { + switch (buf[3]) { case '8': case '9': case '+': @@ -342,53 +294,39 @@ private boolean looks_utf7( byte[] buf, int nbytes ) return false; } - private int looks_ucs16( byte[] buf, int nbytes ) - { + private int looksUcs16(byte[] buf, int nbytes) { int bigend; int i; - char[] ubuf = new char[ nbytes ]; + char[] ubuf = new char[nbytes]; - if ( nbytes < 2 ) - { + if (nbytes < 2) { return 0; } - if ( unsignedByte( buf[ 0 ] ) == 0xff && unsignedByte( buf[ 1 ] ) == 0xfe ) - { + if (unsignedByte(buf[0]) == 0xff && unsignedByte(buf[1]) == 0xfe) { bigend = 0; - } - else - { - if ( unsignedByte( buf[ 0 ] ) == 0xfe && unsignedByte( buf[ 1 ] ) == 0xff ) - { + } else { + if (unsignedByte(buf[0]) == 0xfe && unsignedByte(buf[1]) == 0xff) { bigend = 1; - } - else - { + } else { return 0; } } int ulen = 0; - for ( i = 2; i + 1 < nbytes; i += 2 ) - { - if ( bigend == 1 ) - { - ubuf[ ( ulen )++ ] = (char) ( unsignedByte( buf[ i + 1 ] ) + 256 * buf[ i ] ); - } - else - { - ubuf[ ( ulen )++ ] = (char) ( unsignedByte( buf[ i ] ) + 256 * buf[ i + 1 ] ); + for (i = 2; i + 1 < nbytes; i += 2) { + if (bigend == 1) { + ubuf[(ulen)++] = (char) (unsignedByte(buf[i + 1]) + 256 * buf[i]); + } else { + ubuf[(ulen)++] = (char) (unsignedByte(buf[i]) + 256 * buf[i + 1]); } - if ( ubuf[ ulen - 1 ] == 0xfffe ) - { + if (ubuf[ulen - 1] == 0xfffe) { return 0; } - if ( ubuf[ ulen - 1 ] < 128 && text_chars[ubuf[ ulen - 1 ]] != T ) - { + if (ubuf[ulen - 1] < 128 && text_chars[ubuf[ulen - 1]] != T) { return 0; } } @@ -417,7 +355,7 @@ private int looks_ucs16( byte[] buf, int nbytes ) * This is sufficient to allow us to identify EBCDIC text and to distinguish * between old-style and internationalized examples of text. */ - private static final char[] ebcdic_to_ascii = { // + private static final char[] EBCDIC_TO_ASCII = { // 0, 1, 2, 3, 156, 9, 134, 127, 151, 141, 142, 11, 12, 13, 14, 15, // 16, 17, 18, 19, 157, 133, 8, 135, 24, 25, 146, 143, 28, 29, 30, 31, // 128, 129, 130, 131, 132, 10, 23, 27, 136, 137, 138, 139, 140, 5, 6, 7, // @@ -449,7 +387,7 @@ private int looks_ucs16( byte[] buf, int nbytes ) * If this table is used instead of the above one, some of the special * cases for the NEL character can be taken out of the code. */ - private static final char[] ebcdic_1047_to_8859 = { // + private static final char[] EBCDIC_1047_TO_8859 = { // 0x00, 0x01, 0x02, 0x03, 0x9C, 0x09, 0x86, 0x7F, 0x97, 0x8D, 0x8E, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, // 0x10, 0x11, 0x12, 0x13, 0x9D, 0x0A, 0x08, 0x87, 0x18, 0x19, 0x92, 0x8F, 0x1C, 0x1D, 0x1E, 0x1F, // 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x17, 0x1B, 0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x05, 0x06, 0x07, // @@ -471,18 +409,15 @@ private int looks_ucs16( byte[] buf, int nbytes ) /* * Copy buf[0 ... nbytes-1] into out[], translating EBCDIC to ASCII. */ - private byte[] from_ebcdic( byte[] buf, int nbytes ) - { - byte[] out = new byte[ nbytes ]; - for ( int i = 0; i < nbytes; i++ ) - { - out[ i ] = (byte) ebcdic_to_ascii[ unsignedByte( buf[ i ] ) ]; + private byte[] fromEbcdic(byte[] buf, int nbytes) { + byte[] out = new byte[nbytes]; + for (int i = 0; i < nbytes; i++) { + out[i] = (byte) EBCDIC_TO_ASCII[unsignedByte(buf[i])]; } return out; } - private int unsignedByte( byte value ) - { + private int unsignedByte(byte value) { return value & 0xFF; } -} \ No newline at end of file +} diff --git a/src/test/java/org/apache/maven/plugins/enforcer/AbstractRequireRolesTest.java b/src/test/java/org/apache/maven/plugins/enforcer/AbstractRequireRolesTest.java index c447b296..29316ff7 100644 --- a/src/test/java/org/apache/maven/plugins/enforcer/AbstractRequireRolesTest.java +++ b/src/test/java/org/apache/maven/plugins/enforcer/AbstractRequireRolesTest.java @@ -22,36 +22,32 @@ import org.junit.Test; -public class AbstractRequireRolesTest -{ - private final String CSV_TO_SPLIT = "a,b,c"; - private final String CSV_WITH_SPACES_TO_SPLIT = " a, b ,c "; +public class AbstractRequireRolesTest { + private static final String CSV_TO_SPLIT = "a,b,c"; + private static final String CSV_WITH_SPACES_TO_SPLIT = " a, b ,c "; @Test - public void testCsvSplitSize() - { - Set values = AbstractRequireRoles.splitCsvToSet( CSV_TO_SPLIT ); + public void testCsvSplitSize() { + Set values = AbstractRequireRoles.splitCsvToSet(CSV_TO_SPLIT); assert values.size() == 3; } @Test - public void testCsvSplitExpectedElements() - { - Set values = AbstractRequireRoles.splitCsvToSet( CSV_TO_SPLIT ); + public void testCsvSplitExpectedElements() { + Set values = AbstractRequireRoles.splitCsvToSet(CSV_TO_SPLIT); - assert values.contains( "a" ); - assert values.contains( "b" ); - assert values.contains( "c" ); + assert values.contains("a"); + assert values.contains("b"); + assert values.contains("c"); } @Test - public void testCsvSplitTrimsValues() - { - Set values = AbstractRequireRoles.splitCsvToSet( CSV_WITH_SPACES_TO_SPLIT ); + public void testCsvSplitTrimsValues() { + Set values = AbstractRequireRoles.splitCsvToSet(CSV_WITH_SPACES_TO_SPLIT); - assert values.contains( "a" ); - assert values.contains( "b" ); - assert values.contains( "c" ); + assert values.contains("a"); + assert values.contains("b"); + assert values.contains("c"); } } diff --git a/src/test/java/org/apache/maven/plugins/enforcer/ArtifactBuilder.java b/src/test/java/org/apache/maven/plugins/enforcer/ArtifactBuilder.java index 436a57f9..8e5532ba 100644 --- a/src/test/java/org/apache/maven/plugins/enforcer/ArtifactBuilder.java +++ b/src/test/java/org/apache/maven/plugins/enforcer/ArtifactBuilder.java @@ -30,69 +30,57 @@ /** * Test helper for working with {@link Artifact}s. */ -public class ArtifactBuilder -{ +public class ArtifactBuilder { private String groupId = "groupId"; private String artifactId = "artifactId"; - private VersionRange versionRange = VersionRange.createFromVersion( "1.0" ); + private VersionRange versionRange = VersionRange.createFromVersion("1.0"); private String scope = "scope"; private String type = "type"; private String classifier = "classifier"; private File fileOrDirectory = getAnyFile(); - public static ArtifactBuilder newBuilder() - { + public static ArtifactBuilder newBuilder() { return new ArtifactBuilder(); } - public ArtifactBuilder withVersion( String version ) - { - versionRange = VersionRange.createFromVersion( version ); + public ArtifactBuilder withVersion(String version) { + versionRange = VersionRange.createFromVersion(version); return this; } - public ArtifactBuilder withType( String type ) - { + public ArtifactBuilder withType(String type) { this.type = type; return this; } - public ArtifactBuilder withAnyDirectory() - { + public ArtifactBuilder withAnyDirectory() { fileOrDirectory = getAnyDirectory(); return this; } - public ArtifactBuilder withFileOrDirectory( File directory ) - { + public ArtifactBuilder withFileOrDirectory(File directory) { fileOrDirectory = directory; return this; } - public Artifact build() - { - Artifact artifact = new DefaultArtifact( groupId, artifactId, versionRange, scope, type, classifier, null ); - artifact.setFile( fileOrDirectory ); + public Artifact build() { + Artifact artifact = new DefaultArtifact(groupId, artifactId, versionRange, scope, type, classifier, null); + artifact.setFile(fileOrDirectory); return artifact; } - private static File getAnyFile() - { + private static File getAnyFile() { // the actual file isn't important, just so long as it exists - URL url = ArtifactBuilder.class.getResource( "/utf8.txt" ); - try - { - return new File( url.toURI() ); - } - catch ( URISyntaxException exception ) - { - throw new RuntimeException( exception ); + URL url = ArtifactBuilder.class.getResource("/utf8.txt"); + try { + return new File(url.toURI()); + } catch (URISyntaxException exception) { + throw new RuntimeException(exception); } } - private File getAnyDirectory() - { + private File getAnyDirectory() { return getAnyFile().getParentFile(); } } diff --git a/src/test/java/org/apache/maven/plugins/enforcer/ClassFileHelper.java b/src/test/java/org/apache/maven/plugins/enforcer/ClassFileHelper.java index cb92878c..e7972ff6 100644 --- a/src/test/java/org/apache/maven/plugins/enforcer/ClassFileHelper.java +++ b/src/test/java/org/apache/maven/plugins/enforcer/ClassFileHelper.java @@ -30,62 +30,54 @@ /** * Test utility to make writing tests with {@link ClassFile}s easier. */ -public class ClassFileHelper -{ +public class ClassFileHelper { private static int uniqueId = 0; private final TemporaryFolder temporaryFolder; - public ClassFileHelper( TemporaryFolder temporaryFolder ) - { + public ClassFileHelper(TemporaryFolder temporaryFolder) { this.temporaryFolder = temporaryFolder; } - public ClassFile createWithContent( String pathToClassFile, String fileContents ) throws IOException - { + public ClassFile createWithContent(String pathToClassFile, String fileContents) throws IOException { uniqueId++; - String uniqueIdStr = Integer.toString( uniqueId ); + String uniqueIdStr = Integer.toString(uniqueId); - File tempDirectory = createTempDirectory( uniqueIdStr ); - createClassFile( tempDirectory, pathToClassFile, fileContents ); + File tempDirectory = createTempDirectory(uniqueIdStr); + createClassFile(tempDirectory, pathToClassFile, fileContents); Artifact artifact = ArtifactBuilder.newBuilder() - .withFileOrDirectory( tempDirectory ) - .withVersion( uniqueIdStr ) - .withType( "some type that isn't 'jar' so our code assumes it's a directory" ) - .build(); + .withFileOrDirectory(tempDirectory) + .withVersion(uniqueIdStr) + .withType("some type that isn't 'jar' so our code assumes it's a directory") + .build(); - return new ClassFile( pathToClassFile, artifact, - () -> Files.newInputStream( tempDirectory.toPath().resolve( pathToClassFile ) ) ); + return new ClassFile( + pathToClassFile, + artifact, + () -> Files.newInputStream(tempDirectory.toPath().resolve(pathToClassFile))); } - private File createTempDirectory( String uniqueIdStr ) - { - try - { - return temporaryFolder.newFolder( uniqueIdStr ); - } - catch ( IOException exception ) - { - throw new RuntimeException( "unable to create temporary folder", exception ); + private File createTempDirectory(String uniqueIdStr) { + try { + return temporaryFolder.newFolder(uniqueIdStr); + } catch (IOException exception) { + throw new RuntimeException("unable to create temporary folder", exception); } } - private void createClassFile( File directory, String pathToClassFile, String fileContents ) throws IOException - { - File file = new File( directory, pathToClassFile ); + private void createClassFile(File directory, String pathToClassFile, String fileContents) throws IOException { + File file = new File(directory, pathToClassFile); boolean madeDirs = file.getParentFile().mkdirs(); - if ( !madeDirs ) - { - throw new RuntimeException( "unable to create parent directories for " + file ); + if (!madeDirs) { + throw new RuntimeException("unable to create parent directories for " + file); } file.createNewFile(); - try ( FileWriter writer = new FileWriter( file ) ) - { - writer.write( fileContents ); + try (FileWriter writer = new FileWriter(file)) { + writer.write(fileContents); } } } diff --git a/src/test/java/org/apache/maven/plugins/enforcer/ClassFileTest.java b/src/test/java/org/apache/maven/plugins/enforcer/ClassFileTest.java index 9f2f4b04..dd11bd01 100644 --- a/src/test/java/org/apache/maven/plugins/enforcer/ClassFileTest.java +++ b/src/test/java/org/apache/maven/plugins/enforcer/ClassFileTest.java @@ -6,33 +6,30 @@ import static org.junit.Assert.assertEquals; -public class ClassFileTest -{ - private static final String PATH_TO_CLASS_FILE = ClassFileTest.class.getName().replace( '.', '/' ) + ".class"; +public class ClassFileTest { + private static final String PATH_TO_CLASS_FILE = + ClassFileTest.class.getName().replace('.', '/') + ".class"; @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); - private final ClassFileHelper classFileHelper = new ClassFileHelper( tempFolder ); + private final ClassFileHelper classFileHelper = new ClassFileHelper(tempFolder); @Test - public void getHashComputesHashOfFile() throws Exception - { - ClassFile classFile = classFileHelper.createWithContent( PATH_TO_CLASS_FILE, "the content of the file" ); + public void getHashComputesHashOfFile() throws Exception { + ClassFile classFile = classFileHelper.createWithContent(PATH_TO_CLASS_FILE, "the content of the file"); - assertEquals( "7e47820975c51a762e63caa95cc76e45", classFile.getHash() ); + assertEquals("7e47820975c51a762e63caa95cc76e45", classFile.getHash()); } @Test - public void getHashReturnsConsistentHashWhenInvokedTwice() throws Exception - { - ClassFile classFile = classFileHelper.createWithContent( PATH_TO_CLASS_FILE, "file content" ); + public void getHashReturnsConsistentHashWhenInvokedTwice() throws Exception { + ClassFile classFile = classFileHelper.createWithContent(PATH_TO_CLASS_FILE, "file content"); String hash1 = classFile.getHash(); String hash2 = classFile.getHash(); - assertEquals( "d10b4c3ff123b26dc068d43a8bef2d23", hash1 ); - assertEquals( hash1, hash2 ); + assertEquals("d10b4c3ff123b26dc068d43a8bef2d23", hash1); + assertEquals(hash1, hash2); } - } diff --git a/src/test/java/org/apache/maven/plugins/enforcer/ClassesWithSameNameTest.java b/src/test/java/org/apache/maven/plugins/enforcer/ClassesWithSameNameTest.java index ddb9f393..5b2dda5e 100644 --- a/src/test/java/org/apache/maven/plugins/enforcer/ClassesWithSameNameTest.java +++ b/src/test/java/org/apache/maven/plugins/enforcer/ClassesWithSameNameTest.java @@ -34,11 +34,12 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -public class ClassesWithSameNameTest -{ +public class ClassesWithSameNameTest { /** logging thresholds are: DEBUG=0, INFO=1, WARNING=2, ERROR=3, FATAL ERROR=4, DISABLED=5 */ private static final int LOGGING_THRESHOLD = 5; - private static final String PATH_TO_CLASS_FILE = ClassesWithSameNameTest.class.getName().replace( '.', '/' ) + ".class"; + + private static final String PATH_TO_CLASS_FILE = + ClassesWithSameNameTest.class.getName().replace('.', '/') + ".class"; /** this is an alias to make the code read better */ private static final boolean DETERMINE_DUPLICATES_BY_NAME_AND_BYTECODE = true; @@ -46,7 +47,7 @@ public class ClassesWithSameNameTest /** this is an alias to make the code read better */ private static final boolean DETERMINE_DUPLICATES_BY_NAME = false; - private static final Log log = new DefaultLog( new ConsoleLogger( LOGGING_THRESHOLD, "test" ) ); + private static final Log LOG = new DefaultLog(new ConsoleLogger(LOGGING_THRESHOLD, "test")); @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @@ -54,9 +55,8 @@ public class ClassesWithSameNameTest private ClassFileHelper classFileHelper; @Before - public void beforeEachTest() - { - classFileHelper = new ClassFileHelper( temporaryFolder ); + public void beforeEachTest() { + classFileHelper = new ClassFileHelper(temporaryFolder); } /** @@ -65,38 +65,35 @@ public void beforeEachTest() * files are exactly the same. */ @Test - public void hasDuplicatesShouldReturnTrueWhenClassNameIsDuplicate() throws Exception - { - ClassFile classFile1 = classFileHelper.createWithContent( PATH_TO_CLASS_FILE, "" ); - ClassFile classFile2 = classFileHelper.createWithContent( PATH_TO_CLASS_FILE, "" ); - ClassesWithSameName classesWithSameName = new ClassesWithSameName( log, classFile1, classFile2 ); + public void hasDuplicatesShouldReturnTrueWhenClassNameIsDuplicate() throws Exception { + ClassFile classFile1 = classFileHelper.createWithContent(PATH_TO_CLASS_FILE, ""); + ClassFile classFile2 = classFileHelper.createWithContent(PATH_TO_CLASS_FILE, ""); + ClassesWithSameName classesWithSameName = new ClassesWithSameName(LOG, classFile1, classFile2); - boolean result = classesWithSameName.hasDuplicates( DETERMINE_DUPLICATES_BY_NAME ); + boolean result = classesWithSameName.hasDuplicates(DETERMINE_DUPLICATES_BY_NAME); - assertTrue( result ); + assertTrue(result); } @Test - public void hasDuplicatesShouldReturnFalseWhenClassNameIsDuplicateButBytecodeIsIdentical() throws Exception - { - ClassFile classFile1 = classFileHelper.createWithContent( PATH_TO_CLASS_FILE, "content matches in both" ); - ClassFile classFile2 = classFileHelper.createWithContent( PATH_TO_CLASS_FILE, "content matches in both" ); - ClassesWithSameName classesWithSameName = new ClassesWithSameName( log, classFile1, classFile2 ); + public void hasDuplicatesShouldReturnFalseWhenClassNameIsDuplicateButBytecodeIsIdentical() throws Exception { + ClassFile classFile1 = classFileHelper.createWithContent(PATH_TO_CLASS_FILE, "content matches in both"); + ClassFile classFile2 = classFileHelper.createWithContent(PATH_TO_CLASS_FILE, "content matches in both"); + ClassesWithSameName classesWithSameName = new ClassesWithSameName(LOG, classFile1, classFile2); - boolean result = classesWithSameName.hasDuplicates( DETERMINE_DUPLICATES_BY_NAME_AND_BYTECODE ); + boolean result = classesWithSameName.hasDuplicates(DETERMINE_DUPLICATES_BY_NAME_AND_BYTECODE); - assertFalse( result ); + assertFalse(result); } @Test - public void hasDuplicatesShouldReturnFalseWhenClassHasNoDuplicates() throws Exception - { - ClassFile classFile = classFileHelper.createWithContent( PATH_TO_CLASS_FILE, "" ); - ClassesWithSameName classesWithSameName = new ClassesWithSameName( log, classFile ); + public void hasDuplicatesShouldReturnFalseWhenClassHasNoDuplicates() throws Exception { + ClassFile classFile = classFileHelper.createWithContent(PATH_TO_CLASS_FILE, ""); + ClassesWithSameName classesWithSameName = new ClassesWithSameName(LOG, classFile); - boolean result = classesWithSameName.hasDuplicates( DETERMINE_DUPLICATES_BY_NAME ); + boolean result = classesWithSameName.hasDuplicates(DETERMINE_DUPLICATES_BY_NAME); - assertFalse( result ); + assertFalse(result); } /** @@ -108,15 +105,14 @@ public void hasDuplicatesShouldReturnFalseWhenClassHasNoDuplicates() throws Exce * bytecode). */ @Test - public void hasDuplicatesShouldReturnTrueWhenClassNameIsDuplicateButBytecodeDiffers() throws Exception - { - ClassFile classFile1 = classFileHelper.createWithContent( PATH_TO_CLASS_FILE, "1" ); - ClassFile classFile2 = classFileHelper.createWithContent( PATH_TO_CLASS_FILE, "2" ); - ClassesWithSameName classesWithSameName = new ClassesWithSameName( log, classFile1, classFile2 ); + public void hasDuplicatesShouldReturnTrueWhenClassNameIsDuplicateButBytecodeDiffers() throws Exception { + ClassFile classFile1 = classFileHelper.createWithContent(PATH_TO_CLASS_FILE, "1"); + ClassFile classFile2 = classFileHelper.createWithContent(PATH_TO_CLASS_FILE, "2"); + ClassesWithSameName classesWithSameName = new ClassesWithSameName(LOG, classFile1, classFile2); - boolean result = classesWithSameName.hasDuplicates( DETERMINE_DUPLICATES_BY_NAME ); + boolean result = classesWithSameName.hasDuplicates(DETERMINE_DUPLICATES_BY_NAME); - assertTrue( result ); + assertTrue(result); } /** @@ -127,30 +123,28 @@ public void hasDuplicatesShouldReturnTrueWhenClassNameIsDuplicateButBytecodeDiff * We set the test up so it finds duplicates only if the bytecode differs. */ @Test - public void hasDuplicatesShouldReturnFalseWhenClassNameIsDuplicateAndBytecodeDiffers() throws Exception - { - ClassFile classFile1 = classFileHelper.createWithContent( PATH_TO_CLASS_FILE, "1" ); - ClassFile classFile2 = classFileHelper.createWithContent( PATH_TO_CLASS_FILE, "2" ); - ClassesWithSameName classesWithSameName = new ClassesWithSameName( log, classFile1, classFile2 ); + public void hasDuplicatesShouldReturnFalseWhenClassNameIsDuplicateAndBytecodeDiffers() throws Exception { + ClassFile classFile1 = classFileHelper.createWithContent(PATH_TO_CLASS_FILE, "1"); + ClassFile classFile2 = classFileHelper.createWithContent(PATH_TO_CLASS_FILE, "2"); + ClassesWithSameName classesWithSameName = new ClassesWithSameName(LOG, classFile1, classFile2); - boolean result = classesWithSameName.hasDuplicates( DETERMINE_DUPLICATES_BY_NAME_AND_BYTECODE ); + boolean result = classesWithSameName.hasDuplicates(DETERMINE_DUPLICATES_BY_NAME_AND_BYTECODE); - assertTrue( result ); + assertTrue(result); } /** * This tests the normal condition where we just output the class file path. */ @Test - public void toOutputStringOutputsPlainArtifactWhenJustNamesAreDuplicate() throws Exception - { - ClassFile classFile1 = classFileHelper.createWithContent( PATH_TO_CLASS_FILE, "" ); - ClassFile classFile2 = classFileHelper.createWithContent( PATH_TO_CLASS_FILE, "" ); - ClassesWithSameName classesWithSameName = new ClassesWithSameName( log, classFile1, classFile2 ); + public void toOutputStringOutputsPlainArtifactWhenJustNamesAreDuplicate() throws Exception { + ClassFile classFile1 = classFileHelper.createWithContent(PATH_TO_CLASS_FILE, ""); + ClassFile classFile2 = classFileHelper.createWithContent(PATH_TO_CLASS_FILE, ""); + ClassesWithSameName classesWithSameName = new ClassesWithSameName(LOG, classFile1, classFile2); - String actualOutput = classesWithSameName.toOutputString( DETERMINE_DUPLICATES_BY_NAME ); + String actualOutput = classesWithSameName.toOutputString(DETERMINE_DUPLICATES_BY_NAME); - assertEquals( PATH_TO_CLASS_FILE, actualOutput ); + assertEquals(PATH_TO_CLASS_FILE, actualOutput); } /** @@ -159,17 +153,16 @@ public void toOutputStringOutputsPlainArtifactWhenJustNamesAreDuplicate() throws * determine which artifacts they can ignore when fix the BanDuplicateClasses error. */ @Test - public void toOutputStringOutputsTwoArtifactsWhereBytecodeIsExactMatch() throws Exception - { - ClassFile classFile1 = classFileHelper.createWithContent( PATH_TO_CLASS_FILE, "content matches in both" ); - ClassFile classFile2 = classFileHelper.createWithContent( PATH_TO_CLASS_FILE, "content matches in both" ); - ClassesWithSameName classesWithSameName = new ClassesWithSameName( log, classFile1, classFile2 ); + public void toOutputStringOutputsTwoArtifactsWhereBytecodeIsExactMatch() throws Exception { + ClassFile classFile1 = classFileHelper.createWithContent(PATH_TO_CLASS_FILE, "content matches in both"); + ClassFile classFile2 = classFileHelper.createWithContent(PATH_TO_CLASS_FILE, "content matches in both"); + ClassesWithSameName classesWithSameName = new ClassesWithSameName(LOG, classFile1, classFile2); - String actualOutput = classesWithSameName.toOutputString( DETERMINE_DUPLICATES_BY_NAME_AND_BYTECODE ); + String actualOutput = classesWithSameName.toOutputString(DETERMINE_DUPLICATES_BY_NAME_AND_BYTECODE); - String expectedOutput = PATH_TO_CLASS_FILE + " -- the bytecode exactly matches in these: " + - classFile1.getArtifactThisClassWasFoundIn() + " and " + classFile2.getArtifactThisClassWasFoundIn(); - assertEquals( expectedOutput, actualOutput ); + String expectedOutput = PATH_TO_CLASS_FILE + " -- the bytecode exactly matches in these: " + + classFile1.getArtifactThisClassWasFoundIn() + " and " + classFile2.getArtifactThisClassWasFoundIn(); + assertEquals(expectedOutput, actualOutput); } /** @@ -179,92 +172,88 @@ public void toOutputStringOutputsTwoArtifactsWhereBytecodeIsExactMatch() throws * 1 and 2 don't match 3 and 4. */ @Test - public void toOutputStringOutputsFourArtifactsWhereBytecodeIsExactMatchInTwoAndExactMatchInOtherTwo() throws Exception - { - ClassFile classFile1 = classFileHelper.createWithContent( PATH_TO_CLASS_FILE, "file content of 1 and 2" ); - ClassFile classFile2 = classFileHelper.createWithContent( PATH_TO_CLASS_FILE, "file content of 1 and 2" ); - ClassFile classFile3 = classFileHelper.createWithContent( PATH_TO_CLASS_FILE, "file content of 3 and 4" ); - ClassFile classFile4 = classFileHelper.createWithContent( PATH_TO_CLASS_FILE, "file content of 3 and 4" ); - ClassesWithSameName classesWithSameName = new ClassesWithSameName( log, classFile1, classFile2, classFile3, classFile4 ); - - String actualOutput = classesWithSameName.toOutputString( DETERMINE_DUPLICATES_BY_NAME_AND_BYTECODE ); - - String expectedOutput = PATH_TO_CLASS_FILE + " -- the bytecode exactly matches in these: " + - classFile1.getArtifactThisClassWasFoundIn() + " and " + classFile2.getArtifactThisClassWasFoundIn() + - "; and more exact matches in these: " + - classFile3.getArtifactThisClassWasFoundIn() + " and " + classFile4.getArtifactThisClassWasFoundIn(); - assertEquals( expectedOutput, actualOutput ); + public void toOutputStringOutputsFourArtifactsWhereBytecodeIsExactMatchInTwoAndExactMatchInOtherTwo() + throws Exception { + ClassFile classFile1 = classFileHelper.createWithContent(PATH_TO_CLASS_FILE, "file content of 1 and 2"); + ClassFile classFile2 = classFileHelper.createWithContent(PATH_TO_CLASS_FILE, "file content of 1 and 2"); + ClassFile classFile3 = classFileHelper.createWithContent(PATH_TO_CLASS_FILE, "file content of 3 and 4"); + ClassFile classFile4 = classFileHelper.createWithContent(PATH_TO_CLASS_FILE, "file content of 3 and 4"); + ClassesWithSameName classesWithSameName = + new ClassesWithSameName(LOG, classFile1, classFile2, classFile3, classFile4); + + String actualOutput = classesWithSameName.toOutputString(DETERMINE_DUPLICATES_BY_NAME_AND_BYTECODE); + + String expectedOutput = PATH_TO_CLASS_FILE + " -- the bytecode exactly matches in these: " + + classFile1.getArtifactThisClassWasFoundIn() + + " and " + classFile2.getArtifactThisClassWasFoundIn() + "; and more exact matches in these: " + + classFile3.getArtifactThisClassWasFoundIn() + + " and " + classFile4.getArtifactThisClassWasFoundIn(); + assertEquals(expectedOutput, actualOutput); } /** * The method should return the 2nd-to-last element in the last, but if there's only 1 element * there's no 2nd-to-last element to return. */ - @Test( expected = IllegalArgumentException.class ) - public void previousShouldThrowIfOnlyOneArtifact() throws Exception - { - ClassFile classFile = classFileHelper.createWithContent( PATH_TO_CLASS_FILE, "file content of 1 and 2" ); - ClassesWithSameName classesWithSameName = new ClassesWithSameName( log, classFile ); + @Test(expected = IllegalArgumentException.class) + public void previousShouldThrowIfOnlyOneArtifact() throws Exception { + ClassFile classFile = classFileHelper.createWithContent(PATH_TO_CLASS_FILE, "file content of 1 and 2"); + ClassesWithSameName classesWithSameName = new ClassesWithSameName(LOG, classFile); classesWithSameName.previous(); } @Test - public void previousShouldReturn2ndToLastElement() throws Exception - { - ClassFile classFile1 = classFileHelper.createWithContent( PATH_TO_CLASS_FILE, "file content of 1 and 2" ); - ClassFile classFile2 = classFileHelper.createWithContent( PATH_TO_CLASS_FILE, "file content of 1 and 2" ); - ClassesWithSameName classesWithSameName = new ClassesWithSameName( log, classFile1, classFile2 ); + public void previousShouldReturn2ndToLastElement() throws Exception { + ClassFile classFile1 = classFileHelper.createWithContent(PATH_TO_CLASS_FILE, "file content of 1 and 2"); + ClassFile classFile2 = classFileHelper.createWithContent(PATH_TO_CLASS_FILE, "file content of 1 and 2"); + ClassesWithSameName classesWithSameName = new ClassesWithSameName(LOG, classFile1, classFile2); ClassFile previous = classesWithSameName.previous(); - assertEquals( classFile1, previous ); + assertEquals(classFile1, previous); } @Test - public void addShouldAddArtifact() throws Exception - { - ClassFile classFile1 = classFileHelper.createWithContent( PATH_TO_CLASS_FILE, "" ); - ClassFile classFile2 = classFileHelper.createWithContent( PATH_TO_CLASS_FILE, "" ); - ClassesWithSameName classesWithSameName = new ClassesWithSameName( log, classFile1 ); - - assertEquals( 1, classesWithSameName.getAllArtifactsThisClassWasFoundIn().size() ); - classesWithSameName.add( classFile2 ); - assertEquals( 2, classesWithSameName.getAllArtifactsThisClassWasFoundIn().size() ); + public void addShouldAddArtifact() throws Exception { + ClassFile classFile1 = classFileHelper.createWithContent(PATH_TO_CLASS_FILE, ""); + ClassFile classFile2 = classFileHelper.createWithContent(PATH_TO_CLASS_FILE, ""); + ClassesWithSameName classesWithSameName = new ClassesWithSameName(LOG, classFile1); + + assertEquals(1, classesWithSameName.getAllArtifactsThisClassWasFoundIn().size()); + classesWithSameName.add(classFile2); + assertEquals(2, classesWithSameName.getAllArtifactsThisClassWasFoundIn().size()); } - @Test( expected = IllegalArgumentException.class ) - public void addShouldThrowWhenClassNameDoesNotMatch() throws Exception - { - ClassFile classFile1 = classFileHelper.createWithContent( PATH_TO_CLASS_FILE, "" ); - ClassFile classFile2 = classFileHelper.createWithContent( "some/other/path.class", "" ); - ClassesWithSameName classesWithSameName = new ClassesWithSameName( log, classFile1 ); + @Test(expected = IllegalArgumentException.class) + public void addShouldThrowWhenClassNameDoesNotMatch() throws Exception { + ClassFile classFile1 = classFileHelper.createWithContent(PATH_TO_CLASS_FILE, ""); + ClassFile classFile2 = classFileHelper.createWithContent("some/other/path.class", ""); + ClassesWithSameName classesWithSameName = new ClassesWithSameName(LOG, classFile1); - classesWithSameName.add( classFile2 ); + classesWithSameName.add(classFile2); } - @Test( expected = IllegalArgumentException.class ) - public void constructorShouldThrowWhenClassNameDoesNotMatch() throws Exception - { - ClassFile classFile1 = classFileHelper.createWithContent( PATH_TO_CLASS_FILE, "" ); - ClassFile classFile2 = classFileHelper.createWithContent( "some/other/path.class", "" ); + @Test(expected = IllegalArgumentException.class) + public void constructorShouldThrowWhenClassNameDoesNotMatch() throws Exception { + ClassFile classFile1 = classFileHelper.createWithContent(PATH_TO_CLASS_FILE, ""); + ClassFile classFile2 = classFileHelper.createWithContent("some/other/path.class", ""); - new ClassesWithSameName( log, classFile1, classFile2 ); + new ClassesWithSameName(LOG, classFile1, classFile2); } @Test - public void getAllArtifactsThisClassWasFoundInShouldReturnAllArtifacts() throws Exception - { - ClassFile classFile1 = classFileHelper.createWithContent( PATH_TO_CLASS_FILE, "" ); - ClassFile classFile2 = classFileHelper.createWithContent( PATH_TO_CLASS_FILE, "" ); - ClassesWithSameName classesWithSameName = new ClassesWithSameName( log, classFile1, classFile2 ); + public void getAllArtifactsThisClassWasFoundInShouldReturnAllArtifacts() throws Exception { + ClassFile classFile1 = classFileHelper.createWithContent(PATH_TO_CLASS_FILE, ""); + ClassFile classFile2 = classFileHelper.createWithContent(PATH_TO_CLASS_FILE, ""); + ClassesWithSameName classesWithSameName = new ClassesWithSameName(LOG, classFile1, classFile2); Artifact artifact1 = classFile1.getArtifactThisClassWasFoundIn(); Artifact artifact2 = classFile2.getArtifactThisClassWasFoundIn(); Set result = classesWithSameName.getAllArtifactsThisClassWasFoundIn(); - assertEquals( 2, result.size() ); - assertTrue( result.contains( artifact1 ) ); - assertTrue( result.contains( artifact2 ) ); + assertEquals(2, result.size()); + assertTrue(result.contains(artifact1)); + assertTrue(result.contains(artifact2)); } } diff --git a/src/test/java/org/apache/maven/plugins/enforcer/EnforceBytecodeVersionTest.java b/src/test/java/org/apache/maven/plugins/enforcer/EnforceBytecodeVersionTest.java index 342ab830..45f1791c 100644 --- a/src/test/java/org/apache/maven/plugins/enforcer/EnforceBytecodeVersionTest.java +++ b/src/test/java/org/apache/maven/plugins/enforcer/EnforceBytecodeVersionTest.java @@ -17,19 +17,18 @@ package org.apache.maven.plugins.enforcer; import org.junit.Test; + import static org.junit.Assert.*; public class EnforceBytecodeVersionTest { @Test - public void renderVersion() - { - assertEquals( "JDK 1.5", EnforceBytecodeVersion.renderVersion( 49, 0 ) ); - assertEquals( "JDK 1.7", EnforceBytecodeVersion.renderVersion( 51, 0 ) ); - assertEquals( "JDK 11", EnforceBytecodeVersion.renderVersion( 55, 0 ) ); - assertEquals( "JDK 12", EnforceBytecodeVersion.renderVersion( 56, 0 ) ); - assertEquals( "51.3", EnforceBytecodeVersion.renderVersion( 51, 3 ) ); - assertEquals( "44.0", EnforceBytecodeVersion.renderVersion( 44, 0 ) ); + public void renderVersion() { + assertEquals("JDK 1.5", EnforceBytecodeVersion.renderVersion(49, 0)); + assertEquals("JDK 1.7", EnforceBytecodeVersion.renderVersion(51, 0)); + assertEquals("JDK 11", EnforceBytecodeVersion.renderVersion(55, 0)); + assertEquals("JDK 12", EnforceBytecodeVersion.renderVersion(56, 0)); + assertEquals("51.3", EnforceBytecodeVersion.renderVersion(51, 3)); + assertEquals("44.0", EnforceBytecodeVersion.renderVersion(44, 0)); } - } diff --git a/src/test/java/org/apache/maven/plugins/enforcer/JarUtilsTest.java b/src/test/java/org/apache/maven/plugins/enforcer/JarUtilsTest.java index 101e0d34..79a3dec1 100644 --- a/src/test/java/org/apache/maven/plugins/enforcer/JarUtilsTest.java +++ b/src/test/java/org/apache/maven/plugins/enforcer/JarUtilsTest.java @@ -7,16 +7,14 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -public class JarUtilsTest -{ +public class JarUtilsTest { /** * "Sunny day" test: the method should return true for a jar artifact. */ @Test - public void isJarFileShouldReturnTrueForJarFile() - { - Artifact artifact = newBuilder().withType( "jar" ).build(); - assertTrue( JarUtils.isJarFile( artifact ) ); + public void isJarFileShouldReturnTrueForJarFile() { + Artifact artifact = newBuilder().withType("jar").build(); + assertTrue(JarUtils.isJarFile(artifact)); } /** @@ -24,13 +22,9 @@ public void isJarFileShouldReturnTrueForJarFile() * a folder with a bunch of packages/class files in it). */ @Test - public void isJarFileShouldReturnFalseForDirectory() - { - Artifact artifact = newBuilder() - .withType( "jar" ) - .withAnyDirectory() - .build(); - assertFalse( JarUtils.isJarFile( artifact ) ); + public void isJarFileShouldReturnFalseForDirectory() { + Artifact artifact = newBuilder().withType("jar").withAnyDirectory().build(); + assertFalse(JarUtils.isJarFile(artifact)); } /** @@ -38,9 +32,8 @@ public void isJarFileShouldReturnFalseForDirectory() * not "jar". For example: a war or a zip file. */ @Test - public void isJarFileShouldReturnFalseWhenArtifactTypeIsNotJar() - { - Artifact artifact = newBuilder().withType( "war" ).build(); - assertFalse( JarUtils.isJarFile( artifact ) ); + public void isJarFileShouldReturnFalseWhenArtifactTypeIsNotJar() { + Artifact artifact = newBuilder().withType("war").build(); + assertFalse(JarUtils.isJarFile(artifact)); } } diff --git a/src/test/java/org/apache/maven/plugins/enforcer/RequireEncodingTest.java b/src/test/java/org/apache/maven/plugins/enforcer/RequireEncodingTest.java index 77b85d74..d908ce79 100644 --- a/src/test/java/org/apache/maven/plugins/enforcer/RequireEncodingTest.java +++ b/src/test/java/org/apache/maven/plugins/enforcer/RequireEncodingTest.java @@ -1,9 +1,5 @@ package org.apache.maven.plugins.enforcer; -import static org.junit.Assert.assertThrows; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - import java.io.File; import org.apache.maven.enforcer.rule.api.EnforcerRuleException; @@ -12,26 +8,30 @@ import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + public class RequireEncodingTest { - private EnforcerRuleHelper helper; - private RequireEncoding rule; - - @Before - public void initFields() { - helper = mock(EnforcerRuleHelper.class); - rule = new RequireEncoding(); - } - - @Test - public void failUTF8() throws Exception { - - when(helper.evaluate("${basedir}")).thenReturn(new File("src/test/resources").getAbsolutePath()); - when(helper.evaluate("${project.build.sourceEncoding}")).thenReturn("UTF-8"); - when(helper.getLog()).thenReturn(mock(Log.class)); - - rule.setIncludes("ascii.txt"); - - assertThrows(EnforcerRuleException.class, () -> rule.execute(helper) ); - } + private EnforcerRuleHelper helper; + private RequireEncoding rule; + + @Before + public void initFields() { + helper = mock(EnforcerRuleHelper.class); + rule = new RequireEncoding(); + } + + @Test + public void failUTF8() throws Exception { + + when(helper.evaluate("${basedir}")).thenReturn(new File("src/test/resources").getAbsolutePath()); + when(helper.evaluate("${project.build.sourceEncoding}")).thenReturn("UTF-8"); + when(helper.getLog()).thenReturn(mock(Log.class)); + + rule.setIncludes("ascii.txt"); + + assertThrows(EnforcerRuleException.class, () -> rule.execute(helper)); + } } diff --git a/src/test/java/org/apache/maven/plugins/enforcer/RequirePropertyDivergesTest.java b/src/test/java/org/apache/maven/plugins/enforcer/RequirePropertyDivergesTest.java index 097fb97a..2b3cd6b9 100644 --- a/src/test/java/org/apache/maven/plugins/enforcer/RequirePropertyDivergesTest.java +++ b/src/test/java/org/apache/maven/plugins/enforcer/RequirePropertyDivergesTest.java @@ -18,9 +18,6 @@ * specific language governing permissions and limitations * under the License. */ -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.when; -import static org.mockito.Mockito.mock; import org.apache.maven.enforcer.rule.api.EnforcerRuleException; import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper; @@ -35,36 +32,37 @@ import org.codehaus.plexus.util.xml.Xpp3Dom; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + /** - * * @author mirko */ -public class RequirePropertyDivergesTest -{ +public class RequirePropertyDivergesTest { + + final EnforcerRuleHelper helper = mock(EnforcerRuleHelper.class); - final EnforcerRuleHelper helper = mock( EnforcerRuleHelper.class ); final RequirePropertyDiverges instance = new RequirePropertyDiverges(); /** * Test of execute method, of class RequirePropertyDiverges. */ @Test - public void testExecuteInChild() throws EnforcerRuleException - { + public void testExecuteInChild() throws EnforcerRuleException { RequirePropertyDiverges mockInstance = createMockRule(); - final MavenProject project = createMavenProject( "company", "child" ); + final MavenProject project = createMavenProject("company", "child"); final MavenProject parent = createParentProject(); - project.setParent( parent ); - setUpHelper( project, "childValue" ); - mockInstance.execute( helper ); + project.setParent(parent); + setUpHelper(project, "childValue"); + mockInstance.execute(helper); } /** * Test of execute method, of class RequirePropertyDiverges. */ @Test - public void testExecuteInParent() throws EnforcerRuleException - { + public void testExecuteInParent() throws EnforcerRuleException { RequirePropertyDiverges mockInstance = createMockRule(); final MavenProject project = createParentProject(); setUpHelper(project, "parentValue"); @@ -72,14 +70,14 @@ public void testExecuteInParent() throws EnforcerRuleException } private MavenProject createParentProject() { - final MavenProject project = createMavenProject( "company", "company-parent-pom" ); + final MavenProject project = createMavenProject("company", "company-parent-pom"); final Build build = new Build(); - build.setPluginManagement( new PluginManagement() ); - final Plugin plugin = newPlugin( "org.apache.maven.plugins", "maven-enforcer-plugin", "1.0"); + build.setPluginManagement(new PluginManagement()); + final Plugin plugin = newPlugin("org.apache.maven.plugins", "maven-enforcer-plugin", "1.0"); final Xpp3Dom configuration = createPluginConfiguration(); - plugin.setConfiguration( configuration ); - build.addPlugin( plugin ); - project.getOriginalModel().setBuild( build ); + plugin.setConfiguration(configuration); + build.addPlugin(plugin); + project.getOriginalModel().setBuild(build); return project; } @@ -87,217 +85,191 @@ private MavenProject createParentProject() { * Test of execute method, of class RequirePropertyDiverges. */ @Test - public void testExecuteInParentWithConfigurationInPluginManagement() throws EnforcerRuleException - { + public void testExecuteInParentWithConfigurationInPluginManagement() throws EnforcerRuleException { RequirePropertyDiverges mockInstance = createMockRule(); - final MavenProject project = createMavenProject( "company", "company-parent-pom" ); + final MavenProject project = createMavenProject("company", "company-parent-pom"); final Build build = new Build(); // create pluginManagement - final Plugin pluginInManagement = newPlugin( "org.apache.maven.plugins", "maven-enforcer-plugin", "1.0"); + final Plugin pluginInManagement = newPlugin("org.apache.maven.plugins", "maven-enforcer-plugin", "1.0"); final Xpp3Dom configuration = createPluginConfiguration(); - pluginInManagement.setConfiguration( configuration ); + pluginInManagement.setConfiguration(configuration); final PluginManagement pluginManagement = new PluginManagement(); - pluginManagement.addPlugin( pluginInManagement ); - build.setPluginManagement( pluginManagement ); + pluginManagement.addPlugin(pluginInManagement); + build.setPluginManagement(pluginManagement); // create plugins - final Plugin pluginInPlugins = newPlugin( "org.apache.maven.plugins", "maven-enforcer-plugin", "1.0"); - build.addPlugin( pluginInPlugins ); + final Plugin pluginInPlugins = newPlugin("org.apache.maven.plugins", "maven-enforcer-plugin", "1.0"); + build.addPlugin(pluginInPlugins); // add build - project.getOriginalModel().setBuild( build ); - //project.getOriginalModel().setBuild( build ); - setUpHelper( project, "parentValue" ); - mockInstance.execute( helper ); + project.getOriginalModel().setBuild(build); + // project.getOriginalModel().setBuild( build ); + setUpHelper(project, "parentValue"); + mockInstance.execute(helper); } /** * Test of execute method, of class RequirePropertyDiverges. */ @Test - public void testExecuteInParentWithConfigurationInExecution() throws EnforcerRuleException - { + public void testExecuteInParentWithConfigurationInExecution() throws EnforcerRuleException { RequirePropertyDiverges mockInstance = createMockRule(); - final MavenProject project = createMavenProject( "company", "company-parent-pom" ); + final MavenProject project = createMavenProject("company", "company-parent-pom"); final Build build = new Build(); - build.setPluginManagement( new PluginManagement() ); - final Plugin plugin = newPlugin( "org.apache.maven.plugins", "maven-enforcer-plugin", "1.0" ); + build.setPluginManagement(new PluginManagement()); + final Plugin plugin = newPlugin("org.apache.maven.plugins", "maven-enforcer-plugin", "1.0"); final Xpp3Dom configuration = createPluginConfiguration(); PluginExecution pluginExecution = new PluginExecution(); - pluginExecution.setConfiguration( configuration ); - plugin.addExecution( pluginExecution ); - build.addPlugin( plugin ); - project.getOriginalModel().setBuild( build ); + pluginExecution.setConfiguration(configuration); + plugin.addExecution(pluginExecution); + build.addPlugin(plugin); + project.getOriginalModel().setBuild(build); setUpHelper(project, "parentValue"); - mockInstance.execute( helper ); + mockInstance.execute(helper); } @Test - public void testProjectWithoutEnforcer() - { + public void testProjectWithoutEnforcer() { final Build build = new Build(); - //build.setPluginManagement( new PluginManagement() ); - instance.getRuleConfigurations( build ); + // build.setPluginManagement( new PluginManagement() ); + instance.getRuleConfigurations(build); } /** * Test of execute method, of class RequirePropertyDiverges. */ - @Test( expected = EnforcerRuleException.class ) - public void testExecuteInChildShouldFail() throws EnforcerRuleException - { + @Test(expected = EnforcerRuleException.class) + public void testExecuteInChildShouldFail() throws EnforcerRuleException { RequirePropertyDiverges mockInstance = createMockRule(); - final MavenProject project = createMavenProject( "company", "child" ); + final MavenProject project = createMavenProject("company", "child"); final MavenProject parent = createParentProject(); - project.setParent( parent ); - setUpHelper( project, "parentValue" ); - mockInstance.execute( helper ); + project.setParent(parent); + setUpHelper(project, "parentValue"); + mockInstance.execute(helper); } /** * Test of checkPropValueNotBlank method, of class RequirePropertyDiverges. */ @Test - public void testCheckPropValueNotBlank() throws Exception - { - instance.setProperty( "checkedProperty" ); - instance.checkPropValueNotBlank( "propertyValue" ); + public void testCheckPropValueNotBlank() throws Exception { + instance.setProperty("checkedProperty"); + instance.checkPropValueNotBlank("propertyValue"); } /** * Test of checkPropValueNotBlank method, of class RequirePropertyDiverges. */ - @Test( expected = EnforcerRuleException.class ) - public void testCheckPropValueNotBlankNull() throws EnforcerRuleException - { - instance.setProperty( "checkedProperty" ); - instance.checkPropValueNotBlank( null ); + @Test(expected = EnforcerRuleException.class) + public void testCheckPropValueNotBlankNull() throws EnforcerRuleException { + instance.setProperty("checkedProperty"); + instance.checkPropValueNotBlank(null); } @Test - public void testCreateResultingErrorMessageReturningCustomMessage() - { - instance.setProperty( "checkedProperty" ); - instance.setMessage( "This is needed for foo." ); - final String actual = instance.createResultingErrorMessage( "default message" ); + public void testCreateResultingErrorMessageReturningCustomMessage() { + instance.setProperty("checkedProperty"); + instance.setMessage("This is needed for foo."); + final String actual = instance.createResultingErrorMessage("default message"); final String expected = "Property 'checkedProperty' must be overridden:\nThis is needed for foo."; - assertEquals( expected, actual); + assertEquals(expected, actual); } @Test - public void testCreateResultingErrorMessageReturningDefaultMessage() - { - instance.setProperty( "checkedProperty" ); - instance.setMessage( null ); - { - final String actual = instance.createResultingErrorMessage( "default message" ); - final String expected = "default message"; - assertEquals( expected, actual ); - } - instance.setMessage( "" ); - { - final String actual = instance.createResultingErrorMessage( "default message" ); - final String expected = "default message"; - assertEquals( expected, actual ); - } + public void testCreateResultingErrorMessageReturningDefaultMessage() { + instance.setProperty("checkedProperty"); + instance.setMessage(null); + String actual = instance.createResultingErrorMessage("default message"); + String expected = "default message"; + assertEquals(expected, actual); + + instance.setMessage(""); + actual = instance.createResultingErrorMessage("default message"); + expected = "default message"; + assertEquals(expected, actual); } @Test - public void testGetRuleName() - { - assertEquals( "requirePropertyDiverges", instance.getRuleName() ); + public void testGetRuleName() { + assertEquals("requirePropertyDiverges", instance.getRuleName()); } - @Test( expected = EnforcerRuleException.class ) - public void testGetPropertyValueFail() throws ExpressionEvaluationException, EnforcerRuleException - { - when( helper.evaluate( "${checkedProperty}" ) ).thenThrow( ExpressionEvaluationException.class ); - instance.setProperty( "checkedProperty" ); - instance.getPropertyValue( helper ); + @Test(expected = EnforcerRuleException.class) + public void testGetPropertyValueFail() throws ExpressionEvaluationException, EnforcerRuleException { + when(helper.evaluate("${checkedProperty}")).thenThrow(ExpressionEvaluationException.class); + instance.setProperty("checkedProperty"); + instance.getPropertyValue(helper); } - @Test( expected = EnforcerRuleException.class ) - public void testGetProjectFail() throws ExpressionEvaluationException, EnforcerRuleException - { - when( helper.evaluate( "${project}" ) ).thenThrow( ExpressionEvaluationException.class ); - instance.getMavenProject( helper ); + @Test(expected = EnforcerRuleException.class) + public void testGetProjectFail() throws ExpressionEvaluationException, EnforcerRuleException { + when(helper.evaluate("${project}")).thenThrow(ExpressionEvaluationException.class); + instance.getMavenProject(helper); } - @Test( expected = EnforcerRuleException.class ) - public void testCheckAgainstParentValueFailing() throws EnforcerRuleException, ExpressionEvaluationException - { - testCheckAgainstParentValue( "company.parent-pom", "company.parent-pom" ); + @Test(expected = EnforcerRuleException.class) + public void testCheckAgainstParentValueFailing() throws EnforcerRuleException, ExpressionEvaluationException { + testCheckAgainstParentValue("company.parent-pom", "company.parent-pom"); } @Test - public void testCheckAgainstParentValue() throws EnforcerRuleException, ExpressionEvaluationException - { - testCheckAgainstParentValue( "company.parent-pom", "company.project1" ); + public void testCheckAgainstParentValue() throws EnforcerRuleException, ExpressionEvaluationException { + testCheckAgainstParentValue("company.parent-pom", "company.project1"); } - void testCheckAgainstParentValue( final String parentGroupId, final String childGroupId ) throws ExpressionEvaluationException, EnforcerRuleException - { - instance.setProperty( "project.groupId" ); - MavenProject parent = createMavenProject( parentGroupId, "parent-pom" ); - MavenProject project = createMavenProject( childGroupId, "child" ); - project.setParent( parent ); - when( helper.evaluate( "${project.parent.groupId}" ) ).thenReturn( parentGroupId ); - instance.checkAgainstParentValue( project, parent, helper, childGroupId ); + void testCheckAgainstParentValue(final String parentGroupId, final String childGroupId) + throws ExpressionEvaluationException, EnforcerRuleException { + instance.setProperty("project.groupId"); + MavenProject parent = createMavenProject(parentGroupId, "parent-pom"); + MavenProject project = createMavenProject(childGroupId, "child"); + project.setParent(parent); + when(helper.evaluate("${project.parent.groupId}")).thenReturn(parentGroupId); + instance.checkAgainstParentValue(project, parent, helper, childGroupId); } - static RequirePropertyDiverges createMockRule() - { + static RequirePropertyDiverges createMockRule() { RequirePropertyDiverges instance = new RequirePropertyDiverges(); - instance.setRegex( "parentValue" ); - instance.setProperty( "checkedProperty" ); + instance.setRegex("parentValue"); + instance.setProperty("checkedProperty"); return instance; - } - static MavenProject createMavenProject( final String groupId, final String artifactId ) - { + static MavenProject createMavenProject(final String groupId, final String artifactId) { final MavenProject project = new MavenProject(); - project.setGroupId( groupId ); - project.setArtifactId( artifactId ); - project.setOriginalModel( new Model() ); + project.setGroupId(groupId); + project.setArtifactId(artifactId); + project.setOriginalModel(new Model()); return project; } - void setUpHelper( final MavenProject project, final String propertyValue ) throws RuntimeException - { - try - { - when( helper.evaluate( "${project}" ) ).thenReturn( project ); - when( helper.evaluate( "${checkedProperty}" ) ).thenReturn( propertyValue ); + void setUpHelper(final MavenProject project, final String propertyValue) throws RuntimeException { + try { + when(helper.evaluate("${project}")).thenReturn(project); + when(helper.evaluate("${checkedProperty}")).thenReturn(propertyValue); + } catch (ExpressionEvaluationException ex) { + throw new RuntimeException(ex); } - catch ( ExpressionEvaluationException ex ) - { - throw new RuntimeException( ex ); - } - when( helper.getLog() ).thenReturn( mock( Log.class ) ); + when(helper.getLog()).thenReturn(mock(Log.class)); } - Xpp3Dom createPluginConfiguration() - { - final Xpp3Dom configuration = new Xpp3Dom( "configuration" ); - final Xpp3Dom rules = new Xpp3Dom( "rules" ); - final Xpp3Dom rule = new Xpp3Dom( instance.getRuleName() ); - rules.addChild( rule ); - final Xpp3Dom property = new Xpp3Dom( "property" ); - property.setValue( "checkedProperty" ); - rule.addChild( property ); - final Xpp3Dom regex = new Xpp3Dom( "regex" ); - regex.setValue( "parentValue" ); - rule.addChild( regex ); - configuration.addChild( rules ); + Xpp3Dom createPluginConfiguration() { + final Xpp3Dom configuration = new Xpp3Dom("configuration"); + final Xpp3Dom rules = new Xpp3Dom("rules"); + final Xpp3Dom rule = new Xpp3Dom(instance.getRuleName()); + rules.addChild(rule); + final Xpp3Dom property = new Xpp3Dom("property"); + property.setValue("checkedProperty"); + rule.addChild(property); + final Xpp3Dom regex = new Xpp3Dom("regex"); + regex.setValue("parentValue"); + rule.addChild(regex); + configuration.addChild(rules); return configuration; } - static Plugin newPlugin( String groupId, String artifactId, String version ) - { + static Plugin newPlugin(String groupId, String artifactId, String version) { Plugin plugin = new Plugin(); - plugin.setArtifactId( artifactId ); - plugin.setGroupId( groupId ); - plugin.setVersion( version ); + plugin.setArtifactId(artifactId); + plugin.setGroupId(groupId); + plugin.setVersion(version); return plugin; } - } diff --git a/src/test/java/org/apache/maven/plugins/enforcer/RequireRolesTest.java b/src/test/java/org/apache/maven/plugins/enforcer/RequireRolesTest.java index 2e565ec5..c0a17d46 100644 --- a/src/test/java/org/apache/maven/plugins/enforcer/RequireRolesTest.java +++ b/src/test/java/org/apache/maven/plugins/enforcer/RequireRolesTest.java @@ -29,146 +29,130 @@ import org.apache.maven.model.Contributor; import org.apache.maven.model.Developer; import org.apache.maven.project.MavenProject; -import static org.junit.Assert.assertEquals; import org.junit.Test; import org.mockito.Mockito; +import static org.junit.Assert.assertEquals; + /** * * @author Mirko Friedenhagen */ -public class RequireRolesTest -{ +public class RequireRolesTest { - final EnforcerRuleHelper helper = Mockito.mock( EnforcerRuleHelper.class ); + final EnforcerRuleHelper helper = Mockito.mock(EnforcerRuleHelper.class); @Test - public void shouldSucceedBecauseArchitectAsDeveloperAndBusinessEngineerAsContributorArePresent() throws Exception - { + public void shouldSucceedBecauseArchitectAsDeveloperAndBusinessEngineerAsContributorArePresent() throws Exception { addProjectHavingAnArchitectAsDeveloperAndABusinessEngineerAsContributorToHelper(); - newRequireDeveloperRoles( "architect" /*required role*/, null /* valid roles not needed */).execute( helper ); - newRequireContributorRoles( "business engineer" /*required role*/, "*" /* valid roles */).execute( helper ); + newRequireDeveloperRoles("architect" /*required role*/, null /* valid roles not needed */) + .execute(helper); + newRequireContributorRoles("business engineer" /*required role*/, "*" /* valid roles */) + .execute(helper); } - @Test( expected = EnforcerRuleException.class ) - public void shouldFailBecauseContributorWithRoleQualityManagerIsMissing() throws Exception - { + @Test(expected = EnforcerRuleException.class) + public void shouldFailBecauseContributorWithRoleQualityManagerIsMissing() throws Exception { addProjectHavingAnArchitectAsDeveloperAndABusinessEngineerAsContributorToHelper(); - newRequireContributorRoles( "business engineer, quality manager", null ).execute( helper ); + newRequireContributorRoles("business engineer, quality manager", null).execute(helper); } - @Test( expected = EnforcerRuleException.class ) - public void shouldFailBecauseDeveloperWithRoleCodeMonkeyIsMissing() throws Exception - { + @Test(expected = EnforcerRuleException.class) + public void shouldFailBecauseDeveloperWithRoleCodeMonkeyIsMissing() throws Exception { addProjectHavingAnArchitectAsDeveloperAndABusinessEngineerAsContributorToHelper(); - newRequireDeveloperRoles( "codemonkey" /* required but not in project */, - null ).execute( helper ); + newRequireDeveloperRoles("codemonkey" /* required but not in project */, null) + .execute(helper); } - @Test( expected = EnforcerRuleException.class ) - public void shouldFailBecauseContributorRoleBusinessEngineerIsInvalid() throws Exception - { + @Test(expected = EnforcerRuleException.class) + public void shouldFailBecauseContributorRoleBusinessEngineerIsInvalid() throws Exception { addProjectHavingAnArchitectAsDeveloperAndABusinessEngineerAsContributorToHelper(); - newRequireContributorRoles( null /* no required roles needed */, - "hacker" /* only valid role */).execute( helper ); + newRequireContributorRoles(null /* no required roles needed */, "hacker" /* only valid role */) + .execute(helper); } - @Test( expected = EnforcerRuleException.class ) - public void shouldFailBecauseNoContributorRolesAtAllAreValid() throws Exception - { + @Test(expected = EnforcerRuleException.class) + public void shouldFailBecauseNoContributorRolesAtAllAreValid() throws Exception { addProjectHavingAnArchitectAsDeveloperAndABusinessEngineerAsContributorToHelper(); - newRequireContributorRoles( null /* no required roles needed */, - "" /*but no role is valid at all */).execute( helper ); + newRequireContributorRoles(null /* no required roles needed */, "" /*but no role is valid at all */) + .execute(helper); } @Test - public void shouldSucceedAsNoRolesAreRequiredAndAllAreAccepted() throws Exception - { + public void shouldSucceedAsNoRolesAreRequiredAndAllAreAccepted() throws Exception { addProjectHavingAnArchitectAsDeveloperAndABusinessEngineerAsContributorToHelper(); - newRequireContributorRoles( null /* no required roles */, - "*" /* any role is valid */).execute( helper ); - newRequireContributorRoles( null /* no required roles */, - null /* any role is valid */).execute( helper ); + newRequireContributorRoles(null /* no required roles */, "*" /* any role is valid */) + .execute(helper); + newRequireContributorRoles(null /* no required roles */, null /* any role is valid */) + .execute(helper); } /** * Test of getRolesFromString method, of class AbstractRequireRoles. */ @Test - public void testGetRolesFromString() - { + public void testGetRolesFromString() { HashSet expResult = new HashSet<>(Arrays.asList("architect", "codemonkey", "business engineer")); final RequireContributorRoles sut = new RequireContributorRoles(); - Set result = sut.getRolesFromString( " architect, business engineer , codemonkey " ); - assertEquals( expResult, result ); + Set result = sut.getRolesFromString(" architect, business engineer , codemonkey "); + assertEquals(expResult, result); } /** * Test of getRolesFromMaven method, of class AbstractRequireRoles. */ @Test - public void testGetRolesFromMaven() - { - HashSet expResult = new HashSet<>(Arrays.asList( - "quality manager", "product owner", "business engineer")); + public void testGetRolesFromMaven() { + HashSet expResult = + new HashSet<>(Arrays.asList("quality manager", "product owner", "business engineer")); final Contributor singleHero = new Contributor(); - singleHero.addRole( "quality manager" ); - singleHero.addRole( "business engineer" ); - singleHero.addRole( "product owner" ); + singleHero.addRole("quality manager"); + singleHero.addRole("business engineer"); + singleHero.addRole("product owner"); List listFromMaven = Collections.singletonList(singleHero); final HashSet result = new HashSet<>(); - for ( final Contributor contributor : listFromMaven ) - { - @SuppressWarnings( "unchecked" ) + for (final Contributor contributor : listFromMaven) { + @SuppressWarnings("unchecked") List roles = contributor.getRoles(); result.addAll(roles); } - assertEquals( expResult, result ); + assertEquals(expResult, result); } - private void addProjectHavingAnArchitectAsDeveloperAndABusinessEngineerAsContributorToHelper() throws Exception - { + private void addProjectHavingAnArchitectAsDeveloperAndABusinessEngineerAsContributorToHelper() throws Exception { final MavenProject mavenProject = new MavenProject(); final Developer developer = new Developer(); - developer.addRole( "architect" ); - mavenProject.addDeveloper( developer ); + developer.addRole("architect"); + mavenProject.addDeveloper(developer); final Contributor contributor = new Contributor(); - contributor.addRole( "business engineer" ); - mavenProject.addContributor( contributor ); - Mockito.when( helper.evaluate( "${project}" ) ).thenReturn( mavenProject ); + contributor.addRole("business engineer"); + mavenProject.addContributor(contributor); + Mockito.when(helper.evaluate("${project}")).thenReturn(mavenProject); } - private RequireDeveloperRoles newRequireDeveloperRoles( - final String commaSeparatedRequiredRoles, - final String commaSeparatedValidRoles ) - { + final String commaSeparatedRequiredRoles, final String commaSeparatedValidRoles) { final RequireDeveloperRoles sut = new RequireDeveloperRoles(); - if ( commaSeparatedRequiredRoles != null ) - { - sut.setRequiredRoles( commaSeparatedRequiredRoles ); + if (commaSeparatedRequiredRoles != null) { + sut.setRequiredRoles(commaSeparatedRequiredRoles); } - if ( commaSeparatedValidRoles != null ) - { - sut.setValidRoles( commaSeparatedValidRoles ); + if (commaSeparatedValidRoles != null) { + sut.setValidRoles(commaSeparatedValidRoles); } return sut; } - + private RequireContributorRoles newRequireContributorRoles( - final String commaSeparatedRequiredRoles, - final String commaSeparatedValidRoles ) - { + final String commaSeparatedRequiredRoles, final String commaSeparatedValidRoles) { final RequireContributorRoles sut = new RequireContributorRoles(); - if ( commaSeparatedRequiredRoles != null ) - { - sut.setRequiredRoles( commaSeparatedRequiredRoles ); + if (commaSeparatedRequiredRoles != null) { + sut.setRequiredRoles(commaSeparatedRequiredRoles); } - if ( commaSeparatedValidRoles != null ) - { - sut.setValidRoles( commaSeparatedValidRoles ); + if (commaSeparatedValidRoles != null) { + sut.setValidRoles(commaSeparatedValidRoles); } return sut; - }} + } +} diff --git a/src/test/java/org/apache/maven/plugins/enforcer/RuleXpp3DomTest.java b/src/test/java/org/apache/maven/plugins/enforcer/RuleXpp3DomTest.java index e534f3db..c6a01456 100644 --- a/src/test/java/org/apache/maven/plugins/enforcer/RuleXpp3DomTest.java +++ b/src/test/java/org/apache/maven/plugins/enforcer/RuleXpp3DomTest.java @@ -20,76 +20,68 @@ */ import org.codehaus.plexus.util.xml.Xpp3Dom; +import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; -import org.junit.Test; /** * * @author mfriedenhagen */ -public class RuleXpp3DomTest -{ +public class RuleXpp3DomTest { final RequirePropertyDiverges sut1 = new RequirePropertyDiverges(); final RequirePropertyDiverges sut2 = new RequirePropertyDiverges(); @Test - public void checkRuleWithoutRegex() - { - sut1.setProperty( "foo" ); - sut2.setProperty( "foo" ); + public void checkRuleWithoutRegex() { + sut1.setProperty("foo"); + sut2.setProperty("foo"); checkEquals(); } @Test - public void checkRuleWithoutRegexButMessage() - { - sut1.setProperty( "foo" ); - sut1.setMessage( "Oops" ); - sut2.setProperty( "foo" ); - sut2.setMessage( "Oops" ); + public void checkRuleWithoutRegexButMessage() { + sut1.setProperty("foo"); + sut1.setMessage("Oops"); + sut2.setProperty("foo"); + sut2.setMessage("Oops"); checkEquals(); } @Test - public void checkRuleWithoutRegexDiverges() - { - sut1.setProperty( "foo" ); - sut2.setProperty( "foo2" ); + public void checkRuleWithoutRegexDiverges() { + sut1.setProperty("foo"); + sut2.setProperty("foo2"); checkDiverges(); } @Test - public void checkRuleWithRegex() - { - sut1.setProperty( "foo" ); - sut1.setRegex( "http://company/wiki/company-parent-pom.*" ); - sut2.setProperty( "foo" ); - sut2.setRegex( "http://company/wiki/company-parent-pom.*" ); + public void checkRuleWithRegex() { + sut1.setProperty("foo"); + sut1.setRegex("http://company/wiki/company-parent-pom.*"); + sut2.setProperty("foo"); + sut2.setRegex("http://company/wiki/company-parent-pom.*"); checkEquals(); } @Test - public void checkRuleWithRegexDiverges() - { - sut1.setProperty( "foo" ); - sut1.setRegex( "http://company/wiki/company-parent-pom.*" ); - sut2.setProperty( "foo" ); - sut2.setRegex( "http://company/wiki/company-project1" ); + public void checkRuleWithRegexDiverges() { + sut1.setProperty("foo"); + sut1.setRegex("http://company/wiki/company-parent-pom.*"); + sut2.setProperty("foo"); + sut2.setRegex("http://company/wiki/company-project1"); checkDiverges(); } - void checkEquals() - { + void checkEquals() { Xpp3Dom ruleDom1 = sut1.createInvokingRuleDom(); Xpp3Dom ruleDom2 = sut2.createInvokingRuleDom(); assertEquals(ruleDom1, ruleDom2); } - void checkDiverges() - { + void checkDiverges() { Xpp3Dom ruleDom1 = sut1.createInvokingRuleDom(); Xpp3Dom ruleDom2 = sut2.createInvokingRuleDom(); assertNotEquals(ruleDom1, ruleDom2); diff --git a/src/test/java/org/codehaus/mojo/extraenforcerrules/it/BanDuplicateClassesLogParser.java b/src/test/java/org/codehaus/mojo/extraenforcerrules/it/BanDuplicateClassesLogParser.java index 710f78c6..c8ab6a45 100644 --- a/src/test/java/org/codehaus/mojo/extraenforcerrules/it/BanDuplicateClassesLogParser.java +++ b/src/test/java/org/codehaus/mojo/extraenforcerrules/it/BanDuplicateClassesLogParser.java @@ -1,107 +1,92 @@ -package org.codehaus.mojo.extraenforcerrules.it; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -/** - * LogParser for BanDuplicateClasses Enforcer Rule used for integration test verification by parsing the messages from the BanDuplicateClasses rule. - */ -public class BanDuplicateClassesLogParser -{ - private static final String DUPLICATE_START_LINE = - "[ERROR] Rule 0: org.apache.maven.plugins.enforcer.BanDuplicateClasses failed with message:"; - - private final File logFile; - - public BanDuplicateClassesLogParser( File logFile ) - { - this.logFile = logFile; - } - - /** - * Parse out the violations from BanDuplicateClasses in a log file. - * - * @return A map where the keys are sets of jars which contain duplicate classes, and the values are sets of classes - * which are duplicated in those jars. - * @throws IOException if the reader for the log file throws one - */ - public Map, Set> parse( ) - throws IOException - { - Map, Set> duplicates = new HashMap<>(); - - try ( BufferedReader reader = new BufferedReader( new FileReader( logFile ) ) ) - { - String line; - while ( ( line = reader.readLine() ) != null ) - { - if ( DUPLICATE_START_LINE.equals( line.trim() ) ) - { - break; - } - } - while ( ( line = reader.readLine() ) != null ) - { - if ( line.startsWith( "[INFO] ---" ) ) - { - break; - } - if ( line.equals( " Found in:" ) ) - { - Set jars = readFoundInJars( reader ); - Set classes = readDuplicateClasses( reader ); - duplicates.put( jars, classes ); - } - } - } - return duplicates; - } - - private static Set readFoundInJars( BufferedReader reader ) - throws IOException - { - Set jars = new HashSet<>(); - for ( String line = reader.readLine(); line != null && !" Duplicate classes:".equals( line ); line = - reader.readLine() ) - { - jars.add( line.trim() ); - } - return jars; - } - - private static Set readDuplicateClasses( BufferedReader reader ) - throws IOException - { - Set classes = new HashSet<>(); - for ( String line = reader.readLine(); line != null && line.length() > 0; line = reader.readLine() ) - { - classes.add( line.trim() ); - } - return classes; - } -} +package org.codehaus.mojo.extraenforcerrules.it; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +/** + * LogParser for BanDuplicateClasses Enforcer Rule used for integration test verification by parsing the messages from the BanDuplicateClasses rule. + */ +public class BanDuplicateClassesLogParser { + private static final String DUPLICATE_START_LINE = + "[ERROR] Rule 0: org.apache.maven.plugins.enforcer.BanDuplicateClasses failed with message:"; + + private final File logFile; + + public BanDuplicateClassesLogParser(File logFile) { + this.logFile = logFile; + } + + /** + * Parse out the violations from BanDuplicateClasses in a log file. + * + * @return A map where the keys are sets of jars which contain duplicate classes, and the values are sets of classes + * which are duplicated in those jars. + * @throws IOException if the reader for the log file throws one + */ + public Map, Set> parse() throws IOException { + Map, Set> duplicates = new HashMap<>(); + + try (BufferedReader reader = new BufferedReader(new FileReader(logFile))) { + String line; + while ((line = reader.readLine()) != null) { + if (DUPLICATE_START_LINE.equals(line.trim())) { + break; + } + } + while ((line = reader.readLine()) != null) { + if (line.startsWith("[INFO] ---")) { + break; + } + if (line.equals(" Found in:")) { + Set jars = readFoundInJars(reader); + Set classes = readDuplicateClasses(reader); + duplicates.put(jars, classes); + } + } + } + return duplicates; + } + + private static Set readFoundInJars(BufferedReader reader) throws IOException { + Set jars = new HashSet<>(); + for (String line = reader.readLine(); + line != null && !" Duplicate classes:".equals(line); + line = reader.readLine()) { + jars.add(line.trim()); + } + return jars; + } + + private static Set readDuplicateClasses(BufferedReader reader) throws IOException { + Set classes = new HashSet<>(); + for (String line = reader.readLine(); line != null && line.length() > 0; line = reader.readLine()) { + classes.add(line.trim()); + } + return classes; + } +} diff --git a/src/test/java/org/codehaus/mojo/extraenforcerrules/it/package-info.java b/src/test/java/org/codehaus/mojo/extraenforcerrules/it/package-info.java index 6ad0f31b..eb5078a4 100644 --- a/src/test/java/org/codehaus/mojo/extraenforcerrules/it/package-info.java +++ b/src/test/java/org/codehaus/mojo/extraenforcerrules/it/package-info.java @@ -1,25 +1,24 @@ -/** - * Utility classes for use in - * integration tests. - */ -package org.codehaus.mojo.extraenforcerrules.it; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - +/** + * Utility classes for use in + * integration tests. + */ +package org.codehaus.mojo.extraenforcerrules.it; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ diff --git a/src/test/java/org/freebsd/file/FileEncodingTest.java b/src/test/java/org/freebsd/file/FileEncodingTest.java index 7badeead..4b8c1c79 100644 --- a/src/test/java/org/freebsd/file/FileEncodingTest.java +++ b/src/test/java/org/freebsd/file/FileEncodingTest.java @@ -1,80 +1,105 @@ package org.freebsd.file; -import static org.junit.Assert.assertEquals; - import java.nio.charset.StandardCharsets; import org.junit.Before; import org.junit.Test; -public class FileEncodingTest -{ +import static org.junit.Assert.assertEquals; + +public class FileEncodingTest { private FileEncoding rule; @Before - public void initFields() - { + public void initFields() { rule = new FileEncoding(); } @Test - public void detectAscii() - { - assertEncoding( new byte[]{'a', 'b', 'c', 'A', 'B', 'C', '1', '2', '3'}, StandardCharsets.US_ASCII.name(), "ASCII" ); + public void detectAscii() { + assertEncoding( + new byte[] {'a', 'b', 'c', 'A', 'B', 'C', '1', '2', '3'}, StandardCharsets.US_ASCII.name(), "ASCII"); } @Test - public void detectISO() - { - assertEncoding( new byte[]{'a', 'b', 'c', 'A', 'B', 'C', '1', '2', '3', (byte) 0xF7}, StandardCharsets.ISO_8859_1.name(), "ISO-8859" ); + public void detectISO() { + assertEncoding( + new byte[] {'a', 'b', 'c', 'A', 'B', 'C', '1', '2', '3', (byte) 0xF7}, + StandardCharsets.ISO_8859_1.name(), + "ISO-8859"); } @Test - public void detectUTF7() - { - assertEncoding( new byte[]{'+', '/', 'v', '8', 'B', 'C', '1', '2', '3'}, "UTF-7", "UTF-7 UNICODE" ); - assertEncoding( new byte[]{'+', '/', 'v', '9', 'B', 'C', '1', '2', '3'}, "UTF-7", "UTF-7 UNICODE" ); - assertEncoding( new byte[]{'+', '/', 'v', '+', 'B', 'C', '1', '2', '3'}, "UTF-7", "UTF-7 UNICODE" ); - assertEncoding( new byte[]{'+', '/', 'v', '/', 'B', 'C', '1', '2', '3'}, "UTF-7", "UTF-7 UNICODE" ); - + public void detectUTF7() { + assertEncoding(new byte[] {'+', '/', 'v', '8', 'B', 'C', '1', '2', '3'}, "UTF-7", "UTF-7 UNICODE"); + assertEncoding(new byte[] {'+', '/', 'v', '9', 'B', 'C', '1', '2', '3'}, "UTF-7", "UTF-7 UNICODE"); + assertEncoding(new byte[] {'+', '/', 'v', '+', 'B', 'C', '1', '2', '3'}, "UTF-7", "UTF-7 UNICODE"); + assertEncoding(new byte[] {'+', '/', 'v', '/', 'B', 'C', '1', '2', '3'}, "UTF-7", "UTF-7 UNICODE"); } @Test - public void detectUTF_8() - { - assertEncoding( new byte[]{'a', 'b', 'c', 'A', 'B', 'C', '1', '2', '3', (byte) 0xC3, (byte) 0xB6}, StandardCharsets.UTF_8.name(), "UTF-8 UNICODE" ); + public void detectUTF8() { + assertEncoding( + new byte[] {'a', 'b', 'c', 'A', 'B', 'C', '1', '2', '3', (byte) 0xC3, (byte) 0xB6}, + StandardCharsets.UTF_8.name(), + "UTF-8 UNICODE"); } @Test - public void detectUTF_8WithBoom() - { - assertEncoding( new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF, 'a', 'b', 'c', 'A', 'B', 'C', '1', '2', '3'}, StandardCharsets.UTF_8.name(), "UTF-8 UNICODE (WITH BOM)" ); - assertEncoding( new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF, 'a', 'b', 'c', 'A', 'B', 'C', '1', '2', '3', (byte) 0xC3, (byte) 0xB6}, StandardCharsets.UTF_8.name(), "UTF-8 UNICODE (WITH BOM)" ); + public void detectUTF8WithBoom() { + assertEncoding( + new byte[] {(byte) 0xEF, (byte) 0xBB, (byte) 0xBF, 'a', 'b', 'c', 'A', 'B', 'C', '1', '2', '3'}, + StandardCharsets.UTF_8.name(), + "UTF-8 UNICODE (WITH BOM)"); + assertEncoding( + new byte[] { + (byte) 0xEF, + (byte) 0xBB, + (byte) 0xBF, + 'a', + 'b', + 'c', + 'A', + 'B', + 'C', + '1', + '2', + '3', + (byte) 0xC3, + (byte) 0xB6 + }, + StandardCharsets.UTF_8.name(), + "UTF-8 UNICODE (WITH BOM)"); } @Test - public void detectUTF_16LE() - { - assertEncoding( new byte[]{(byte) 0xFF, (byte) 0xFE, (byte) 0xD6, (byte) 0x00, (byte) 0x41, (byte) 0x00}, StandardCharsets.UTF_16LE.name(), "LITTLE-ENDIAN UTF-16 UNICODE" ); + public void detectUTF16LE() { + assertEncoding( + new byte[] {(byte) 0xFF, (byte) 0xFE, (byte) 0xD6, (byte) 0x00, (byte) 0x41, (byte) 0x00}, + StandardCharsets.UTF_16LE.name(), + "LITTLE-ENDIAN UTF-16 UNICODE"); } @Test - public void detectUTF_16BE() - { - assertEncoding( new byte[]{(byte) 0xFE, (byte) 0xFF, (byte) 0x00, (byte) 0xD6, (byte) 0x00, (byte) 0x41}, StandardCharsets.UTF_16BE.name(), "BIG-ENDIAN UTF-16 UNICODE" ); + public void detectUTF16BE() { + assertEncoding( + new byte[] {(byte) 0xFE, (byte) 0xFF, (byte) 0x00, (byte) 0xD6, (byte) 0x00, (byte) 0x41}, + StandardCharsets.UTF_16BE.name(), + "BIG-ENDIAN UTF-16 UNICODE"); } @Test - public void detectExtendedAscii() - { - assertEncoding( new byte[]{'a', 'b', 'c', 'A', 'B', 'C', '1', '2', '3', (byte) 0x96}, "UNKNOWN-8BIT", "NON-ISO EXTENDED-ASCII" ); + public void detectExtendedAscii() { + assertEncoding( + new byte[] {'a', 'b', 'c', 'A', 'B', 'C', '1', '2', '3', (byte) 0x96}, + "UNKNOWN-8BIT", + "NON-ISO EXTENDED-ASCII"); } - private void assertEncoding( byte[] data, String codeMime, String code ) - { - rule.guessFileEncoding( data ); - assertEquals( codeMime, rule.getCodeMime().toUpperCase() ); - assertEquals( code, rule.getCode().toUpperCase() ); + private void assertEncoding(byte[] data, String codeMime, String code) { + rule.guessFileEncoding(data); + assertEquals(codeMime, rule.getCodeMime().toUpperCase()); + assertEquals(code, rule.getCode().toUpperCase()); } -} \ No newline at end of file +}