private Map<String, Artifact> createManagedVersionMap() throws MojoExecutionException {
   Map<String, Artifact> map = new HashMap<String, Artifact>();
   DependencyManagement dependencyManagement = project.getDependencyManagement();
   if (dependencyManagement != null && dependencyManagement.getDependencies() != null) {
     for (Dependency d : dependencyManagement.getDependencies()) {
       try {
         VersionRange versionRange = VersionRange.createFromVersionSpec(d.getVersion());
         Artifact artifact =
             artifactFactory.createDependencyArtifact(
                 d.getGroupId(),
                 d.getArtifactId(),
                 versionRange,
                 d.getType(),
                 d.getClassifier(),
                 d.getScope(),
                 d.isOptional());
         handleExclusions(artifact, d);
         map.put(d.getManagementKey(), artifact);
       } catch (InvalidVersionSpecificationException e) {
         throw new MojoExecutionException(
             String.format(
                 "%1s: unable to parse version '%2s' for dependency '%3s': %4s",
                 project.getId(), d.getVersion(), d.getManagementKey(), e.getMessage()),
             e);
       }
     }
   }
   return map;
 }
 @SuppressWarnings("unchecked")
 private Set<Artifact> getAllArtifacts() throws MojoExecutionException {
   Set<Artifact> artifacts = new LinkedHashSet<Artifact>();
   for (Dependency dep : (List<Dependency>) project.getDependencies()) {
     VersionRange versionRange;
     try {
       versionRange = VersionRange.createFromVersionSpec(dep.getVersion());
     } catch (InvalidVersionSpecificationException e) {
       throw new MojoExecutionException(
           String.format(
               "%1s: unable to parse version '%2s' for dependency '%3s': %4s",
               dep.getArtifactId(), dep.getVersion(), dep.getManagementKey(), e.getMessage()),
           e);
     }
     String type = dep.getType() == null ? "jar" : dep.getType();
     boolean optional = dep.isOptional();
     String scope = dep.getScope() == null ? Artifact.SCOPE_COMPILE : dep.getScope();
     Artifact artifact =
         artifactFactory.createDependencyArtifact(
             dep.getGroupId(),
             dep.getArtifactId(),
             versionRange,
             type,
             dep.getClassifier(),
             scope,
             optional);
     if (scope.equalsIgnoreCase(Artifact.SCOPE_SYSTEM)) {
       artifact.setFile(new File(dep.getSystemPath()));
     }
     handleExclusions(artifact, dep);
     artifacts.add(artifact);
   }
   return artifacts;
 }
  private List<String> alterModel(MavenProject project, String newVersion) {
    Model originalModel = project.getOriginalModel();
    originalModel.setVersion(newVersion);

    List<String> errors = new ArrayList<String>();

    String searchingFrom = project.getArtifactId();
    MavenProject parent = project.getParent();
    if (parent != null && isSnapshot(parent.getVersion())) {
      try {
        ReleasableModule parentBeingReleased =
            reactor.find(parent.getGroupId(), parent.getArtifactId(), parent.getVersion());
        originalModel.getParent().setVersion(parentBeingReleased.getVersionToDependOn());
        log.debug(
            " Parent "
                + parentBeingReleased.getArtifactId()
                + " rewritten to version "
                + parentBeingReleased.getVersionToDependOn());
      } catch (UnresolvedSnapshotDependencyException e) {
        errors.add("The parent of " + searchingFrom + " is " + e.artifactId + " " + e.version);
      }
    }
    for (Dependency dependency : originalModel.getDependencies()) {
      String version = dependency.getVersion();
      if (isSnapshot(version)) {
        try {
          ReleasableModule dependencyBeingReleased =
              reactor.find(dependency.getGroupId(), dependency.getArtifactId(), version);
          dependency.setVersion(dependencyBeingReleased.getVersionToDependOn());
          log.debug(
              " Dependency on "
                  + dependencyBeingReleased.getArtifactId()
                  + " rewritten to version "
                  + dependencyBeingReleased.getVersionToDependOn());
        } catch (UnresolvedSnapshotDependencyException e) {
          errors.add(searchingFrom + " references dependency " + e.artifactId + " " + e.version);
        }
      } else
        log.debug(
            " Dependency on "
                + dependency.getArtifactId()
                + " kept at version "
                + dependency.getVersion());
    }
    for (Plugin plugin : project.getModel().getBuild().getPlugins()) {
      String version = plugin.getVersion();
      if (isSnapshot(version)) {
        if (!isMultiModuleReleasePlugin(plugin)) {
          errors.add(
              searchingFrom + " references plugin " + plugin.getArtifactId() + " " + version);
        }
      }
    }
    return errors;
  }
  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 boolean match(Dependency dependency, Artifact artifact) {
    boolean match =
        dependency.getGroupId().equals(artifact.getGroupId())
            && dependency.getArtifactId().equals(artifact.getArtifactId())
            && dependency.getVersion().equals(artifact.getVersion());

    if (match) {
      if (dependency.getClassifier() == null) {
        match = artifact.getClassifier() == null;
      } else {
        match = dependency.getClassifier().equals(artifact.getClassifier());
      }
    }

    if (match) {
      String type = artifact.getType();
      if (dependency.getType() == null) {
        match = type == null || type.equals("jar");
      } else {
        match = dependency.getType().equals(type);
      }
    }

    return match;
  }
