Beispiel #1
0
 protected Dependency dependency(String groupId, String artifactId, String version) {
   Dependency dependency = new Dependency();
   dependency.setGroupId(groupId);
   dependency.setArtifactId(artifactId);
   dependency.setVersion(version);
   return dependency;
 }
Beispiel #2
0
 public static String getCamelVersion(IProject project) {
   IPath pomPathValue =
       project.getProject().getRawLocation() != null
           ? project.getProject().getRawLocation().append("pom.xml")
           : ResourcesPlugin.getWorkspace()
               .getRoot()
               .getLocation()
               .append(project.getFullPath().append("pom.xml"));
   String pomPath = pomPathValue.toOSString();
   final File pomFile = new File(pomPath);
   try {
     final org.apache.maven.model.Model model = MavenPlugin.getMaven().readModel(pomFile);
     List<org.apache.maven.model.Dependency> deps = model.getDependencies();
     for (Iterator<org.apache.maven.model.Dependency> iterator = deps.iterator();
         iterator.hasNext(); ) {
       org.apache.maven.model.Dependency dependency = iterator.next();
       if (dependency.getArtifactId().equals("camel-core")) {
         return dependency.getVersion();
       }
     }
   } catch (CoreException e) {
     // not found, go with default
   }
   return org.fusesource.ide.camel.editor.Activator.getDefault().getCamelVersion();
 }
Beispiel #3
0
 private void checkOnNoDependencieVersionsFrom3rdParty(MavenProject project)
     throws EnforcerRuleException {
   Model originalModel = project.getOriginalModel();
   StringBuilder dependenciesWithVersionDeclaration = new StringBuilder();
   if (project.getGroupId().equals(ignoreMasterProjectGroupId)
       || originalModel.getDependencyManagement() == null
       || originalModel.getDependencyManagement().getDependencies() == null) {
     return;
   }
   boolean fail = false;
   for (Dependency d : originalModel.getDependencyManagement().getDependencies()) {
     if (!d.getGroupId().startsWith(allowedGroupPrefix)) {
       dependenciesWithVersionDeclaration.append(" - " + d.toString() + "\n");
       fail = true;
     }
   }
   if (fail) {
     throw new EnforcerRuleException(
         "This Project contains Dependency-Versions from 3rd party libs (not "
             + allowedGroupPrefix
             + ").\n"
             + "Please declare for maintainance reasons 3rd pary versions in "
             + ignoreMasterProjectGroupId
             + ".\n"
             + "This dependencies sould be corrected:\n"
             + dependenciesWithVersionDeclaration);
   }
 }
 public boolean accept(Edge edge, Dependency dep) {
   String scope = dep.getScope();
   if (scope == null) {
     return matcher == SegmentMatch.ANY;
   }
   return matcher.match(dep.getScope());
 }
