protected void dropRepositories() {
   for (Repository repository : repositoryRegistry.getRepositories()) {
     try {
       repositoryRegistry.removeRepositorySilently(repository.getId());
     } catch (NoSuchRepositoryException e) {
       // will not happen
     }
   }
 }
 private Repository findRepository() {
   try {
     return repositoryRegistry.getRepository(getRepositoryId());
   } catch (NoSuchRepositoryException e) {
     return null;
   }
 }
 public void writeRepositoryMetadata(
     final String repositoryId, final RepositoryMetadata repositoryMetadata)
     throws NoSuchRepositoryException, MetadataHandlerException, IOException {
   final Repository repository = repositoryRegistry.getRepository(repositoryId);
   final NexusRawTransport nrt = new NexusRawTransport(repository, true, false);
   repositoryMetadataHandler.writeRepositoryMetadata(repositoryMetadata, nrt);
 }
Example #4
0
  /**
   * Tests walking an out of service repo. The walker should NOT not fail, but also NOT find any
   * items.</BR> Verifies fix for: NEXUS-4554 (which is more general then just fixing the Trash
   * task)
   */
  @Test
  public void testWalkOutOfServiceRepo() throws Exception {
    // put repo2 out of service
    String repoId = "repo2";
    M2Repository repo = (M2Repository) repositoryRegistry.getRepository(repoId);
    repo.setLocalStatus(LocalStatus.OUT_OF_SERVICE);
    repo.commitChanges();

    TestWalkerProcessor wp = null;
    WalkerContext wc = null;

    wp = new TestWalkerProcessor();

    // this is a group
    wc =
        new DefaultWalkerContext(
            getRepositoryRegistry().getRepository(repoId),
            new ResourceStoreRequest(RepositoryItemUid.PATH_ROOT, true));

    wc.getProcessors().add(wp);

    walker.walk(wc);

    Assert.assertEquals(0, wp.collEnters);
    Assert.assertEquals(0, wp.collExits);
    Assert.assertEquals(0, wp.colls);
    Assert.assertEquals(0, wp.files);
    Assert.assertEquals(0, wp.links);
  }
  protected Repository getRepositoryForPathPrefixOrId(
      String pathPrefixOrId, Class<? extends Repository> kind) throws NoSuchRepositoryException {
    List<? extends Repository> repositories = repositoryRegistry.getRepositoriesWithFacet(kind);

    Repository idMatched = null;

    Repository pathPrefixMatched = null;

    for (Repository repository : repositories) {
      if (StringUtils.equals(repository.getId(), pathPrefixOrId)) {
        idMatched = repository;
      }

      if (StringUtils.equals(repository.getPathPrefix(), pathPrefixOrId)) {
        pathPrefixMatched = repository;
      }
    }

    if (idMatched != null) {
      // id wins
      return idMatched;
    }

    if (pathPrefixMatched != null) {
      // if no id found, prefix wins
      return pathPrefixMatched;
    }

    // nothing found
    throw new NoSuchRepositoryException("pathPrefixOrId: '" + pathPrefixOrId + "'");
  }
 private void regenerateMetadataForGroups() {
   if (StringUtils.isBlank(getVersion())) {
     try {
       final Repository repository = repositoryRegistry.getRepository(getRepositoryId());
       for (GroupRepository groupRepository :
           repositoryRegistry.getGroupsOfRepository(repository)) {
         if (yumRegistry.isRegistered(repository.getId())) {
           MergeMetadataTask.createTaskFor(nexusScheduler, groupRepository);
         }
       }
     } catch (NoSuchRepositoryException e) {
       logger.warn(
           "Repository '{}' does not exist anymore. Backing out from triggering group merge for it.",
           getRepositoryId());
     }
   }
 }
  protected Repository instantiateRepository(
      final Configuration configuration, final CRepository repositoryModel)
      throws ConfigurationException {
    checkRepositoryMaxInstanceCountForCreation(repositoryModel);

    // create it, will do runtime validation
    Repository repository =
        runtimeConfigurationBuilder.createRepositoryFromModel(configuration, repositoryModel);

    // register with repoRegistry
    repositoryRegistry.addRepository(repository);

    // give it back
    return repository;
  }
  private void checkForCyclicReference(
      final String id, List<String> memberRepositoryIds, String path)
      throws InvalidGroupingException {
    if (memberRepositoryIds.contains(id)) {
      throw new InvalidGroupingException(id, path);
    }

    for (String memberId : memberRepositoryIds) {
      try {
        GroupRepository group =
            repoRegistry.getRepositoryWithFacet(memberId, GroupRepository.class);
        checkForCyclicReference(id, group.getMemberRepositoryIds(), path + '/' + memberId);
      } catch (NoSuchRepositoryException e) {
        // not a group repo, just ignore
      }
    }
  }
  public List<Repository> getMemberRepositories() {
    ArrayList<Repository> result = new ArrayList<Repository>();

    for (String repoId : getMemberRepositoryIds()) {
      try {
        Repository repo = repoRegistry.getRepository(repoId);
        result.add(repo);
      } catch (NoSuchRepositoryException e) {
        if (getLogger().isDebugEnabled()) {
          this.getLogger()
              .warn("Could not find repository '{}' while iterating members", repoId, e);
        } else {
          this.getLogger().warn("Could not find repository '{}' while iterating members", repoId);
        }
        // XXX throw new StorageException( e ) ;
      }
    }

    return result;
  }
  @Override
  public DefaultRepositoryItemUid createUid(final String uidStr)
      throws IllegalArgumentException, NoSuchRepositoryException {
    if (uidStr.indexOf(":") > -1) {
      String[] parts = uidStr.split(":");

      if (parts.length == 2) {
        Repository repository = repositoryRegistry.getRepository(parts[0]);

        return createUid(repository, parts[1]);
      } else {
        throw new IllegalArgumentException(
            uidStr
                + " is malformed RepositoryItemUid! The proper format is '<repoId>:/path/to/something'.");
      }
    } else {
      throw new IllegalArgumentException(
          uidStr
              + " is malformed RepositoryItemUid! The proper format is '<repoId>:/path/to/something'.");
    }
  }
  public void addMemberRepositoryId(String repositoryId)
      throws NoSuchRepositoryException, InvalidGroupingException {
    // validate THEN modify
    // this will throw NoSuchRepository if needed
    Repository repo = repoRegistry.getRepository(repositoryId);

    // check for cycles
    List<String> memberIds =
        new ArrayList<String>(getExternalConfiguration(false).getMemberRepositoryIds());
    memberIds.add(repo.getId());
    checkForCyclicReference(getId(), memberIds, getId());

    // check for compatibility
    if (!repo.getRepositoryContentClass().isCompatible(getRepositoryContentClass())) {
      throw new InvalidGroupingException(
          getRepositoryContentClass(), repo.getRepositoryContentClass());
    }

    // if we are here, all is well
    getExternalConfiguration(true).addMemberRepositoryId(repo.getId());
  }
  protected void inspect(Event<?> evt) {
    if (!isNexusStarted()) {
      return;
    }

    Repository repository = null;

    if (evt instanceof RepositoryRegistryRepositoryEvent) {
      repository = ((RepositoryRegistryRepositoryEvent) evt).getRepository();
    } else {
      repository = ((RepositoryConfigurationUpdatedEvent) evt).getRepository();
    }

    try {
      // check registry for existence, wont be able to do much
      // if doesn't exist yet
      repoRegistry.getRepository(repository.getId());

      inspectForTimeline(evt, repository);
    } catch (NoSuchRepositoryException e) {
      log.debug("Attempted to handle repository that isn't yet in registry");
    }
  }
 public RepositoryMetadata readRepositoryMetadata(final String repositoryId)
     throws NoSuchRepositoryException, MetadataHandlerException, IOException {
   final Repository repository = repositoryRegistry.getRepository(repositoryId);
   final NexusRawTransport nrt = new NexusRawTransport(repository, false, true);
   return repositoryMetadataHandler.readRepositoryMetadata(nrt);
 }
  public synchronized void deleteRepository(String id)
      throws NoSuchRepositoryException, IOException, ConfigurationException {
    Repository repository = repositoryRegistry.getRepository(id);
    // put out of service so wont be accessed any longer
    repository.setLocalStatus(LocalStatus.OUT_OF_SERVICE);
    // disable indexing for same purpose
    repository.setIndexable(false);
    repository.setSearchable(false);

    // remove dependants too

    // =======
    // shadows
    // (fail if any repo references the currently processing one)
    List<ShadowRepository> shadows =
        repositoryRegistry.getRepositoriesWithFacet(ShadowRepository.class);

    for (Iterator<ShadowRepository> i = shadows.iterator(); i.hasNext(); ) {
      ShadowRepository shadow = i.next();

      if (repository.getId().equals(shadow.getMasterRepository().getId())) {
        throw new RepositoryDependentException(repository, shadow);
      }
    }

    // ======
    // groups
    // (correction in config only, registry DOES handle it)
    // since NEXUS-1770, groups are "self maintaining"

    // ===========
    // pahMappings
    // (correction, since registry is completely unaware of this component)

    List<CPathMappingItem> pathMappings =
        getConfigurationModel().getRepositoryGrouping().getPathMappings();

    for (Iterator<CPathMappingItem> i = pathMappings.iterator(); i.hasNext(); ) {
      CPathMappingItem item = i.next();

      item.removeRepository(id);
    }

    // ===========
    // and finally
    // this cleans it properly from the registry (from reposes and repo groups)
    repositoryRegistry.removeRepository(id);

    List<CRepository> reposes = getConfigurationModel().getRepositories();

    for (Iterator<CRepository> i = reposes.iterator(); i.hasNext(); ) {
      CRepository repo = i.next();

      if (repo.getId().equals(id)) {
        i.remove();

        saveConfiguration();

        releaseRepository(repository, getConfigurationModel(), repo);

        return;
      }
    }

    throw new NoSuchRepositoryException(id);
  }
  public List<Repository> getMappedRepositories(
      Repository repository, ResourceStoreRequest request, List<Repository> resolvedRepositories)
      throws NoSuchRepositoryException {
    if (!compiled) {
      compile();
    }

    // NEXUS-2852: to make our life easier, we will work with repository IDs,
    // and will fill the result with Repositories at the end
    LinkedHashSet<String> reposIdSet = new LinkedHashSet<String>(resolvedRepositories.size());

    for (Repository resolvedRepositorty : resolvedRepositories) {
      reposIdSet.add(resolvedRepositorty.getId());
    }

    // for tracking what is applied
    ArrayList<RepositoryPathMapping> appliedMappings = new ArrayList<RepositoryPathMapping>();

    // if include found, add it to the list.
    boolean firstAdd = true;

    for (RepositoryPathMapping mapping : blockings) {
      if (mapping.matches(repository, request)) {
        if (getLogger().isDebugEnabled()) {
          getLogger()
              .debug(
                  "The request path ["
                      + request.toString()
                      + "] is blocked by rule "
                      + mapping.toString());
        }

        return Collections.emptyList();
      }
    }

    // include, if found a match
    // NEXUS-2852: watch to not add multiple times same repository
    // ie. you have different inclusive rules that are triggered by same request
    // and contains some repositories. This is now solved using LinkedHashSet and using repo IDs.
    for (RepositoryPathMapping mapping : inclusions) {
      if (mapping.matches(repository, request)) {
        appliedMappings.add(mapping);

        if (firstAdd) {
          reposIdSet.clear();

          firstAdd = false;
        }

        // add only those that are in initial resolvedRepositories list and that are non-user
        // managed
        // (preserve ordering)
        if (mapping.getMappedRepositories().size() == 1
            && "*".equals(mapping.getMappedRepositories().get(0))) {
          for (Repository repo : resolvedRepositories) {
            reposIdSet.add(repo.getId());
          }
        } else {
          for (Repository repo : resolvedRepositories) {
            if (mapping.getMappedRepositories().contains(repo.getId()) || !repo.isUserManaged()) {
              reposIdSet.add(repo.getId());
            }
          }
        }
      }
    }

    // then, if exlude found, remove those
    for (RepositoryPathMapping mapping : exclusions) {
      if (mapping.matches(repository, request)) {
        appliedMappings.add(mapping);

        if (mapping.getMappedRepositories().size() == 1
            && "*".equals(mapping.getMappedRepositories().get(0))) {
          reposIdSet.clear();

          break;
        }

        for (String repositoryId : mapping.getMappedRepositories()) {
          Repository mappedRepository = repositoryRegistry.getRepository(repositoryId);

          // but only if is user managed
          if (mappedRepository.isUserManaged()) {
            reposIdSet.remove(mappedRepository.getId());
          }
        }
      }
    }

    // store the applied mappings to request context
    ArrayList<String> appliedMappingsList = new ArrayList<String>(appliedMappings.size());

    for (RepositoryPathMapping mapping : appliedMappings) {
      appliedMappingsList.add(mapping.toString());
    }

    request.addAppliedMappingsList(repository, appliedMappingsList);

    // log it if needed
    if (getLogger().isDebugEnabled()) {
      if (appliedMappings.isEmpty()) {
        getLogger().debug("No mapping exists for request path [" + request.toString() + "]");
      } else {
        StringBuilder sb =
            new StringBuilder(
                "Request for path \""
                    + request.toString()
                    + "\" with the initial list of processable repositories of \""
                    + ResourceStoreUtils.getResourceStoreListAsString(resolvedRepositories)
                    + "\" got these mappings applied:\n");

        for (RepositoryPathMapping mapping : appliedMappings) {
          sb.append(" * ").append(mapping.toString()).append("\n");
        }

        getLogger().debug(sb.toString());

        if (reposIdSet.size() == 0) {
          getLogger()
              .debug(
                  "Mapping for path ["
                      + request.toString()
                      + "] excluded all storages from servicing the request.");
        } else {
          getLogger()
              .debug(
                  "Request path for ["
                      + request.toString()
                      + "] is MAPPED to reposes: "
                      + reposIdSet);
        }
      }
    }

    ArrayList<Repository> result = new ArrayList<Repository>(reposIdSet.size());

    try {
      for (String repoId : reposIdSet) {
        result.add(repositoryRegistry.getRepository(repoId));
      }
    } catch (NoSuchRepositoryException e) {
      getLogger()
          .error(
              "Some of the Routes contains references to non-existant repositories! Please check the following mappings: \""
                  + appliedMappingsList.toString()
                  + "\".");

      throw e;
    }

    return result;
  }
  protected Collection<StorageItem> listVirtualPath(
      ResourceStoreRequest request, RequestRoute route) throws ItemNotFoundException {
    if (route.getRequestDepth() == 0) {
      // 1st level
      ArrayList<StorageItem> result = new ArrayList<StorageItem>();

      for (RepositoryTypeDescriptor rtd :
          repositoryTypeRegistry.getRegisteredRepositoryTypeDescriptors()) {
        // check is there any repo registered
        if (!repositoryRegistry.getRepositoriesWithFacet(rtd.getRole()).isEmpty()) {
          ResourceStoreRequest req =
              new ResourceStoreRequest(
                  ItemPathUtils.concatPaths(request.getRequestPath(), rtd.getPrefix()));

          DefaultStorageCollectionItem repositories =
              new DefaultStorageCollectionItem(this, req, true, false);

          repositories.getItemContext().putAll(request.getRequestContext());

          result.add(repositories);
        }
      }

      return result;
    } else if (route.getRequestDepth() == 1) {
      // 2nd level
      List<? extends Repository> repositories = null;

      Class<? extends Repository> kind = null;

      for (RepositoryTypeDescriptor rtd :
          repositoryTypeRegistry.getRegisteredRepositoryTypeDescriptors()) {
        if (route.getStrippedPrefix().startsWith("/" + rtd.getPrefix())) {
          kind = rtd.getRole();

          repositories = repositoryRegistry.getRepositoriesWithFacet(kind);

          break;
        }
      }

      // if no prefix matched, Item not found
      if (repositories == null || repositories.isEmpty()) {
        throw new ItemNotFoundException(request);
      }

      // filter access to the repositories
      // NOTE: do this AFTER the null/empty check so we return an empty list vs. an ItemNotFound
      repositories = filterAccessToRepositories(repositories);

      ArrayList<StorageItem> result = new ArrayList<StorageItem>(repositories.size());

      for (Repository repository : repositories) {
        if (repository.isExposed() && repository.isBrowseable()) {
          DefaultStorageCollectionItem repoItem = null;

          ResourceStoreRequest req = null;

          if (Repository.class.equals(kind)) {
            req =
                new ResourceStoreRequest(
                    ItemPathUtils.concatPaths(request.getRequestPath(), repository.getId()));
          } else {
            req =
                new ResourceStoreRequest(
                    ItemPathUtils.concatPaths(
                        request.getRequestPath(), repository.getPathPrefix()));
          }

          repoItem = new DefaultStorageCollectionItem(this, req, true, false);

          repoItem.getItemContext().putAll(request.getRequestContext());

          result.add(repoItem);
        }
      }

      return result;
    } else {
      throw new ItemNotFoundException(request);
    }
  }