private Collection<Artifact> getMostRecentArtifacts(Set<Artifact> artifacts) {
    Map<String, Artifact> artifactIdToArtifact = new HashMap<String, Artifact>();

    for (Artifact artifact : artifacts) {
      if (artifact.getScope() != null && artifact.getScope().contains("provide")) {
        continue;
      }

      String artifactId = artifact.getArtifactId();

      ArtifactVersion artifactVersion;

      try {
        artifactVersion = new DefaultArtifactVersion(artifact.getVersion());
      } catch (Exception e) {
        artifactVersion = null;
      }

      Artifact actualArtifactForId = artifactIdToArtifact.get(artifactId);
      ArtifactVersion actualArtifactVersion =
          (actualArtifactForId == null)
              ? null
              : new DefaultArtifactVersion(actualArtifactForId.getVersion());

      if (actualArtifactVersion == null) {
        artifactIdToArtifact.put(artifactId, artifact);
      } else {
        if (actualArtifactVersion.compareTo(artifactVersion) < 0) {
          artifactIdToArtifact.put(artifactId, artifact);
        }
      }
    }

    return artifactIdToArtifact.values();
  }
  /**
   * Returns <code>true</code> if the update should be applied.
   *
   * @param artifact The artifact.
   * @param currentVersion The current version of the artifact.
   * @param updateVersion The proposed new version of the artifact.
   * @return <code>true</code> if the update should be applied.
   * @since 1.0-alpha-1
   */
  protected boolean shouldApplyUpdate(
      Artifact artifact, String currentVersion, ArtifactVersion updateVersion) {
    getLog().debug("Proposal is to update from " + currentVersion + " to " + updateVersion);

    if (updateVersion == null) {
      getLog().warn("Not updating version: could not resolve any versions");
      return false;
    }

    artifact.setVersion(updateVersion.toString());
    try {
      resolver.resolveAlways(artifact, remoteArtifactRepositories, localRepository);
    } catch (ArtifactResolutionException e) {
      getLog().warn("Not updating version: could not resolve " + artifact.toString(), e);
      return false;
    } catch (ArtifactNotFoundException e) {
      getLog().warn("Not updating version: could not find " + artifact.toString(), e);
      return false;
    }

    if (currentVersion.equals(updateVersion.toString())) {
      getLog().info("Current version of " + artifact.toString() + " is the latest.");
      return false;
    }
    return true;
  }
  /** Check gwt-user dependency matches plugin version */
  private void checkGwtUserVersion() throws MojoExecutionException {
    InputStream inputStream =
        Thread.currentThread()
            .getContextClassLoader()
            .getResourceAsStream("org/codehaus/mojo/gwt/mojoGwtVersion.properties");
    Properties properties = new Properties();
    try {
      properties.load(inputStream);

    } catch (IOException e) {
      throw new MojoExecutionException("Failed to load plugin properties", e);
    } finally {
      IOUtils.closeQuietly(inputStream);
    }
    for (Iterator iterator = getProject().getCompileArtifacts().iterator(); iterator.hasNext(); ) {
      Artifact artifact = (Artifact) iterator.next();
      if (GWT_GROUP_ID.equals(artifact.getGroupId())
          && "gwt-user".equals(artifact.getArtifactId())) {
        String mojoGwtVersion = properties.getProperty("gwt.version");
        // ComparableVersion with an up2date maven version
        ArtifactVersion mojoGwtArtifactVersion = new DefaultArtifactVersion(mojoGwtVersion);
        ArtifactVersion userGwtArtifactVersion = new DefaultArtifactVersion(artifact.getVersion());
        if (userGwtArtifactVersion.compareTo(mojoGwtArtifactVersion) < 0) {
          getLog()
              .warn(
                  "You're project declares dependency on gwt-user "
                      + artifact.getVersion()
                      + ". This plugin is designed for at least gwt version "
                      + mojoGwtVersion);
        }
        break;
      }
    }
  }
 protected final List<ArtifactVersion> filterNonPreviousVersions(
     final List<ArtifactVersion> availableVersions, final Version version) {
   final List<ArtifactVersion> versions = new ArrayList<ArtifactVersion>();
   for (final ArtifactVersion artifactVersion : availableVersions) {
     if (version.compareTo(Version.parse(artifactVersion.toString())) > 0) {
       versions.add(artifactVersion);
     }
   }
   return versions;
 }
 @SuppressWarnings("unchecked")
 private boolean containsConflicts(List<DependencyNodeHopCountPair> pairs) {
   ArtifactVersion resolvedVersion = pairs.get(0).extractArtifactVersion();
   for (DependencyNodeHopCountPair pair : pairs) {
     ArtifactVersion version = pair.extractArtifactVersion();
     if (resolvedVersion.compareTo(version) < 0) {
       return true;
     }
   }
   return false;
 }
  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);
          }
        }
      }
    }
  }
  protected void updatePropertyToNewestVersion(
      ModifiedPomXMLEventReader pom,
      Property property,
      PropertyVersions version,
      String currentVersion)
      throws MojoExecutionException, XMLStreamException {
    ArtifactVersion winner =
        version.getNewestVersion(
            currentVersion, property, this.allowSnapshots, this.reactorProjects, this.getHelper());

    if (winner == null || currentVersion.equals(winner.toString())) {
      getLog()
          .info("Property ${" + property.getName() + "}: Leaving unchanged as " + currentVersion);
    } else if (PomHelper.setPropertyVersion(
        pom, version.getProfileId(), property.getName(), winner.toString())) {
      getLog()
          .info("Updated ${" + property.getName() + "} from " + currentVersion + " to " + winner);
    }
  }
 /**
  * @param artifactMetadataSource
  * @param project
  * @param localRepository
  * @return all available versions from most recent to oldest
  * @throws ArtifactMetadataRetrievalException
  */
 protected final List<ArtifactVersion> getAvailableReleasedVersions(
     final ArtifactMetadataSource artifactMetadataSource,
     final MavenProject project,
     final ArtifactRepository localRepository)
     throws ArtifactMetadataRetrievalException {
   final List<ArtifactVersion> availableVersions =
       artifactMetadataSource.retrieveAvailableVersions(
           project.getArtifact(), localRepository, project.getRemoteArtifactRepositories());
   availableVersions.remove(new DefaultArtifactVersion(project.getArtifact().getVersion()));
   for (final Iterator<ArtifactVersion> iterator = availableVersions.iterator();
       iterator.hasNext(); ) {
     final ArtifactVersion artifactVersion = iterator.next();
     if (Version.parse(artifactVersion.toString()).isSnapshot()) {
       iterator.remove();
     }
   }
   // TODO proper sorting based on Version
   Collections.sort(availableVersions);
   Collections.reverse(availableVersions);
   return availableVersions;
 }
  public void execute() throws MojoExecutionException, MojoFailureException {
    List<String> current = new ArrayList<String>();
    List<String> updates = new ArrayList<String>();

    Map<Property, PropertyVersions> propertyVersions =
        this.getHelper()
            .getVersionPropertiesMap(
                getProject(),
                properties,
                includeProperties,
                excludeProperties,
                !Boolean.FALSE.equals(autoLinkItems));
    for (Map.Entry<Property, PropertyVersions> entry : propertyVersions.entrySet()) {
      Property property = entry.getKey();
      PropertyVersions version = entry.getValue();

      final String currentVersion = getProject().getProperties().getProperty(property.getName());
      if (currentVersion == null) {
        continue;
      }

      ArtifactVersion winner =
          version.getNewestVersion(
              currentVersion,
              property,
              this.allowSnapshots,
              this.reactorProjects,
              this.getHelper());

      if (winner != null && !currentVersion.equals(winner.toString())) {
        StringBuilder buf = new StringBuilder();
        buf.append("${");
        buf.append(property.getName());
        buf.append("} ");
        final String newVersion = winner.toString();
        int padding = INFO_PAD_SIZE - currentVersion.length() - newVersion.length() - 4;
        while (buf.length() < padding) {
          buf.append('.');
        }
        buf.append(' ');
        buf.append(currentVersion);
        buf.append(" -> ");
        buf.append(newVersion);
        updates.add(buf.toString());
      } else {
        StringBuilder buf = new StringBuilder();
        buf.append("${");
        buf.append(property.getName());
        buf.append("} ");
        int padding = INFO_PAD_SIZE - currentVersion.length();
        while (buf.length() < padding) {
          buf.append('.');
        }
        buf.append(' ');
        buf.append(currentVersion);
        current.add(buf.toString());
      }
    }

    getLog().info("");
    if (!current.isEmpty()) {
      getLog()
          .info("The following version properties are referencing the newest available version:");
      for (String s : current) {
        getLog().info("  " + s);
      }
    }
    if (updates.isEmpty() && current.isEmpty()) {
      getLog().info("This project does not have any properties associated with versions.");
    } else if (updates.isEmpty()) {
      getLog().info("All version properties are referencing the newest version available.");
    }

    if (!updates.isEmpty()) {
      getLog().info("The following version property updates are available:");
      for (String update : updates) {
        getLog().info("  " + update);
      }
    }
    getLog().info("");
  }
  @SuppressWarnings("unchecked")
  public void execute() throws MojoExecutionException {
    ArtifactVersion currentVersion = ri.getApplicationVersion();
    ArtifactVersion maxUsageVersion = new DefaultArtifactVersion("2.2.0");

    if (maxUsageVersion.compareTo(currentVersion) < 0) {
      getLog()
          .debug(
              "This version of Maven does not require injection of custom ArtifactHandlers using this code. Skipping.");
      return;
    }

    Map<String, ?> handlerDescriptors =
        session.getContainer().getComponentDescriptorMap(ArtifactHandler.ROLE);
    if (handlerDescriptors != null) {
      getLog().debug("Registering all unregistered ArtifactHandlers...");

      if (artifactHandlerManager instanceof DefaultArtifactHandlerManager) {
        Set<String> existingHints =
            ((DefaultArtifactHandlerManager) artifactHandlerManager).getHandlerTypes();
        if (existingHints != null) {
          for (String hint : existingHints) {
            handlerDescriptors.remove(hint);
          }
        }
      }

      if (handlerDescriptors.isEmpty()) {
        getLog().debug("All ArtifactHandlers are registered. Continuing...");
      } else {
        Map<String, ArtifactHandler> unregisteredHandlers =
            new HashMap<String, ArtifactHandler>(handlerDescriptors.size());

        for (String hint : handlerDescriptors.keySet()) {
          try {
            unregisteredHandlers.put(
                hint, (ArtifactHandler) session.lookup(ArtifactHandler.ROLE, hint));
            getLog().info("Adding ArtifactHandler for: " + hint);
          } catch (ComponentLookupException e) {
            getLog()
                .warn(
                    "Failed to lookup ArtifactHandler with hint: "
                        + hint
                        + ". Reason: "
                        + e.getMessage(),
                    e);
          }
        }

        artifactHandlerManager.addHandlers(unregisteredHandlers);
      }
    }

    getLog()
        .debug("...done.\nSetting ArtifactHandler on project-artifact: " + project.getId() + "...");

    Set<Artifact> artifacts = new HashSet<Artifact>();
    artifacts.add(project.getArtifact());

    Set<Artifact> dependencyArtifacts = project.getDependencyArtifacts();
    if (dependencyArtifacts != null && !dependencyArtifacts.isEmpty()) {
      artifacts.addAll(dependencyArtifacts);
    }

    for (Artifact artifact : artifacts) {
      String type = artifact.getType();
      ArtifactHandler handler = artifactHandlerManager.getArtifactHandler(type);

      getLog()
          .debug(
              "Artifact: "
                  + artifact.getId()
                  + "\nType: "
                  + type
                  + "\nArtifactHandler extension: "
                  + handler.getExtension());

      artifact.setArtifactHandler(handler);
    }

    getLog().debug("...done.");
  }
  /**
   * Parse a version String and add the components to a properties object.
   *
   * @param version the version to parse
   */
  public void parseVersion(String version) {
    ArtifactVersion artifactVersion = new DefaultArtifactVersion(version);

    ArtifactVersion releaseVersion = artifactVersion;
    if (ArtifactUtils.isSnapshot(version)) {
      // work around for MBUILDHELPER-69
      releaseVersion =
          new DefaultArtifactVersion(
              StringUtils.substring(
                  version, 0, version.length() - Artifact.SNAPSHOT_VERSION.length() - 1));
    }

    if (version.equals(artifactVersion.getQualifier())) {
      // This means the version parsing failed, so try osgi format.
      getLog().debug("The version is not in the regular format, will try OSGi format instead");
      artifactVersion = new OsgiArtifactVersion(version);
    }

    defineVersionProperty("majorVersion", artifactVersion.getMajorVersion());
    defineVersionProperty("minorVersion", artifactVersion.getMinorVersion());
    defineVersionProperty("incrementalVersion", artifactVersion.getIncrementalVersion());
    defineVersionProperty("nextMajorVersion", artifactVersion.getMajorVersion() + 1);
    defineVersionProperty("nextMinorVersion", artifactVersion.getMinorVersion() + 1);
    defineVersionProperty("nextIncrementalVersion", artifactVersion.getIncrementalVersion() + 1);

    String qualifier = artifactVersion.getQualifier();
    if (qualifier == null) {
      qualifier = "";
    }
    defineVersionProperty("qualifier", qualifier);

    defineVersionProperty("buildNumber", releaseVersion.getBuildNumber()); // see MBUILDHELPER-69

    // Replace the first instance of "-" to create an osgi compatible version string.
    String osgiVersion = getOsgiVersion(artifactVersion);
    defineVersionProperty("osgiVersion", osgiVersion);
  }
  /**
   * Make an osgi compatible version String from an ArtifactVersion
   *
   * @param version The artifact version.
   * @return The OSGi version as string.
   */
  public String getOsgiVersion(ArtifactVersion version) {
    if (version.toString().equals(version.getQualifier())) {
      return version.toString();
    }

    StringBuffer osgiVersion = new StringBuffer();
    osgiVersion.append(version.getMajorVersion());
    osgiVersion.append("." + version.getMinorVersion());
    osgiVersion.append("." + version.getIncrementalVersion());

    if (version.getQualifier() != null || version.getBuildNumber() != 0) {
      osgiVersion.append(".");

      if (version.getQualifier() != null) {
        osgiVersion.append(version.getQualifier());
      }
      if (version.getBuildNumber() != 0) {
        osgiVersion.append(version.getBuildNumber());
      }
    }

    return osgiVersion.toString();
  }