Beispiel #5
0
  private List<File> getFrameworkExtensions() throws MojoExecutionException {
    List<File> files = new ArrayList<File>();

    if (frameworkExtensions != null) {
      for (Dependency frameworkExtension : frameworkExtensions) {
        Artifact artifact = repositorySystem.createDependencyArtifact(frameworkExtension);
        ArtifactResolutionRequest request = new ArtifactResolutionRequest();
        request.setArtifact(artifact);
        request.setResolveRoot(true).setResolveTransitively(false);
        request.setLocalRepository(session.getLocalRepository());
        request.setRemoteRepositories(project.getPluginArtifactRepositories());
        request.setOffline(session.isOffline());
        request.setForceUpdate(session.getRequest().isUpdateSnapshots());
        ArtifactResolutionResult result = repositorySystem.resolve(request);
        try {
          resolutionErrorHandler.throwErrors(request, result);
        } catch (ArtifactResolutionException e) {
          throw new MojoExecutionException(
              "Failed to resolve framework extension " + frameworkExtension.getManagementKey(), e);
        }
        files.add(artifact.getFile());
      }
    }

    return files;
  }
 /**
  * Converts an Aether artifact to a Maven model dependency.
  *
  * @param artifact the Aether artifact to be converted
  * @return a Maven dependency with the same coordinates
  */
 private Dependency artifactToDependency(Artifact artifact) {
   final Dependency dependency = new Dependency();
   dependency.setGroupId(artifact.getGroupId());
   dependency.setArtifactId(artifact.getArtifactId());
   dependency.setVersion(artifact.getVersion());
   dependency.setType(artifact.getExtension());
   return dependency;
 }
  private Set<String> findDuplicateDependencies(List<Dependency> modelDependencies) {
    List<String> modelDependencies2 = new ArrayList<String>();
    for (Dependency dep : modelDependencies) {
      modelDependencies2.add(dep.getManagementKey());
    }

    return new HashSet<String>(
        CollectionUtils.disjunction(modelDependencies2, new HashSet<String>(modelDependencies2)));
  }
  /**
   * Resolves a Maven artifact, given its coordinates, by looking it up in dependency management
   * section of POM in which the test resides.
   *
   * @param groupId Maven group id of artifact to be resolved
   * @param artifactId Maven artifact id of artifact to be resolved
   * @param type Maven type of artifact to be resolved. If not specified (null), type is not
   *     considered while finding the dependency in dependency management
   * @param classifier Maven classifier of artifact to be resolved. If not specified (null),
   *     classifier is not considered while finding the dependency in dependency management
   * @param overrideType an optional type to be used to override the type specified in dependency
   *     management (e.g nexus-plugin -> zip)
   * @param overrideClassifier an optional classifier to override the classifier specified in
   *     dependency management (e.g (not specified) -> bundle)
   * @return resolved artifact file
   */
  public File resolveFromDependencyManagement(
      final String groupId,
      final String artifactId,
      final String type,
      final String classifier,
      final String overrideType,
      final String overrideClassifier) {
    try {
      final Model model = modelResolver.resolveModel(model().pom(testProjectPomFile));

      if (model.getDependencyManagement() != null) {
        final List<Dependency> dependencies = model.getDependencyManagement().getDependencies();

        for (Dependency dependency : dependencies) {
          if (!dependency.getGroupId().equalsIgnoreCase(groupId)) {
            continue;
          }
          if (!dependency.getArtifactId().equalsIgnoreCase(artifactId)) {
            continue;
          }
          if (type != null && !dependency.getType().equals(type)) {
            continue;
          }
          if (classifier != null && !dependency.getClassifier().equals(classifier)) {
            continue;
          }

          StringBuilder coordinates = new StringBuilder();
          coordinates.append(dependency.getGroupId());
          coordinates.append(":").append(dependency.getArtifactId());

          String rExtension = dependency.getType();
          if (overrideType != null) {
            rExtension = overrideType;
          }
          if (rExtension != null) {
            coordinates.append(":").append(rExtension);
          }

          String rClassifier = dependency.getClassifier();
          if (overrideClassifier != null) {
            rClassifier = overrideClassifier;
          }
          if (rClassifier != null) {
            coordinates.append(":").append(rClassifier);
          }
          coordinates.append(":").append(dependency.getVersion());
          return resolveArtifact(coordinates.toString());
        }
      }
      throw new RuntimeException(
          String.format("Dependency %s:%s was not found", groupId, artifactId));
    } catch (Exception e) {
      throw Throwables.propagate(e);
    }
  }
 protected static String getKey(Dependency d) {
   StringBuilder sb = new StringBuilder();
   sb.append(StringUtils.defaultString(d.getGroupId())).append(":");
   sb.append(StringUtils.defaultString(d.getArtifactId())).append(":");
   sb.append(StringUtils.defaultString(d.getVersion()));
   if (StringUtils.isNotEmpty(d.getClassifier())) {
     sb.append(":").append(d.getClassifier());
   }
   return sb.toString();
 }