示例#7
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();
 }
示例#8
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;
  }
  /**
   * 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);
    }
  }
  /**
   * Compare the list of selected dependencies against the selected targetPOM. If one of the
   * dependencies is already under dependencyManagement, but has a different version than the
   * selected dependency, warn the user about this. returns true if the user has been warned (but
   * this method updates the status itself)
   *
   * @param model
   * @param dependencies
   */
  protected boolean checkDependencies(
      org.apache.maven.model.Model model, LinkedList<Dependency> dependencies) {
    if (this.status != null && this.status.getCode() == IStatus.ERROR) {
      // Don't warn the user if there is already an error
      return false;
    }
    if (model == null
        || model.getDependencyManagement() == null
        || model.getDependencyManagement().getDependencies() == null
        || model.getDependencyManagement().getDependencies().isEmpty()) {
      return false;
    }

    for (Dependency selectedDep : dependencies) {
      for (org.apache.maven.model.Dependency targetDep :
          model.getDependencyManagement().getDependencies()) {
        if (selectedDep.getGroupId().equals(targetDep.getGroupId())
            && selectedDep.getArtifactId().equals(targetDep.getArtifactId())
            && !selectedDep.getVersion().equals(targetDep.getVersion())) {
          String modelID =
              model.getGroupId()
                  + ":"
                  + model.getArtifactId()
                  + ":"
                  + model.getVersion(); // $NON-NLS-1$ //$NON-NLS-2$
          if (targetDep.getLocation("") != null
              && targetDep.getLocation("").getSource() != null) { // $NON-NLS-1$ //$NON-NLS-2$
            modelID = targetDep.getLocation("").getSource().getModelId(); // $NON-NLS-1$
          }
          Object[] arguments = {
            selectedDep.getArtifactId() + "-" + selectedDep.getVersion(), // $NON-NLS-1$
            targetDep.getVersion(),
            modelID
          };
          String message =
              NLS.bind(Messages.ManageDependenciesDialog_dependencyExistsWarning, arguments);
          updateStatus(new Status(IStatus.WARNING, MavenEditorPlugin.PLUGIN_ID, message));
          return true;
        }
      }
    }
    return false;
  }
 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();
 }
  private void enforceProjectVersion(
      final Project project, final List<Dependency> dependencies, final Set<Project> changed) {
    for (final Dependency d : dependencies) {
      if (d.getVersion() != null && d.getVersion().contains(PROJVER)) {
        String newVersion =
            project.getModel().getVersion() == null
                ? project.getModel().getParent().getVersion()
                : project.getModel().getVersion();

        logger.info(
            "Replacing project.version within {} for project {} with {}", d, project, newVersion);
        logger.debug(
            "Original version is " + project.getVersion() + " and model is " + project.getModel());

        d.setVersion(newVersion);
        changed.add(project);
      }
    }
  }
