/**
  * @param snapshotDirectoryPath Path to a repository snapshot directory (eg, /a/path/1.0-SNAPSHOT)
  * @param buildNumber The file with build number to search for or 0 if doesn't matter
  * @param timestamp The file with timestamp to search for or null if doesn't matter
  * @param fileExtension The file type to search for. Use null for any type
  * @return The path of the first unique snapshot file with the input build number.
  */
 private String findSnapshotFile(
     RepoPath snapshotDirectoryPath, int buildNumber, String timestamp, String fileExtension) {
   log.debug(
       "Searching for unique snapshot file in {} with build number {} and timestamp {}",
       new Object[] {snapshotDirectoryPath, buildNumber, timestamp});
   RepositoryService repoService = ContextHelper.get().getRepositoryService();
   if (repoService.exists(snapshotDirectoryPath)) {
     List<String> children = repoService.getChildrenNames(snapshotDirectoryPath);
     for (String child : children) {
       if (MavenNaming.isUniqueSnapshotFileName(child)) {
         // now match against all the conditions
         boolean buildNumberMatches =
             buildNumber == 0
                 || buildNumber == MavenNaming.getUniqueSnapshotVersionBuildNumber(child);
         boolean timestampMatches =
             timestamp == null
                 || timestamp.equals(MavenNaming.getUniqueSnapshotVersionTimestamp(child));
         boolean typeMatches =
             fileExtension == null || fileExtension.equals(PathUtils.getExtension(child));
         if (buildNumberMatches && timestampMatches && typeMatches) {
           // passed all the search requirements...
           log.debug("Found unique snapshot: {}", child);
           return child;
         }
       }
     }
   }
   log.debug(
       "Unique snapshot file not found in {} for build number {}",
       snapshotDirectoryPath,
       buildNumber);
   return null;
 }
 /**
  * @return The last build number for snapshot version. 0 if maven-metadata not found for the path.
  */
 private int getLastBuildNumber(RepoPath repoPath) {
   int buildNumber = 0;
   try {
     // get the parent path which should contains the maven-metadata
     RepoPath parentRepoPath = repoPath.getParent();
     RepositoryService repoService = ContextHelper.get().getRepositoryService();
     RepoPathImpl mavenMetadataPath =
         new RepoPathImpl(parentRepoPath, MavenNaming.MAVEN_METADATA_NAME);
     if (repoService.exists(mavenMetadataPath)) {
       String mavenMetadataStr = repoService.getStringContent(mavenMetadataPath);
       Metadata metadata = MavenModelUtils.toMavenMetadata(mavenMetadataStr);
       Versioning versioning = metadata.getVersioning();
       if (versioning != null) {
         Snapshot snapshot = versioning.getSnapshot();
         if (snapshot != null) {
           buildNumber = snapshot.getBuildNumber();
         }
       }
     } else {
       // ok probably not found. just log
       log.debug("No maven metadata found for {}.", repoPath);
     }
   } catch (Exception e) {
     log.error("Cannot obtain build number from metadata.", e);
   }
   return buildNumber;
 }
 /**
  * Validate the importable repo key
  *
  * @param importableRemoteRepo Importable repo to validate
  */
 private void validateRepoKey(ImportableRemoteRepo importableRemoteRepo) {
   // Indicate if the key already exists as any type
   boolean existsAsLocal =
       repositoryService.localRepoDescriptorByKey(importableRemoteRepo.getRepoKey()) != null;
   boolean existsAsRemote = false;
   if (!existsAsLocal) {
     existsAsRemote =
         repositoryService.remoteRepoDescriptorByKey(importableRemoteRepo.getRepoKey()) != null;
   }
   boolean existsAsVirtual = false;
   if (!existsAsLocal && !existsAsRemote) {
     existsAsVirtual =
         repositoryService.virtualRepoDescriptorByKey(importableRemoteRepo.getRepoKey()) != null;
   }
   importableRemoteRepo.setExistsAsLocal(existsAsLocal);
   importableRemoteRepo.setExistsAsRemote(existsAsRemote);
   importableRemoteRepo.setExistsAsVirtual(existsAsVirtual);
 }
 private List<String> getOrderdRepoKeys() {
   List<RepoDescriptor> repoSet = Lists.newArrayList();
   List<LocalRepoDescriptor> localAndCachedRepoDescriptors =
       repoService.getLocalAndCachedRepoDescriptors();
   Collections.sort(localAndCachedRepoDescriptors, new LocalAndCachedDescriptorsComparator());
   repoSet.addAll(localAndCachedRepoDescriptors);
   List<String> repoKeys = Lists.newArrayList();
   for (RepoDescriptor descriptor : repoSet) {
     repoKeys.add(descriptor.getKey());
   }
   return repoKeys;
 }
  /**
   * Returns the list of shared remote repositories from the entered URL
   *
   * @return List of importable repositories
   */
  private List<ImportableRemoteRepo> getSharedRemoteRepos() {
    // Append headers
    Map<String, String> headersMap = WicketUtils.getHeadersMap();
    List<RemoteRepoDescriptor> remoteRepoList =
        repositoryService.getSharedRemoteRepoConfigs(url, headersMap);
    List<ImportableRemoteRepo> importableRepoList = Lists.newArrayList();

    // Indicate if an importable repository key already exists as a local\remote repository's key
    for (RemoteRepoDescriptor remoteRepoDescriptor : remoteRepoList) {
      ImportableRemoteRepo importableRemoteRepo = new ImportableRemoteRepo(remoteRepoDescriptor);

      validateRepoKey(importableRemoteRepo);

      importableRepoList.add(importableRemoteRepo);
    }
    return importableRepoList;
  }
  private String adjustChecksum(MavenSnapshotVersionAdapterContext context) {
    // find latest unique file matching the checksum coordinates
    RepositoryService repoService = ContextHelper.get().getRepositoryService();
    RepoPath repoPath = context.getRepoPath();
    RepoPath parentRepoPath = repoPath.getParent();
    RepoDescriptor repoDescriptor = repoService.repoDescriptorByKey(parentRepoPath.getRepoKey());
    RepoLayout repoLayout = repoDescriptor.getRepoLayout();

    String latestMatching = null;

    String originalChecksumRequestPath = repoPath.getPath();
    String originalRequestPathWithNoChecksum =
        PathUtils.stripExtension(originalChecksumRequestPath);

    if (repoService.exists(parentRepoPath)) {
      List<String> children = repoService.getChildrenNames(parentRepoPath);
      for (String child : children) {
        if (MavenNaming.isUniqueSnapshotFileName(child)) {

          ModuleInfo childModule =
              repoService.getItemModuleInfo(InternalRepoPathFactory.create(parentRepoPath, child));
          String fileRevisionIntegration = childModule.getFileIntegrationRevision();

          // Try to construct a new non-unique path as a descriptor
          String nonUniquePath =
              replaceIntegration(
                  ModuleInfoUtils.constructDescriptorPath(childModule, repoLayout, true),
                  fileRevisionIntegration);

          // If the path as a descriptor doesn't match, perhaps it's an artifact path
          if (!nonUniquePath.equals(originalRequestPathWithNoChecksum)) {
            // Try to construct a new non-unique path as an artifact
            nonUniquePath =
                replaceIntegration(
                    ModuleInfoUtils.constructArtifactPath(childModule, repoLayout),
                    fileRevisionIntegration);
          }

          if (nonUniquePath.equals(originalRequestPathWithNoChecksum)) {
            if (latestMatching == null
                || MavenNaming.getUniqueSnapshotVersionBuildNumber(latestMatching)
                    < MavenNaming.getUniqueSnapshotVersionBuildNumber(child)) {
              latestMatching = child;
            }
          }
        }
      }
    }

    // if latest not found, return invalid path which will fail and return a message to the client
    String timestamp =
        latestMatching != null
            ? MavenNaming.getUniqueSnapshotVersionTimestamp(latestMatching)
            : System.currentTimeMillis() + "";
    int buildNumber =
        latestMatching != null
            ? MavenNaming.getUniqueSnapshotVersionBuildNumber(latestMatching)
            : 0;

    // use the timestamp and build number from it. if not found return something that will fail?
    return buildUniqueSnapshotFileName(buildNumber, timestamp, context.getModuleInfo());
  }