Beispiel #10
0
 /**
  * Convert dependencies to root artifacts.
  *
  * <p>The method is getting a list of artifacts from Maven Project, without their transitive
  * dependencies (that's why they are called "root" artifacts).
  *
  * @return The set of root artifacts
  */
 private Set<RootArtifact> roots() {
   final Set<RootArtifact> roots = new LinkedHashSet<RootArtifact>(0);
   for (Dependency dep : this.project.getDependencies()) {
     if (!this.scopes.contains(dep.getScope())) {
       continue;
     }
     roots.add(this.root(dep));
   }
   return roots;
 }
 public ProjectModule getModuleForDependency(Dependency dependency) {
   final List<ProjectModule> allModules = getFlatListOfAllModules(config.getModules());
   for (ProjectModule module : allModules) {
     if (dependency.getGroupId().equals(module.getGroupId())
         && dependency.getArtifactId().equals(module.getArtifactId())) {
       return module;
     }
   }
   return null;
 }
  @Test
  public void testInteropolateDependencies() throws Exception {
    final Model model =
        TestUtils.resolveModelResource(RESOURCE_BASE, "infinispan-bom-8.2.0.Final.pom");

    Project project = new Project(model);
    PropertyInterpolator pi = new PropertyInterpolator(project.getModel().getProperties(), project);

    String nonInterp = "", interp = "";
    for (Dependency d : project.getManagedDependencies()) {
      nonInterp +=
          (d.getGroupId().equals("${project.groupId}") ? project.getGroupId() : d.getGroupId())
              + ":"
              + (d.getArtifactId().equals("${project.artifactId}")
                  ? project.getArtifactId()
                  : d.getArtifactId())
              + System.lineSeparator();

      interp +=
          pi.interp(
                  d.getGroupId().equals("${project.groupId}")
                      ? project.getGroupId()
                      : d.getGroupId())
              + ":"
              + pi.interp(
                  d.getArtifactId().equals("${project.artifactId}")
                      ? project.getArtifactId()
                      : d.getArtifactId())
              + System.lineSeparator();
    }
    assertTrue(nonInterp.contains("${"));
    assertFalse(interp.contains("${"));
  }