示例#13
0
 /**
  * Convert dependency to root artifact.
  *
  * @param dep Dependency
  * @return Root artifact
  */
 private RootArtifact root(final Dependency dep) {
   return new RootArtifact(
       this.aether,
       new DefaultArtifact(
           dep.getGroupId(),
           dep.getArtifactId(),
           dep.getClassifier(),
           dep.getType(),
           dep.getVersion()),
       dep.getExclusions());
 }
  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);
    }
  }
 /**
  * {@inheritDoc}
  *
  * <p>The text returned for objects of type <code>Dependency</code> contains the following
  * information about the dependency:
  *
  * <p>{groupId} - {artifactId} - {version} - {type}
  */
 public String getText(Object element) {
   if (element instanceof Dependency) {
     Dependency d = (Dependency) element;
     return d.getGroupId()
         + ":"
         + d.getArtifactId()
         + ":"
         + d.getVersion()
         + (d.getClassifier() == null ? "" : ":" + d.getClassifier());
   }
   return super.getText(element);
 }
  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);
          }
        }
      }
    }
  }
示例#17
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;
  }
示例#18
0
  // DefaultProjectBuilder
  public Artifact createDependencyArtifact(Dependency d) {
    if (d.getVersion() == null) {
      return null;
    }

    VersionRange versionRange;
    try {
      versionRange = VersionRange.createFromVersionSpec(d.getVersion());
    } catch (InvalidVersionSpecificationException e) {
      return null;
    }

    Artifact artifact =
        XcreateDependencyArtifact(
            d.getGroupId(),
            d.getArtifactId(),
            versionRange,
            d.getType(),
            d.getClassifier(),
            d.getScope(),
            d.isOptional());

    if (Artifact.SCOPE_SYSTEM.equals(d.getScope()) && d.getSystemPath() != null) {
      artifact.setFile(new File(d.getSystemPath()));
    }

    if (!d.getExclusions().isEmpty()) {
      List<String> exclusions = new ArrayList<>();

      for (Exclusion exclusion : d.getExclusions()) {
        exclusions.add(exclusion.getGroupId() + ':' + exclusion.getArtifactId());
      }

      artifact.setDependencyFilter(new ExcludesArtifactFilter(exclusions));
    }

    return artifact;
  }
 @Override
 public String toString() {
   return dependency.getGroupId()
       + ":"
       + dependency.getArtifactId()
       + ":"
       + dependency.getVersion()
       + ":"
       + dependency.getType()
       + ":"
       + dependency.getScope()
       + ":"
       + dependency.getClassifier();
 }
 /**
  * Uses the injected artifact factory to convert a single Dependency object into an Artifact
  * instance.
  *
  * @param dep The dependency to convert.
  * @return The resulting Artifact.
  */
 private Artifact dependencyToArtifact(final Dependency dep) {
   //    return this.artifactFactory.createBuildArtifact(
   //      dep.getGroupId(),
   //      dep.getArtifactId(),
   //      dep.getVersion(),
   //      "pom");
   return this.artifactFactory.createDependencyArtifact(
       dep.getGroupId(),
       dep.getArtifactId(),
       VersionRange.createFromVersion(dep.getVersion()),
       dep.getType(),
       dep.getClassifier(),
       dep.getScope());
 }
  private Map createManagedVersionMap(
      ArtifactFactory artifactFactory, String projectId, DependencyManagement dependencyManagement)
      throws MojoExecutionException {
    Map map;
    if (dependencyManagement != null && dependencyManagement.getDependencies() != null) {
      map = new HashMap();
      for (Iterator i = dependencyManagement.getDependencies().iterator(); i.hasNext(); ) {
        Dependency d = (Dependency) i.next();

        try {
          VersionRange versionRange = VersionRange.createFromVersionSpec(d.getVersion());
          Artifact artifact =
              artifactFactory.createDependencyArtifact(
                  d.getGroupId(),
                  d.getArtifactId(),
                  versionRange,
                  d.getType(),
                  d.getClassifier(),
                  d.getScope(),
                  d.isOptional());
          map.put(d.getManagementKey(), artifact);
        } catch (InvalidVersionSpecificationException e) {
          throw new MojoExecutionException(
              Messages.getString(
                  "unabletoparseversion",
                  new Object[] { // $NON-NLS-1$
                    projectId, d.getVersion(), d.getManagementKey(), e.getMessage()
                  }),
              e);
        }
      }
    } else {
      map = Collections.EMPTY_MAP;
    }
    return map;
  }
