OptionalArtifactFilter.java

  1. /*
  2.  * Licensed under the Apache License, Version 2.0 (the "License");
  3.  * you may not use this file except in compliance with the License.
  4.  * You may obtain a copy of the License at
  5.  *
  6.  * http://www.apache.org/licenses/LICENSE-2.0
  7.  *
  8.  * Unless required by applicable law or agreed to in writing, software
  9.  * distributed under the License is distributed on an "AS IS" BASIS,
  10.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11.  * See the License for the specific language governing permissions and
  12.  * limitations under the License.
  13.  */

  14. package org.basepom.mojo.repack;

  15. import static com.google.common.base.Preconditions.checkNotNull;

  16. import java.util.Set;

  17. import com.google.common.collect.ImmutableSet;
  18. import org.apache.maven.artifact.Artifact;
  19. import org.apache.maven.shared.artifact.filter.collection.AbstractArtifactsFilter;

  20. final class OptionalArtifactFilter extends AbstractArtifactsFilter {

  21.     private final Set<DependencyDefinition> includeDependencies;

  22.     OptionalArtifactFilter(Set<DependencyDefinition> includedDependencies) {
  23.         this.includeDependencies = checkNotNull(includedDependencies, "includedDependencies is null");
  24.     }

  25.     @Override
  26.     public Set<Artifact> filter(Set<Artifact> artifacts) {
  27.         ImmutableSet.Builder<Artifact> builder = ImmutableSet.builder();

  28.         Artifacts:
  29.         for (Artifact artifact : artifacts) {
  30.             if (!artifact.isOptional()) {
  31.                 // not optional: included
  32.                 builder.add(artifact);
  33.             } else {
  34.                 // search for a matcher that brings the dependency in
  35.                 for (DependencyDefinition includedDependency : includeDependencies) {
  36.                     if (includedDependency.matches(artifact)) {
  37.                         builder.add(artifact);
  38.                         Reporter.addOptional(artifact);
  39.                         continue Artifacts;
  40.                     }
  41.                 }
  42.                 Reporter.addExcluded(artifact, "optional");
  43.             }
  44.         }

  45.         return builder.build();
  46.     }
  47. }