Beispiel #13
0
  public List<String> getDependencies() {
    List<Dependency> deps = pom.getDependencies();
    if (deps == null) return null;

    final List<String> dependencies = new ArrayList<String>();
    for (Dependency dep : deps) {
      if (!dep.isOptional()) {
        String coords =
            dep.getGroupId()
                + ":"
                + dep.getArtifactId()
                + ":"
                + dep.getVersion()
                + (dep.getClassifier() != null && !dep.getClassifier().isEmpty()
                    ? ":" + dep.getClassifier()
                    : "");
        List<Exclusion> exclusions = dep.getExclusions();
        if (exclusions != null && !exclusions.isEmpty()) {
          StringBuilder sb = new StringBuilder();
          sb.append('(');
          for (Exclusion ex : exclusions)
            sb.append(ex.getGroupId()).append(':').append(ex.getArtifactId()).append(',');
          sb.delete(sb.length() - 1, sb.length());
          sb.append(')');
          coords += sb.toString();
        }
        dependencies.add(coords);
      }
    }
    return dependencies;
  }
  private Set<Artifact> processTransitiveDependencies(
      List<Dependency> dependencies, boolean sharedLibraries) throws MojoExecutionException {
    final Set<Artifact> transitiveArtifacts = new LinkedHashSet<Artifact>();
    for (Dependency dependency : dependencies) {
      if (!Artifact.SCOPE_PROVIDED.equals(dependency.getScope()) && !dependency.isOptional()) {
        transitiveArtifacts.addAll(processTransitiveDependencies(dependency, sharedLibraries));
      }
    }

    return transitiveArtifacts;
  }
  @Test
  public void testJacocoCommands() throws Exception {

    Project project = initializeJavaProject();
    Dependency junitDep = new Dependency();
    junitDep.setArtifactId("junit");
    junitDep.setGroupId("junit");
    junitDep.setVersion("4.10");
    junitDep.setScope("test");
    MavenCoreFacet facet = project.getFacet(MavenCoreFacet.class);
    Model pom = facet.getPOM();
    pom.addDependency(junitDep);
    facet.setPOM(pom);

    queueInputLines("");
    // create some simple classes
    getShell().execute("java new-class --package com.test \"public class A {}\"");
    getShell().execute("java new-field \"private int numberA=1;\"");
    getShell().execute("java new-method  \"public int getNumberA(){return numberA;}\"");

    getShell().execute("java new-class --package com.test \"public class B {}\"");
    getShell().execute("java new-field \"private int numberB=2;\"");
    getShell().execute("java new-method  \"public int getNumberB(){return numberB;}\"");

    // create and copy test class
    getShell()
        .execute(
            "java new-class --package com.test \"package com.test; import org.junit.Test;import static org.junit.Assert.*; public class ABTest {}\"");
    getShell()
        .execute(
            "java new-method  \"@Test public void testClasses(){A a = new A();B b = new B();assertEquals(3,a.getNumberA()+b.getNumberB());}\"");
    getShell().execute("cd " + project.getProjectRoot().getFullyQualifiedName());
    getShell().execute("cp src/main/java/com/test/ABTest.java src/test/java/");
    getShell().execute("rm -rf src/main/java/com/test/ABTest.java");

    // run jacoco plugin commands
    getShell().execute("jacoco setup");
    getShell().execute("jacoco run-tests --package com.test");
    queueInputLines("N");
    getShell().execute("jacoco create-report");

    assertTrue(
        "Missing jacoco.exec file!",
        project.getProjectRoot().getChildDirectory("target").getChild("jacoco.exec").exists());
    assertTrue(
        "Missing index.html report file!",
        project
            .getProjectRoot()
            .getChildDirectory("target")
            .getChildDirectory("site")
            .getChildDirectory("jacoco")
            .getChild("index.html")
            .exists());
  }
  protected DependencyArtifacts doResolvePlatform(
      final MavenSession session,
      final MavenProject project,
      List<ReactorProject> reactorProjects,
      DependencyResolverConfiguration resolverConfiguration,
      TargetPlatform resolutionContext,
      P2Resolver resolver,
      TargetPlatformConfiguration configuration) {

    Map<File, ReactorProject> projects = new HashMap<File, ReactorProject>();

    resolver.setEnvironments(getEnvironments(configuration));

    for (ReactorProject otherProject : reactorProjects) {
      projects.put(otherProject.getBasedir(), otherProject);
    }

    if (resolverConfiguration != null) {
      for (Dependency dependency : resolverConfiguration.getExtraRequirements()) {
        resolver.addDependency(
            dependency.getType(), dependency.getArtifactId(), dependency.getVersion());
      }
    }

    if (!isAllowConflictingDependencies(project, configuration)) {
      List<P2ResolutionResult> results =
          resolver.resolveProject(resolutionContext, project.getBasedir());

      MultiEnvironmentTargetPlatform multiPlatform =
          new MultiEnvironmentTargetPlatform(DefaultReactorProject.adapt(project));

      // FIXME this is just wrong
      for (int i = 0; i < configuration.getEnvironments().size(); i++) {
        TargetEnvironment environment = configuration.getEnvironments().get(i);
        P2ResolutionResult result = results.get(i);

        DefaultTargetPlatform platform =
            newDefaultTargetPlatform(
                session, DefaultReactorProject.adapt(project), projects, result);

        // addProjects( session, platform );

        multiPlatform.addPlatform(environment, platform);
      }

      return multiPlatform;
    } else {
      P2ResolutionResult result =
          resolver.collectProjectDependencies(resolutionContext, project.getBasedir());

      return newDefaultTargetPlatform(
          session, DefaultReactorProject.adapt(project), projects, result);
    }
  }
  /**
   * Returns only the dependencies matching the supplied group ID value, filtering out all others.
   *
   * @param dependencies A list of dependencies to be filtered.
   * @return The filtered list of dependencies.
   */
  private List<Dependency> filterGrailsDependencies(final List<Dependency> dependencies) {
    final List<Dependency> filteredDependencies = new ArrayList<Dependency>();
    for (final Dependency dependency : dependencies) {

      if (dependency.getArtifactId().equals("grails-scripts")
          || dependency.getArtifactId().equals("grails-bootstrap")
          || dependency.getArtifactId().equals("grails-launcher")) {
        filteredDependencies.add(dependency);
      }
    }
    return filteredDependencies;
  }