示例#22
0
 private Dependency toAetherDependency(org.apache.maven.model.Dependency dependency) {
   Artifact artifact =
       new DefaultArtifact(
           dependency.getGroupId(),
           dependency.getArtifactId(),
           dependency.getClassifier(),
           dependency.getType(),
           dependency.getVersion());
   ImmutableList.Builder<Exclusion> exclusions = ImmutableList.builder();
   for (org.apache.maven.model.Exclusion exclusion : dependency.getExclusions()) {
     exclusions.add(new Exclusion(exclusion.getGroupId(), exclusion.getArtifactId(), null, "*"));
   }
   return new Dependency(
       artifact, dependency.getScope(), dependency.isOptional(), exclusions.build());
 }
示例#23
0
  public static void updateMavenDependencies(
      final List<Dependency> dependencies, final IProject project) throws CoreException {
    final IFile pomIFile = project.getProject().getFile("pom.xml");
    final File pomFile = new File(pomIFile.getLocationURI());
    final org.apache.maven.model.Model pom = MavenPlugin.getMaven().readModel(pomFile);

    // Check if dependency already in the pom
    final List<Dependency> missingDependencies = new ArrayList<>();
    for (final Dependency dependency : dependencies) {
      boolean found = false;
      for (final org.apache.maven.model.Dependency pomDependency : pom.getDependencies()) {
        if (pomDependency.getGroupId().equalsIgnoreCase(dependency.getGroupId())
            && pomDependency.getArtifactId().equalsIgnoreCase(dependency.getArtifactId())) {
          // check for correct version
          if (!pomDependency.getVersion().equalsIgnoreCase(dependency.getVersion())) {
            pomDependency.setVersion(dependency.getVersion());
          }
          found = true;
          break;
        }
      }
      if (!found) {
        missingDependencies.add(dependency);
      }
    }

    for (final Dependency dependency : missingDependencies) {
      final org.apache.maven.model.Dependency pomDependency =
          new org.apache.maven.model.Dependency();
      pomDependency.setGroupId(dependency.getGroupId());
      pomDependency.setArtifactId(dependency.getArtifactId());
      pomDependency.setVersion(dependency.getVersion());
      pom.addDependency(pomDependency);
    }

    if (!missingDependencies.isEmpty()) {
      try (final OutputStream stream = new BufferedOutputStream(new FileOutputStream(pomFile))) {
        MavenPlugin.getMaven().writeModel(pom, stream);
        pomIFile.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
      } catch (final Exception e) {
        Activator.error(e);
      }
    }
  }
  private DependencyInfo getDependencyInfo(Dependency dependency) {
    DependencyInfo info = new DependencyInfo();

    // dependency data
    info.setGroupId(dependency.getGroupId());
    info.setArtifactId(dependency.getArtifactId());
    info.setVersion(dependency.getVersion());
    info.setScope(dependency.getScope());
    info.setClassifier(dependency.getClassifier());
    info.setOptional(dependency.isOptional());
    info.setType(dependency.getType());
    info.setSystemPath(dependency.getSystemPath());

    // exclusions
    Collection<ExclusionInfo> exclusions = info.getExclusions();
    final List<Exclusion> mavenExclusions = dependency.getExclusions();
    for (Exclusion exclusion : mavenExclusions) {
      exclusions.add(new ExclusionInfo(exclusion.getGroupId(), exclusion.getArtifactId()));
    }

    return info;
  }