Beispiel #18
0
 @Override
 protected boolean doModify(Model model, Dependency dependency) {
   String depArtifId = dependency.getArtifactId();
   if (R_MAP.containsKey(depArtifId)) {
     String[] replacement = R_MAP.get(depArtifId);
     dependency.setArtifactId(replacement[0]);
     if (replacement.length > 1) dependency.setGroupId(replacement[1]);
     if (replacement.length > 2) dependency.setVersion(replacement[2]);
     return true;
   }
   return false;
 }
  public GemSpecification createSpecification(final MavenArtifact artifact) {
    final GemSpecification result = new GemSpecification();

    // this is fix
    result.setPlatform(this.PLATFORM_JAVA);

    // the must ones
    result.setName(
        createGemName(
            artifact.getCoordinates().getGroupId(),
            artifact.getCoordinates().getArtifactId(),
            artifact.getCoordinates().getVersion()));
    result.setVersion(new GemVersion(createGemVersion(artifact.getCoordinates().getVersion())));

    // dependencies
    if (artifact.getPom().getDependencies().size() > 0) {
      for (final Dependency dependency : artifact.getPom().getDependencies()) {
        if (!dependency.isOptional()) {
          result.getDependencies().add(convertDependency(artifact, dependency));
        }
      }
    }

    // and other stuff "nice to have"
    result.setDate(new Date()); // now
    result.setDescription(
        sanitizeStringValue(
            artifact.getPom().getDescription() != null
                ? artifact.getPom().getDescription()
                : artifact.getPom().getName()));
    result.setSummary(sanitizeStringValue(artifact.getPom().getName()));
    result.setHomepage(sanitizeStringValue(artifact.getPom().getUrl()));

    if (artifact.getPom().getLicenses().size() > 0) {
      for (final License license : artifact.getPom().getLicenses()) {
        result
            .getLicenses()
            .add(sanitizeStringValue(license.getName() + " (" + license.getUrl() + ")"));
      }
    }
    if (artifact.getPom().getDevelopers().size() > 0) {
      for (final Developer developer : artifact.getPom().getDevelopers()) {
        result
            .getAuthors()
            .add(sanitizeStringValue(developer.getName() + " (" + developer.getEmail() + ")"));
      }
    }

    // by default, we pack into lib/ inside gem (where is the jar and the
    // stub ruby)
    result.getRequire_paths().add("lib");
    return result;
  }
  private void useLatestSnapshots(ModifiedPomXMLEventReader pom, Collection dependencies)
      throws XMLStreamException, MojoExecutionException, ArtifactMetadataRetrievalException {
    int segment =
        determineUnchangedSegment(allowMajorUpdates, allowMinorUpdates, allowIncrementalUpdates);

    Iterator i = dependencies.iterator();

    while (i.hasNext()) {
      Dependency dep = (Dependency) i.next();

      if (isExcludeReactor() && isProducedByReactor(dep)) {
        getLog().info("Ignoring reactor dependency: " + toString(dep));
        continue;
      }

      String version = dep.getVersion();
      Matcher versionMatcher = matchSnapshotRegex.matcher(version);
      if (!versionMatcher.matches()) {
        getLog().debug("Looking for latest snapshot of " + toString(dep));
        Artifact artifact = this.toArtifact(dep);
        if (!isIncluded(artifact)) {
          continue;
        }

        ArtifactVersions versions = getHelper().lookupArtifactVersions(artifact, false);
        final VersionComparator versionComparator = versions.getVersionComparator();
        final DefaultArtifactVersion lowerBound = new DefaultArtifactVersion(version);
        if (segment + 1 > versionComparator.getSegmentCount(lowerBound)) {
          getLog().info("Ignoring " + toString(dep) + " as the version number is too short");
          continue;
        }
        ArtifactVersion upperBound =
            segment >= 0 ? versionComparator.incrementSegment(lowerBound, segment) : null;
        getLog().info("Upper bound: " + (upperBound == null ? "none" : upperBound.toString()));
        ArtifactVersion[] newer = versions.getVersions(lowerBound, upperBound, true, false, false);
        getLog().debug("Candidate versions " + Arrays.asList(newer));
        String latestVersion = null;
        for (int j = 0; j < newer.length; j++) {
          String newVersion = newer[j].toString();
          if (matchSnapshotRegex.matcher(newVersion).matches()) {
            latestVersion = newVersion;
          }
        }
        if (latestVersion != null) {
          if (PomHelper.setDependencyVersion(
              pom, dep.getGroupId(), dep.getArtifactId(), version, latestVersion)) {
            getLog().info("Updated " + toString(dep) + " to version " + latestVersion);
          }
        }
      }
    }
  }
  private List<Dependency> replaceVersion(List<Dependency> dependencies) {
    if (grailsVersion != null) {
      for (Dependency d : dependencies) {
        if ("org.grails".equals(d.getGroupId())
            && !grailsVersion.equals(d.getVersion())
            && grailsVersion.charAt(0) == d.getVersion().charAt(0)) {
          d.setVersion(grailsVersion);
        }
      }
    }

    return dependencies;
  }
 private String getDependencyVersion(final MavenArtifact artifact, final Dependency dependency) {
   if (dependency.getVersion() != null) {
     return dependency.getVersion();
   } else if (StringUtils.equals(
       artifact.getCoordinates().getGroupId(), dependency.getGroupId())) {
     // hm, this is same groupId, let's suppose they have same
     // dependency!
     return artifact.getCoordinates().getVersion();
   } else {
     // no help here, just interpolated POM
     return "unknown";
   }
 }
  private Set<Artifact> processTransitiveDependencies(
      Dependency dependency, boolean sharedLibraries) throws MojoExecutionException {
    log.debug("Processing transitive dependencies for : " + dependency);

    try {
      final Set<Artifact> artifacts = new LinkedHashSet<Artifact>();

      final List<String> exclusionPatterns = new ArrayList<String>();
      if (dependency.getExclusions() != null && !dependency.getExclusions().isEmpty()) {
        for (final Exclusion exclusion : dependency.getExclusions()) {
          exclusionPatterns.add(exclusion.getGroupId() + ":" + exclusion.getArtifactId());
        }
      }
      final ArtifactFilter optionalFilter =
          new ArtifactFilter() {
            @Override
            public boolean include(Artifact artifact) {
              return !artifact.isOptional();
            }
          };

      final AndArtifactFilter filter = new AndArtifactFilter();
      filter.add(new ExcludesArtifactFilter(exclusionPatterns));
      filter.add(
          new OrArtifactFilter(
              Arrays.<ArtifactFilter>asList(
                  new ScopeArtifactFilter("compile"),
                  new ScopeArtifactFilter("runtime"),
                  new ScopeArtifactFilter("test"))));
      filter.add(optionalFilter);

      final DependencyNode node = dependencyGraphBuilder.buildDependencyGraph(project, filter);
      final CollectingDependencyNodeVisitor collectingVisitor =
          new CollectingDependencyNodeVisitor();
      node.accept(collectingVisitor);

      final List<DependencyNode> dependencies = collectingVisitor.getNodes();
      for (final DependencyNode dep : dependencies) {
        final boolean isNativeLibrary =
            isNativeLibrary(sharedLibraries, dep.getArtifact().getType());
        log.debug("Processing library : " + dep.getArtifact() + " isNative=" + isNativeLibrary);
        if (isNativeLibrary) {
          artifacts.add(dep.getArtifact());
        }
      }

      return artifacts;
    } catch (Exception e) {
      throw new MojoExecutionException("Error while processing transitive dependencies", e);
    }
  }