示例#25
0
 private void checkOnNoDependencieVersion(MavenProject project) throws EnforcerRuleException {
   Model originalModel = project.getOriginalModel();
   StringBuilder dependenciesWithVersionDeclaration = new StringBuilder();
   boolean fail = false;
   for (Dependency d : originalModel.getDependencies()) {
     if (d.getVersion() != null) {
       dependenciesWithVersionDeclaration.append(" - " + d.toString() + "\n");
       fail = true;
     }
   }
   if (fail) {
     throw new EnforcerRuleException(
         "This project contains explicit dependeny versions.\n"
             + "Please declare for maintainance reasons 3rd pary versions in "
             + ignoreMasterProjectGroupId
             + " or\n"
             + "in case of bei '"
             + allowedGroupPrefix
             + "*' Libs in the root pom in the 'dependencyManagement' section.\n"
             + "This dependencies sould be corrected:\n"
             + dependenciesWithVersionDeclaration);
   }
 }
  private File generateRubyStub(
      final GemSpecification gemspec, final MavenArtifact artifact, final RubyDependencyType type)
      throws IOException {
    final VelocityContext context = new VelocityContext();
    switch (type) {
      case RUNTIME:
        if (artifact.getArtifactFile() != null) {
          context.put(
              "jarfile",
              createJarfileName(
                  artifact.getCoordinates().getGroupId(),
                  artifact.getCoordinates().getArtifactId(),
                  artifact.getCoordinates().getVersion()));
        }
        break;
      case DEVELOPMENT:
        context.put("filename", artifact.getCoordinates().getArtifactId() + ".rb");
        break;
    }
    final List<MavenDependency> deps = new ArrayList<MavenDependency>();
    for (final Dependency dependency : artifact.getPom().getDependencies()) {
      if (RubyDependencyType.toRubyDependencyType(dependency.getScope()) == type
          && !dependency.isOptional()) {
        final MavenDependency mavenDependency = new MavenDependency();
        mavenDependency.name =
            createRequireName(
                dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion());
        for (final Exclusion exclusion : dependency.getExclusions()) {
          mavenDependency.exclusions.add(exclusion.getGroupId() + "/" + exclusion.getArtifactId());
        }
        deps.add(mavenDependency);
      }
    }
    context.put("dependencies", deps);

    return generateRubyFile("require" + type.name(), context, "rubyStub" + type.name());
  }
示例#27
0
  /**
   * @param isPom <code>true</code> to lookup the <code>maven-model</code> artifact jar, <code>false
   *     </code> to lookup the <code>maven-settings</code> artifact jar.
   * @return the <code>org.apache.maven:maven-model|maven-settings</code> artifact jar file for this
   *     current HelpPlugin pom.
   * @throws MojoExecutionException if any
   * @throws ProjectBuildingException if any
   * @throws ArtifactResolutionException if any
   * @throws ArtifactNotFoundException if any
   */
  private File getArtifactFile(boolean isPom)
      throws MojoExecutionException, ProjectBuildingException, ArtifactResolutionException,
          ArtifactNotFoundException {
    @SuppressWarnings("unchecked")
    List<Dependency> dependencies = getHelpPluginPom().getDependencies();
    for (Dependency depependency : dependencies) {
      if (!(depependency.getGroupId().equals("org.apache.maven"))) {
        continue;
      }

      if (isPom) {
        if (!(depependency.getArtifactId().equals("maven-model"))) {
          continue;
        }
      } else {
        if (!(depependency.getArtifactId().equals("maven-settings"))) {
          continue;
        }
      }

      Artifact mavenArtifact =
          getArtifact(
              depependency.getGroupId()
                  + ":"
                  + depependency.getArtifactId()
                  + ":"
                  + depependency.getVersion());
      resolver.resolveAlways(mavenArtifact, remoteRepositories, localRepository);

      return mavenArtifact.getFile();
    }

    throw new MojoExecutionException(
        "Unable to find the 'org.apache.maven:"
            + (isPom ? "maven-model" : "maven-settings")
            + "' artifact");
  }
  private GemDependency convertDependency(
      final MavenArtifact artifact, final Dependency dependency) {
    final GemDependency result = new GemDependency();

    result.setName(
        createGemName(
            dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion()));

    result.setType(RubyDependencyType.toRubyDependencyType(dependency.getScope()).toString());

    final GemRequirement requirement = new GemRequirement();

    // TODO: we are adding "hard" dependencies here, but we should maybe
    // support Maven ranges too
    // based on
    // http://blog.zenspider.com/2008/10/rubygems-howto-preventing-cata.html
    final String version = createGemVersion(getDependencyVersion(artifact, dependency));
    final int index = version.length() - version.replaceFirst("^[^.]+[.][^.]+", "").length();
    requirement.addRequirement("~>", new GemVersion(version.substring(0, index)));

    result.setVersion_requirement(requirement);

    return result;
  }
示例#29
0
  /**
   * checks if we need to add a maven dependency for the chosen component and inserts it into the
   * pom.xml if needed
   */
  public static void updateMavenDependencies(
      List<org.fusesource.ide.camel.model.catalog.Dependency> compDeps) throws CoreException {
    RiderDesignEditor editor = Activator.getDiagramEditor();
    if (editor == null) {
      Activator.getLogger()
          .error(
              "Unable to add component dependencies because Editor instance can't be determined.");
      return;
    }

    IProject project = editor.getCamelContextFile().getProject();
    if (project == null) {
      Activator.getLogger()
          .error(
              "Unable to add component dependencies because selected project can't be determined.");
      return;
    }

    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);
    final Model model = MavenPlugin.getMaven().readModel(pomFile);

    // then check if component dependency is already a dep
    ArrayList<org.fusesource.ide.camel.model.catalog.Dependency> missingDeps =
        new ArrayList<org.fusesource.ide.camel.model.catalog.Dependency>();
    List<Dependency> deps = model.getDependencies();
    for (org.fusesource.ide.camel.model.catalog.Dependency conDep : compDeps) {
      boolean found = false;
      for (Dependency pomDep : deps) {
        if (pomDep.getGroupId().equalsIgnoreCase(conDep.getGroupId())
            && pomDep.getArtifactId().equalsIgnoreCase(conDep.getArtifactId())) {
          // check for correct version
          if (pomDep.getVersion().equalsIgnoreCase(conDep.getVersion()) == false) {
            // not the correct version - change it to fit
            pomDep.setVersion(conDep.getVersion());
          }
          found = true;
          break;
        }
      }
      if (!found) {
        missingDeps.add(conDep);
      }
    }

    for (org.fusesource.ide.camel.model.catalog.Dependency missDep : missingDeps) {
      Dependency dep = new Dependency();
      dep.setGroupId(missDep.getGroupId());
      dep.setArtifactId(missDep.getArtifactId());
      dep.setVersion(missDep.getVersion());
      model.addDependency(dep);
    }

    if (missingDeps.size() > 0) {
      OutputStream os = null;
      try {
        os = new BufferedOutputStream(new FileOutputStream(pomFile));
        MavenPlugin.getMaven().writeModel(model, os);
        IFile pomIFile = project.getProject().getFile("pom.xml");
        if (pomIFile != null) {
          pomIFile.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
        }
      } catch (Exception ex) {
        Activator.getLogger().error(ex);
      } finally {
        try {
          if (os != null) {
            os.close();
          }
        } catch (IOException e) {
          Activator.getLogger().error(e);
        }
      }
    }
  }
  private void guess(
      Map<String, DefaultCoreExtension> extensions, DefaultCoreExtensionRepository repository) {
    Set<ExtensionDependency> dependencies = new HashSet<ExtensionDependency>();

    for (DefaultCoreExtension coreExtension : extensions.values()) {
      for (ExtensionDependency dependency : coreExtension.getDependencies()) {
        dependencies.add(dependency);
      }
    }

    // Normalize and guess

    Map<String, Object[]> fileNames = new HashMap<String, Object[]>();
    Map<String, Object[]> guessedArtefacts = new HashMap<String, Object[]>();
    Set<URL> urls = ClasspathHelper.forClassLoader();

    for (URL url : urls) {
      try {
        String path = url.toURI().getPath();
        String filename = path.substring(path.lastIndexOf('/') + 1);
        String type = null;

        int extIndex = filename.lastIndexOf('.');
        if (extIndex != -1) {
          type = filename.substring(extIndex + 1);
          filename = filename.substring(0, extIndex);
        }

        int index;
        if (!filename.endsWith(SNAPSHOTSUFFIX)) {
          index = filename.lastIndexOf('-');
        } else {
          index = filename.lastIndexOf('-', filename.length() - SNAPSHOTSUFFIX.length());
        }

        if (index != -1) {
          fileNames.put(filename, new Object[] {url});

          String artefactname = filename.substring(0, index);
          String version = filename.substring(index + 1);

          guessedArtefacts.put(artefactname, new Object[] {version, url, type});
        }
      } catch (Exception e) {
        this.logger.warn("Failed to parse resource name [" + url + "]", e);
      }
    }

    // Try to resolve version no easy to find from the pom.xml
    try {
      for (DefaultCoreExtension coreExtension : extensions.values()) {
        String artifactId = getArtifactId(coreExtension);

        Object[] artefact = guessedArtefacts.get(artifactId);

        if (artefact != null) {
          if (coreExtension.getId().getVersion().getValue().charAt(0) == '$') {
            coreExtension.setId(
                new ExtensionId(coreExtension.getId().getId(), (String) artefact[0]));
            coreExtension.setGuessed(true);
          }

          if (coreExtension.getType().charAt(0) == '$') {
            coreExtension.setType((String) artefact[2]);
            coreExtension.setGuessed(true);
          }
        }
      }

      // Add dependencies that does not provide proper pom.xml resource and can't be found in the
      // classpath
      for (ExtensionDependency extensionDependency : dependencies) {
        Dependency dependency =
            (Dependency)
                extensionDependency.getProperty(MavenCoreExtensionDependency.PKEY_MAVEN_DEPENDENCY);

        if (dependency == null) {
          dependency =
              toDependency(
                  extensionDependency.getId(),
                  extensionDependency.getVersionConstraint().getValue(),
                  null);
        }

        String dependencyId = dependency.getGroupId() + ':' + dependency.getArtifactId();

        DefaultCoreExtension coreExtension = extensions.get(dependencyId);
        if (coreExtension == null) {
          String dependencyFileName = dependency.getArtifactId() + '-' + dependency.getVersion();
          if (dependency.getClassifier() != null) {
            dependencyFileName += '-' + dependency.getClassifier();
            dependencyId += ':' + dependency.getClassifier();
          }

          Object[] filenameArtifact = fileNames.get(dependencyFileName);
          Object[] guessedArtefact = guessedArtefacts.get(dependency.getArtifactId());

          if (filenameArtifact != null) {
            coreExtension =
                new DefaultCoreExtension(
                    repository,
                    (URL) filenameArtifact[0],
                    new ExtensionId(dependencyId, dependency.getVersion()),
                    packagingToType(dependency.getType()));
            coreExtension.setGuessed(true);
          } else if (guessedArtefact != null) {
            coreExtension =
                new DefaultCoreExtension(
                    repository,
                    (URL) guessedArtefact[1],
                    new ExtensionId(dependencyId, (String) guessedArtefact[0]),
                    packagingToType(dependency.getType()));
            coreExtension.setGuessed(true);
          }

          if (coreExtension != null) {
            extensions.put(dependencyId, coreExtension);
          }
        }
      }
    } catch (Exception e) {
      this.logger.warn("Failed to guess extra information about some extensions", e);
    }
  }