Beispiel #24
0
  /**
   * Initializes the reference paths from the given project's dependencies.
   *
   * @param project The maven project.
   * @throws MojoExecutionException
   */
  @SuppressWarnings({"rawtypes", "unchecked"})
  void initReferencePaths(MavenProject project) throws MojoExecutionException {
    List deps = project.getDependencies();

    if (deps == null) {
      debug("not processing project dependencies because they're null: " + project.getName());
      return;
    }

    if (deps.size() == 0) {
      debug(
          "not processing project dependencies because they're zero length: " + project.getName());
      return;
    }

    if (this.referencePaths == null) {
      this.referencePaths = new ArrayList();
    }

    for (Object od : deps) {
      Dependency d = (Dependency) od;

      if (StringUtils.isEmpty(d.getType())) {
        continue;
      }

      if (!d.getType().matches("dll|exe")) {
        continue;
      }

      File file = DependencyUtils.getArtifactFile(super.factory, super.localRepository, d);

      if (file == null) {
        continue;
      }

      if (!this.referencePaths.contains(file.getParentFile())) {
        this.referencePaths.add(file.getParentFile());

        String assemblyName =
            DependencyUtils.getAssemblyName(
                super.factory,
                super.localRepository,
                super.mavenProject.getRemoteArtifactRepositories(),
                super.resolver,
                d);

        DependencyUtils.copyToAssemblyNamedFiles(file, assemblyName);
      }
    }
  }
Beispiel #25
0
  // generic method to retrieve all the transitive dependencies
  private Collection<Artifact> getAllDependencies() throws MojoExecutionException {
    List<Artifact> artifacts = new ArrayList<Artifact>();

    for (Iterator<?> dependencies = project.getDependencies().iterator();
        dependencies.hasNext(); ) {
      Dependency dependency = (Dependency) dependencies.next();

      String groupId = dependency.getGroupId();
      String artifactId = dependency.getArtifactId();

      VersionRange versionRange;
      try {
        versionRange = VersionRange.createFromVersionSpec(dependency.getVersion());
      } catch (InvalidVersionSpecificationException e) {
        throw new MojoExecutionException("unable to parse version", e);
      }

      String type = dependency.getType();
      if (type == null) {
        type = "jar";
      }
      String classifier = dependency.getClassifier();
      boolean optional = dependency.isOptional();
      String scope = dependency.getScope();
      if (scope == null) {
        scope = Artifact.SCOPE_COMPILE;
      }

      Artifact art =
          this.artifactFactory.createDependencyArtifact(
              groupId, artifactId, versionRange, type, classifier, scope, null, optional);

      if (scope.equalsIgnoreCase(Artifact.SCOPE_SYSTEM)) {
        art.setFile(new File(dependency.getSystemPath()));
      }

      List<String> exclusions = new ArrayList<String>();
      for (Iterator<?> j = dependency.getExclusions().iterator(); j.hasNext(); ) {
        Exclusion e = (Exclusion) j.next();
        exclusions.add(e.getGroupId() + ":" + e.getArtifactId());
      }

      ArtifactFilter newFilter = new ExcludesArtifactFilter(exclusions);

      art.setDependencyFilter(newFilter);

      artifacts.add(art);
    }

    return artifacts;
  }
  /*
   * (non-Javadoc)
   *
   * @see junit.framework.TestCase#setUp()
   */
  @Override
  protected void setUp() throws Exception {
    tempModel =
        (IDOMModel)
            StructuredModelManager.getModelManager()
                .createUnManagedStructuredModelFor("org.eclipse.m2e.core.pomFile");
    document = tempModel.getStructuredDocument();

    d = new Dependency();
    d.setArtifactId("BBBB");
    d.setGroupId("AAA");
    d.setVersion("1.0");

    e = new ArtifactKey("g", "a", "1.0", null);
  }
 /**
  * Adds information about artifact dependencies.
  *
  * @param dependent The dependent to add artifacts as dependencies
  * @param dependencies The dependencies information.
  * @param scannerContext The scanner context
  */
 private <P extends MavenDependentDescriptor, D extends BaseDependencyDescriptor>
     void addDependencies(
         P dependent,
         List<Dependency> dependencies,
         Class<D> dependencyType,
         ScannerContext scannerContext) {
   for (Dependency dependency : dependencies) {
     MavenArtifactDescriptor dependencyArtifactDescriptor =
         getMavenArtifactDescriptor(dependency, scannerContext);
     D dependencyDescriptor =
         scannerContext.getStore().create(dependent, dependencyType, dependencyArtifactDescriptor);
     dependencyDescriptor.setOptional(dependency.isOptional());
     dependencyDescriptor.setScope(dependency.getScope());
   }
 }
  private Set<Artifact> processTransientDependencies(
      List<org.apache.maven.model.Dependency> dependencies, boolean sharedLibraries)
      throws MojoExecutionException {

    Set<Artifact> transientArtifacts = new LinkedHashSet<Artifact>();
    for (org.apache.maven.model.Dependency dependency : dependencies) {
      if (!"provided".equals(dependency.getScope()) && !dependency.isOptional()) {
        transientArtifacts.addAll(
            processTransientDependencies(
                toDependency(dependency, repoSession.getArtifactTypeRegistry()), sharedLibraries));
      }
    }

    return transientArtifacts;
  }
  public void testAddExclusion_existingExclusion() throws Exception {
    document.setText(
        StructuredModelManager.getModelManager(), //
        "<project><dependencies>"
            + //
            "<dependency><groupId>AAA</groupId><artifactId>BBB</artifactId><version>1.0</version></dependency>"
            + //
            "<dependency><groupId>AAAB</groupId><artifactId>BBB</artifactId><version>1.0</version></dependency>"
            + //
            "<dependency><groupId>AAA</groupId><artifactId>BBBB</artifactId><version>1.0</version>"
            + //
            "<exclusions><exclusion><groupId>g</groupId><artifactId>b</artifactId><version>1.0</version></exclusion></exclusions></dependency>"
            + //
            "</dependencies></project>");
    PomEdits.performOnDOMDocument(new OperationTuple(tempModel, new AddExclusionOperation(d, e)));
    assertEquals(
        "Expected no dependency: " + d.toString() + "\n" + document.getText(),
        1,
        dependencyCount(tempModel, d));
    assertTrue(
        "Has exclusion " + e.toString() + "\n" + document.getText(), hasExclusion(tempModel, d, e));

    ArtifactKey key = new ArtifactKey("g", "b", "1.0", null);
    assertTrue(
        "Existing Exclusion Present " + key.toString() + "\n" + document.getText(),
        hasExclusion(tempModel, d, key));
    assertEquals("Exclusions", 2, getExclusionCount(tempModel, d));
    assertEquals("Dependency Count: \n" + document.getText(), 3, getDependencyCount(tempModel));
  }
 static InputLocation findLocationForManagedArtifact(
     final ManagedArtifactRegion region, MavenProject mavprj) {
   Model mdl = mavprj.getModel();
   InputLocation openLocation = null;
   if (region.isDependency) {
     DependencyManagement dm = mdl.getDependencyManagement();
     if (dm != null) {
       List<Dependency> list = dm.getDependencies();
       String id = region.groupId + ":" + region.artifactId + ":"; // $NON-NLS-1$ //$NON-NLS-2$
       if (list != null) {
         for (Dependency dep : list) {
           if (dep.getManagementKey().startsWith(id)) {
             InputLocation location = dep.getLocation(ARTIFACT_ID); // $NON-NLS-1$
             // when would this be null?
             if (location != null) {
               openLocation = location;
               break;
             }
           }
         }
       }
     }
   }
   if (region.isPlugin) {
     Build build = mdl.getBuild();
     if (build != null) {
       PluginManagement pm = build.getPluginManagement();
       if (pm != null) {
         List<Plugin> list = pm.getPlugins();
         String id = Plugin.constructKey(region.groupId, region.artifactId);
         if (list != null) {
           for (Plugin plg : list) {
             if (id.equals(plg.getKey())) {
               InputLocation location = plg.getLocation(ARTIFACT_ID); // $NON-NLS-1$
               // when would this be null?
               if (location != null) {
                 openLocation = location;
                 break;
               }
             }
           }
         }
       }
     }
   }
   return openLocation;
 }