org.sonatype.nexus.repository.group.GroupFacet Java Examples

The following examples show how to use org.sonatype.nexus.repository.group.GroupFacet. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RemoveSnapshotsTask.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected void execute(final Repository repository) {
  if (hasBeenProcessed(repository)) {
    log.debug("Skipping repository '{}'; it has already been processed", repository.getName());
    return;
  }

  if (isGroupRepository(repository)) {
    markProcessed(repository); // nothing to do for the group itself

    repository.facet(GroupFacet.class).members().stream().filter(this::appliesTo).forEach(this::execute);
  }
  else {
    log.info("Executing removal of snapshots on repository '{}'", repository.getName());

    TaskConfiguration config = getConfiguration();
    RemoveSnapshotsConfig removeSnapshotsConfig = new RemoveSnapshotsConfig(
        config.getInteger(MINIMUM_SNAPSHOT_RETAINED_COUNT, 1),
        config.getInteger(SNAPSHOT_RETENTION_DAYS, 30),
        config.getBoolean(REMOVE_IF_RELEASED, false),
        config.getInteger(GRACE_PERIOD, -1));
    repository.facet(RemoveSnapshotsFacet.class).removeSnapshots(removeSnapshotsConfig);
    markProcessed(repository);
  }
}
 
Example #2
Source File: BrowseServiceImplTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testGetAssetById_withEntityId_groupRepository() {
  EntityId assetId = new DetachedEntityId(assetOneORID.toString());
  EntityId bucketId = mock(EntityId.class);
  Bucket bucket = mock(Bucket.class);

  when(storageTx.findAsset(assetId)).thenReturn(assetOne);
  when(assetOne.bucketId()).thenReturn(bucketId);
  when(bucketStore.getById(bucketId)).thenReturn(bucket);
  when(bucket.getRepositoryName()).thenReturn("releases");

  Repository groupRepository = mock(Repository.class);
  when(groupRepository.getType()).thenReturn(new GroupType());
  when(groupRepository.getName()).thenReturn("group-repository");
  when(groupRepository.facet(StorageFacet.class)).thenReturn(storageFacet);
  GroupFacet groupFacet = mock(GroupFacet.class);
  when(groupFacet.allMembers()).thenReturn(Arrays.asList(groupRepository, mavenReleases));
  when(groupRepository.facet(GroupFacet.class)).thenReturn(groupFacet);

  when(assetEntityAdapter.readEntity(assetOneDoc)).thenReturn(assetOne);

  assertThat(underTest.getAssetById(assetId, groupRepository), is(assetOne));
  verify(groupFacet).allMembers();
}
 
Example #3
Source File: BrowseServiceImplTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
private void setupMocksForBrowserComponentAssets(boolean allowAssetOne, boolean allowAssetTwo) {
  Repository groupRepository = mock(Repository.class);
  when(groupRepository.getType()).thenReturn(new GroupType());
  when(groupRepository.getName()).thenReturn("group-repository");
  when(groupRepository.facet(StorageFacet.class)).thenReturn(storageFacet);
  GroupFacet groupFacet = mock(GroupFacet.class);
  when(groupFacet.allMembers()).thenReturn(Arrays.asList(groupRepository, mavenReleases));
  when(groupRepository.facet(GroupFacet.class)).thenReturn(groupFacet);
  when(storageTx.findComponent(new DetachedEntityId(componentOneORID.toString()))).thenReturn(componentOne);
  when(repositoryManager.findContainingGroups(mavenReleases.getName())).thenReturn(Collections.singletonList("group-repository"));
  AssetVariableResolver assetVariableResolver = mock(AssetVariableResolver.class);
  when(variableResolverAdapterManager.get(componentOne.format())).thenReturn(assetVariableResolver);
  VariableSource variableSourceOne = createVariableSource(assetOne);
  VariableSource variableSourceTwo = createVariableSource(assetTwo);
  when(assetVariableResolver.fromAsset(assetOne)).thenReturn(variableSourceOne);
  when(assetVariableResolver.fromAsset(assetTwo)).thenReturn(variableSourceTwo);
  when(storageTx.browseAssets(componentOne)).thenReturn(Arrays.asList(assetOne, assetTwo));
  when(contentPermissionChecker
      .isPermitted(eq(Stream.of(mavenReleases.getName(), "group-repository").collect(Collectors.toSet())), any(),
          any(), eq(variableSourceOne))).thenReturn(allowAssetOne);
  when(contentPermissionChecker
      .isPermitted(eq(Stream.of(mavenReleases.getName(), "group-repository").collect(Collectors.toSet())), any(),
          any(), eq(variableSourceTwo))).thenReturn(allowAssetTwo);
}
 
Example #4
Source File: BrowseServiceImplTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testGetRepoToContainedGroupMap() {
  Repository repo1 = mock(Repository.class);
  when(repo1.getName()).thenReturn("repo1");
  when(repo1.optionalFacet(GroupFacet.class)).thenReturn(Optional.empty());
  Repository repo2 = mock(Repository.class);
  when(repo2.getName()).thenReturn("repo2");
  when(repo2.optionalFacet(GroupFacet.class)).thenReturn(Optional.empty());
  Repository group = mock(Repository.class);
  when(group.getName()).thenReturn("group");
  GroupFacet groupFacet = mock(GroupFacet.class);
  when(groupFacet.leafMembers()).thenReturn(Arrays.asList(repo1));
  when(group.optionalFacet(GroupFacet.class)).thenReturn(Optional.of(groupFacet));

  List<Repository> repositories = Arrays.asList(repo1, repo2, group);

  Map<String, List<String>> repoToContainedGroups = underTest.getRepoToContainedGroupMap(repositories);
  assertThat(repoToContainedGroups.size(), is(3));
  assertThat(repoToContainedGroups.get("repo1").size(), is(2));
  assertThat(repoToContainedGroups.get("repo1").get(0), is("repo1"));
  assertThat(repoToContainedGroups.get("repo1").get(1), is("group"));
  assertThat(repoToContainedGroups.get("repo2").size(), is(1));
  assertThat(repoToContainedGroups.get("repo2").get(0), is("repo2"));
  assertThat(repoToContainedGroups.get("group").size(), is(1));
  assertThat(repoToContainedGroups.get("group").get(0), is("group"));
}
 
Example #5
Source File: ComposerGroupMergingHandler.java    From nexus-repository-composer with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected final Response doGet(@Nonnull final Context context,
                               @Nonnull final GroupHandler.DispatchedRepositories dispatched)
    throws Exception
{
  Repository repository = context.getRepository();
  GroupFacet groupFacet = repository.facet(GroupFacet.class);

  makeUnconditional(context.getRequest());
  Map<Repository, Response> responses;
  try {
    responses = getAll(context, groupFacet.members(), dispatched);
  }
  finally {
    makeConditional(context.getRequest());
  }

  List<Payload> payloads = responses.values().stream()
      .filter(response -> response.getStatus().getCode() == HttpStatus.OK && response.getPayload() != null)
      .map(Response::getPayload)
      .collect(Collectors.toList());
  if (payloads.isEmpty()) {
    return notFoundResponse(context);
  }
  return HttpResponses.ok(merge(repository, payloads));
}
 
Example #6
Source File: RepositoryBrowseResource.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
private Asset getAssetById(final Repository repository, final EntityId assetId) {
  Optional<GroupFacet> optionalGroupFacet = repository.optionalFacet(GroupFacet.class);
  List<Repository> members = optionalGroupFacet.isPresent() ? optionalGroupFacet.get().allMembers()
      : Collections.singletonList(repository);

  return Transactional.operation.withDb(repository.facet(StorageFacet.class).txSupplier()).call(() -> {
    StorageTx tx = UnitOfWork.currentTx();
    Asset candidate = tx.findAsset(assetId);
    if (candidate != null) {
      final String asssetBucketRepositoryName = bucketStore.getById(candidate.bucketId()).getRepositoryName();
      if (members.stream().anyMatch(repo -> repo.getName().equals(asssetBucketRepositoryName))) {
        return candidate;
      }
    }

    return null;
  });
}
 
Example #7
Source File: IndexGroupFacet.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void publishIndex() throws IOException {
  UnitOfWork.begin(getRepository().facet(StorageFacet.class).txSupplier());
  try (DuplicateDetectionStrategy<Record> strategy = duplicateDetectionStrategyProvider.get()) {
    List<Repository> leafMembers = facet(GroupFacet.class).leafMembers();
    ArrayList<String> withoutIndex = new ArrayList<>();
    for (Iterator<Repository> ri = leafMembers.iterator(); ri.hasNext(); ) {
      Repository repository = ri.next();
      if (repository.facet(MavenIndexFacet.class).lastPublished() == null) {
        withoutIndex.add(repository.getName());
        ri.remove();
      }
    }
    if (!withoutIndex.isEmpty()) {
      log.info("Following members of group {} have no index, will not participate in merged index: {}",
          getRepository().getName(),
          withoutIndex
      );
    }
    MavenIndexPublisher.publishMergedIndex(getRepository(), leafMembers, strategy);
  }
  finally {
    UnitOfWork.end();
  }
}
 
Example #8
Source File: GroupMemberMappingCache.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
private Map<String,List<String>> populateCache() {
  Map<String, List<String>> cache = new HashMap<>();

  repositoryManager.browse().forEach(repository -> {
    if (!repository.optionalFacet(GroupFacet.class).isPresent()) {
      TreeMap<Integer, List<String>> groupNamesByLevel = new TreeMap<>();

      findContainingGroups(repository.getName(), groupNamesByLevel, 0);

      cache.put(repository.getName(),
          groupNamesByLevel.values().stream().peek(groupNames -> groupNames.sort(null)).flatMap(Collection::stream)
              .collect(Collectors.toList()));
    }
  });

  return cache;
}
 
Example #9
Source File: NpmSearchIndexFacetGroupTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  underTest = Guice.createInjector(new TransactionModule(), new AbstractModule()
  {
    @Override
    protected void configure() {
      bind(EventManager.class).toInstance(eventManager);
    }
  }).getInstance(NpmSearchIndexFacetGroup.class);

  underTest.attach(groupRepository);

  when(groupRepository.facet(GroupFacet.class)).thenReturn(groupFacet);
  when(groupRepository.facet(StorageFacet.class)).thenReturn(storageFacet);
  when(storageFacet.txSupplier()).thenReturn(supplierStorageTx);
  when(storageTx.findAssetWithProperty(P_NAME, REPOSITORY_ROOT_ASSET, groupBucket)).thenReturn(asset);
  when(storageTx.findBucket(groupRepository)).thenReturn(groupBucket);
}
 
Example #10
Source File: RepositorySearchContribution.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void contribute(final BoolQueryBuilder query, final String type, final String value) {
  if (value == null) {
    return;
  }

  Repository repository = repositoryManager.get(value);

  if (repository != null) {
    Optional<GroupFacet> groupFacet = repository.optionalFacet(GroupFacet.class);
    if (groupFacet.isPresent()) {
      List<Repository> members = groupFacet.get().leafMembers();

      query.must(QueryBuilders.termsQuery(type, members.stream().map(Repository::getName).toArray(String[]::new)));
      return;
    }
  }

  super.contribute(query, type, value);
}
 
Example #11
Source File: NpmSearchGroupHandler.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Searches the member repositories, returning the merged response for all contacted member repositories that returned
 * a valid search response.
 */
private NpmSearchResponse searchMembers(final Context context,
                                        final DispatchedRepositories dispatched,
                                        final Parameters parameters) throws Exception
{
  // preserve original from and size for repeated queries
  int from = npmSearchParameterExtractor.extractFrom(parameters);
  int size = npmSearchParameterExtractor.extractSize(parameters);

  // if the text is empty, then we override the original parameters to return a full set from each upstream source
  // we could make multiple queries to make this more efficient, but this is the simplest implementation for now
  parameters.replace("from", "0");
  parameters.replace("size", Integer.toString(v1SearchMaxResults));

  // sort all the merged results by normalized search score, then build the result responses to send back
  GroupFacet groupFacet = context.getRepository().facet(GroupFacet.class);
  Set<Entry<Repository, Response>> entries = getAll(context, groupFacet.members(), dispatched).entrySet();
  List<NpmSearchResponseObject> mergedResponses = mergeAndNormalizeResponses(entries);
  mergedResponses.sort(comparingDouble(NpmSearchResponseObject::getSearchScore).reversed());
  List<NpmSearchResponseObject> mergedResponseObjects = mergedResponses.stream()
      .skip(from)
      .limit(size)
      .collect(toList());

  return npmSearchResponseFactory.buildResponseForObjects(mergedResponseObjects);
}
 
Example #12
Source File: PackagesGroupHandler.java    From nexus-repository-r with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected Response doGet(@Nonnull final Context context,
                         @Nonnull final GroupHandler.DispatchedRepositories dispatched)
    throws Exception
{
  GroupFacet groupFacet = context.getRepository().facet(GroupFacet.class);
  Map<Repository, Response> responses = getAll(context, groupFacet.members(), dispatched);
  List<Response> successfulResponses = responses.values().stream()
      .filter(response -> response.getStatus().getCode() == HttpStatus.OK && response.getPayload() != null)
      .collect(Collectors.toList());
  if (successfulResponses.isEmpty()) {
    return notFoundResponse(context);
  }
  if (successfulResponses.size() == 1) {
    return successfulResponses.get(0);
  }

  List<List<Map<String, String>>> parts = successfulResponses.stream().map(this::parseResponse).collect(
      Collectors.toList());
  List<Map<String, String>> merged = RPackagesUtils.merge(parts);

  return HttpResponses.ok(RPackagesUtils.buildPackages(merged));
}
 
Example #13
Source File: RepositoryManagerImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private void removeRepositoryFromAllGroups(final Repository repositoryToRemove) throws Exception {
  for (Repository group : repositories.values()) {
    Optional<GroupFacet> groupFacet = group.optionalFacet(GroupFacet.class);
    if (groupFacet.isPresent() && groupFacet.get().member(repositoryToRemove)) {
      removeRepositoryFromGroup(repositoryToRemove, group);
    }
  }
}
 
Example #14
Source File: RepositoryCacheUtils.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Invalidates the group caches for given repository.
 */
public static void invalidateGroupCaches(final Repository repository) {
  checkNotNull(repository);
  checkArgument(GroupType.NAME.equals(repository.getType().getValue()));
  GroupFacet groupFacet = repository.facet(GroupFacet.class);
  groupFacet.invalidateGroupCaches();
}
 
Example #15
Source File: BrowseServiceImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private List<Repository> allMembers(final Repository repository) {
  if (groupType.equals(repository.getType())) {
    return repository.facet(GroupFacet.class).allMembers();
  }
  else {
    return Collections.singletonList(repository);
  }
}
 
Example #16
Source File: GroupMemberMappingCache.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Subscribe
public void on(final RepositoryUpdatedEvent event) {
  log.debug("Handling repository updated event for {}", event.getRepository().getName());
  if (event.getRepository().optionalFacet(GroupFacet.class).isPresent()) {
    memberInGroupsMap = null;
  }
}
 
Example #17
Source File: GroupMemberMappingCache.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Subscribe
public void on(final RepositoryCreatedEvent event) {
  log.debug("Handling repository create event for {}", event.getRepository().getName());
  if (event.getRepository().optionalFacet(GroupFacet.class).isPresent()) {
    memberInGroupsMap = null;
  }
}
 
Example #18
Source File: GroupMemberMappingCacheTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private Repository mockRepository(String name) {
  Repository repository = mock(Repository.class);

  when(repository.getName()).thenReturn(name);
  when(repository.optionalFacet(GroupFacet.class)).thenReturn(Optional.empty());

  return repository;
}
 
Example #19
Source File: RepositoryBrowseResourceTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void validateAsset_groupRepository() throws Exception {
  Repository groupRepository = mock(Repository.class);
  when(groupRepository.getType()).thenReturn(new GroupType());
  when(groupRepository.getName()).thenReturn("group-repository");
  when(groupRepository.getFormat()).thenReturn(new Format("format") {});
  when(groupRepository.facet(StorageFacet.class)).thenReturn(storageFacet);
  GroupFacet groupFacet = mock(GroupFacet.class);
  when(groupFacet.allMembers()).thenReturn(Arrays.asList(groupRepository, repository));
  when(groupRepository.optionalFacet(GroupFacet.class)).thenReturn(Optional.of(groupFacet));
  when(repositoryManager.get("group-repository")).thenReturn(groupRepository);

  List<BrowseNode<EntityId>> nodes = asList(browseNode("a.txt", mock(EntityId.class), true));
  when(asset.size()).thenReturn(1024L);
  when(asset.blobUpdated()).thenReturn(new DateTime(0));
  when(asset.name()).thenReturn("a1.txt");
  when(groupRepository.getUrl()).thenReturn("http://foo/bar");
  when(browseNodeStore
      .getByPath(groupRepository.getName(), Collections.emptyList(), configuration.getMaxHtmlNodes()))
      .thenReturn(nodes);

  underTest.getHtml("group-repository", "", uriInfo);

  ArgumentCaptor<TemplateParameters> argument = ArgumentCaptor.forClass(TemplateParameters.class);
  verify(templateHelper).render(any(), argument.capture());

  List<BrowseListItem> listItems = (List<BrowseListItem>) argument.getValue().get().get("listItems");
  assertThat(listItems.size(), is(1));

  BrowseListItem item = listItems.get(0);
  assertThat(item.getName(), is("a.txt"));
  assertThat(item.getSize(), is("1024"));
  assertThat(item.getLastModified(), is(format.format(asset.blobUpdated().toDate())));
  assertThat(item.getResourceUri(), is("http://foo/bar/a1.txt"));
}
 
Example #20
Source File: RepositoryBrowseResourceTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Before
public void before() throws Exception {
  when(uriInfo.getAbsolutePath()).thenReturn(UriBuilder.fromPath(URL_PREFIX + "central/").build());

  when(securityHelper.allPermitted(any())).thenReturn(true);
  when(templateHelper.parameters()).thenReturn(new TemplateParameters());
  when(templateHelper.render(any(),any())).thenReturn("something");
  when(repository.getName()).thenReturn(REPOSITORY_NAME);
  when(repository.getFormat()).thenReturn(new Format("format") {});
  when(repository.getType()).thenReturn(new ProxyType());

  when(repository.optionalFacet(GroupFacet.class)).thenReturn(Optional.empty());

  when(repository.facet(StorageFacet.class)).thenReturn(storageFacet);
  when(storageFacet.txSupplier()).thenReturn(txSupplier);
  when(txSupplier.get()).thenReturn(storageTx);

  when(storageTx.findAsset(any())).thenReturn(asset);

  EntityId bucketId = mock(EntityId.class);
  when(asset.bucketId()).thenReturn(bucketId);
  when(bucketStore.getById(bucketId)).thenReturn(bucket);
  when(bucket.getRepositoryName()).thenReturn(REPOSITORY_NAME);


  BrowseNode<EntityId> orgBrowseNode = browseNode("org");
  when(browseNodeStore.getByPath(REPOSITORY_NAME, Collections.emptyList(), configuration.getMaxHtmlNodes()))
      .thenReturn(Collections.singleton(orgBrowseNode));

  BrowseNode<EntityId> sonatypeBrowseNode = browseNode("sonatype");
  when(browseNodeStore.getByPath(REPOSITORY_NAME, Collections.singletonList("org"), configuration.getMaxHtmlNodes()))
      .thenReturn(Collections.singleton(sonatypeBrowseNode));
  when(repositoryManager.get(REPOSITORY_NAME)).thenReturn(repository);

  underTest = new RepositoryBrowseResource(repositoryManager, browseNodeStore, configuration, bucketStore,
      templateHelper, securityHelper);
}
 
Example #21
Source File: OrientBrowseNodeStoreImplTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void groupQueryWithLimit() throws Exception {
  List<String> queryPath = asList("org", "foo");

  when(securityHelper.anyPermitted(any())).thenReturn(true);
  when(repository.getType()).thenReturn(new GroupType());
  when(repository.facet(GroupFacet.class)).thenReturn(groupFacet);
  when(groupFacet.leafMembers()).thenReturn(asList(memberA, memberB, memberC));
  when(repository.optionalFacet(BrowseNodeFacet.class)).thenReturn(Optional.of(browseNodeFacet));
  when(browseNodeFacet.browseNodeIdentity()).thenReturn(browseNodeIdentity());

  when(browseNodeEntityAdapter.getByPath(db, MEMBER_A, queryPath, 1, "", emptyMap()))
      .thenReturn(asList(node(MEMBER_A, "com")));
  when(browseNodeEntityAdapter.getByPath(db, MEMBER_B, queryPath, 1, "", emptyMap()))
      .thenReturn(asList(node(MEMBER_B, "com")));
  when(browseNodeEntityAdapter.getByPath(db, MEMBER_C, queryPath, 1, "", emptyMap()))
      .thenReturn(asList(node(MEMBER_C, "com")));

  Iterable<BrowseNode<EntityId>> nodes = underTest.getByPath(REPOSITORY_NAME, queryPath, 1);

  // check that the limit was correctly applied to the merged results
  assertThat(nodes, containsInAnyOrder(
      allOf(hasProperty("repositoryName", is(MEMBER_A)), hasProperty("name", is("com")))));

  verify(securityHelper).anyPermitted(any(RepositoryViewPermission.class));
  // merging of results should be lazy: only the first member should have been consulted
  verify(browseNodeEntityAdapter).getByPath(db, MEMBER_A, queryPath, 1, "", emptyMap());
  verifyNoMoreInteractions(browseNodeEntityAdapter, securityHelper, selectorManager);
}
 
Example #22
Source File: GroupMemberMappingCacheTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private Repository mockGroupRepository(String name, Repository... members) {
  Repository repository = mock(Repository.class);

  when(repository.getName()).thenReturn(name);

  GroupFacet groupFacet = mock(GroupFacet.class);
  for (Repository member : members) {
    when(groupFacet.member(member.getName())).thenReturn(true);
  }

  when(repository.optionalFacet(GroupFacet.class)).thenReturn(Optional.of(groupFacet));

  return repository;
}
 
Example #23
Source File: OrientBrowseNodeStoreImplTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void groupQuery() throws Exception {
  List<String> queryPath = asList("org", "foo");

  when(securityHelper.anyPermitted(any())).thenReturn(true);
  when(repository.getType()).thenReturn(new GroupType());
  when(repository.facet(GroupFacet.class)).thenReturn(groupFacet);
  when(groupFacet.leafMembers()).thenReturn(asList(memberA, memberB, memberC));
  when(repository.optionalFacet(BrowseNodeFacet.class)).thenReturn(Optional.of(browseNodeFacet));
  when(browseNodeFacet.browseNodeIdentity()).thenReturn(browseNodeIdentity());

  when(browseNodeEntityAdapter.getByPath(db, MEMBER_A, queryPath, MAX_NODES, "", emptyMap()))
      .thenReturn(asList(node(MEMBER_A, "com"), node(MEMBER_A, "org")));
  when(browseNodeEntityAdapter.getByPath(db, MEMBER_B, queryPath, MAX_NODES, "", emptyMap()))
      .thenReturn(asList(node(MEMBER_B, "biz"), node(MEMBER_B, "org")));
  when(browseNodeEntityAdapter.getByPath(db, MEMBER_C, queryPath, MAX_NODES, "", emptyMap()))
      .thenReturn(asList(node(MEMBER_C, "com"), node(MEMBER_C, "javax")));

  Iterable<BrowseNode<EntityId>> nodes = underTest.getByPath(REPOSITORY_NAME, queryPath, MAX_NODES);

  // check that duplicate nodes were removed, should follow a 'first-one-wins' approach
  assertThat(nodes, containsInAnyOrder(
      allOf(hasProperty("repositoryName", is(MEMBER_A)), hasProperty("name", is("com"))),
      allOf(hasProperty("repositoryName", is(MEMBER_A)), hasProperty("name", is("org"))),
      allOf(hasProperty("repositoryName", is(MEMBER_B)), hasProperty("name", is("biz"))),
      allOf(hasProperty("repositoryName", is(MEMBER_C)), hasProperty("name", is("javax")))));

  verify(securityHelper).anyPermitted(any(RepositoryViewPermission.class));
  verify(browseNodeEntityAdapter).getByPath(db, MEMBER_A, queryPath, MAX_NODES, "", emptyMap());
  verify(browseNodeEntityAdapter).getByPath(db, MEMBER_B, queryPath, MAX_NODES, "", emptyMap());
  verify(browseNodeEntityAdapter).getByPath(db, MEMBER_C, queryPath, MAX_NODES, "", emptyMap());
  verifyNoMoreInteractions(browseNodeEntityAdapter, securityHelper, selectorManager);
}
 
Example #24
Source File: RepositorySearchContributionTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private Repository mockRepo(String name, Repository... members) {
  Repository repository = mock(Repository.class);
  when(repository.getName()).thenReturn(name);
  when(repositoryManager.get(name)).thenReturn(repository);

  if (members != null && members.length > 0) {
    GroupFacet groupFacet = mock(GroupFacet.class);
    when(groupFacet.leafMembers()).thenReturn(Arrays.asList(members));
    when(repository.optionalFacet(GroupFacet.class)).thenReturn(Optional.of(groupFacet));
  }
  else {
    when(repository.optionalFacet(GroupFacet.class)).thenReturn(Optional.empty());
  }
  return repository;
}
 
Example #25
Source File: AuthorizingRepositoryManagerTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void invalidateCacheGroupRepository() throws Exception {
  when(repository.getType()).thenReturn(new GroupType());
  GroupFacet groupFacet = mock(GroupFacet.class);
  when(repository.facet(GroupFacet.class)).thenReturn(groupFacet);

  authorizingRepositoryManager.invalidateCache("repository");

  verify(repositoryManager).get(eq("repository"));
  verify(repositoryPermissionChecker).ensureUserCanAdmin(eq(EDIT), eq(repository));
  verify(repository).facet(GroupFacet.class);
  verify(groupFacet).invalidateGroupCaches();
  verifyNoMoreInteractions(repositoryManager, repositoryPermissionChecker, groupFacet);
}
 
Example #26
Source File: BrowseServiceImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private List<Repository> getRepositories(final Repository repository) {
  checkNotNull(repository);
  if (groupType.equals(repository.getType())) {
    return repository.facet(GroupFacet.class).leafMembers();
  }
  return ImmutableList.of(repository);
}
 
Example #27
Source File: BrowseServiceImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@VisibleForTesting
Map<String, List<String>> getRepoToContainedGroupMap(List<Repository> repositories) {
  Map<String, List<String>> repoToContainedGroupMap = new HashMap<>();
  for (Repository repository : repositories) {
    List<String> groupNames = new ArrayList<>();
    groupNames.add(repository.getName());
    groupNames.addAll(repositories.stream().filter(groupRepository -> {
      Optional<GroupFacet> groupFacet = groupRepository.optionalFacet(GroupFacet.class);
      return groupFacet.isPresent() && groupFacet.get().leafMembers().stream()
          .anyMatch(leafMember -> repository.getName().equals(leafMember.getName()));
    }).map(groupRepository -> groupRepository.getName()).collect(Collectors.toSet()));
    repoToContainedGroupMap.put(repository.getName(), groupNames);
  }
  return repoToContainedGroupMap;
}
 
Example #28
Source File: BrowseServiceImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public BrowseResult<Asset> previewAssets(final RepositorySelector repositorySelector,
                                         final List<Repository> repositories,
                                         final String jexlExpression,
                                         final QueryOptions queryOptions)
{
  checkNotNull(repositories);
  checkNotNull(jexlExpression);
  final Repository repository = repositories.get(0);
  try (StorageTx storageTx = repository.facet(StorageFacet.class).txSupplier().get()) {
    storageTx.begin();
    List<Repository> previewRepositories;
    if (repositories.size() == 1 && groupType.equals(repository.getType())) {
      previewRepositories = repository.facet(GroupFacet.class).leafMembers();
    }
    else {
      previewRepositories = repositories;
    }

    PreviewAssetsSqlBuilder builder = new PreviewAssetsSqlBuilder(
        repositorySelector,
        jexlExpression,
        queryOptions,
        getRepoToContainedGroupMap(repositories));

    String whereClause = String.format("and (%s)", builder.buildWhereClause());

    //The whereClause is passed in as the querySuffix so that contentExpression will run after repository filtering
    return new BrowseResult<>(
        storageTx.countAssets(null, builder.buildSqlParams(), previewRepositories, whereClause),
        Lists.newArrayList(storageTx.findAssets(null, builder.buildSqlParams(),
            previewRepositories, whereClause + builder.buildQuerySuffix()))
    );
  }
}
 
Example #29
Source File: RemoveSnapshotsTaskTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private Repository mockGroup(List<Repository> groupMembers) {
  Repository group = mock(Repository.class);
  GroupFacet facet = mock(GroupFacet.class);

  when(group.getName()).thenReturn("");
  when(group.getType()).thenReturn(new GroupType());
  when(group.facet(GroupFacet.class)).thenReturn(facet);
  when(group.getFormat()).thenReturn(new Maven2Format());
  when(group.facet(MavenFacet.class)).thenReturn(mavenFacet);
  when(group.facet(RemoveSnapshotsFacet.class)).thenReturn(removeSnapshotsFacet);
  when(group.optionalFacet(RemoveSnapshotsFacet.class)).thenReturn(Optional.of(removeSnapshotsFacet));
  when(facet.members()).thenReturn(groupMembers);

  return group;
}
 
Example #30
Source File: OrientNpmGroupPackageHandlerTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Before
@SuppressWarnings("unchecked")
public void setUp() throws Exception {
  underTest = new OrientNpmGroupPackageHandler();

  AttributesMap attributesMap = new AttributesMap();
  attributesMap.set(TokenMatcher.State.class, state);
  when(context.getAttributes()).thenReturn(attributesMap);
  when(context.getRepository()).thenReturn(group);
  when(context.getRequest()).thenReturn(request);

  when(group.getName()).thenReturn(OrientNpmGroupFacetTest.class.getSimpleName() + "-group");
  when(group.facet(GroupFacet.class)).thenReturn(groupFacet);
  when(group.facet(StorageFacet.class)).thenReturn(storageFacet);

  when(groupFacet.buildPackageRoot(anyMap(), eq(context)))
      .thenReturn(new Content(new BytesPayload("test".getBytes(), "")));

  when(viewFacet.dispatch(request, context))
      .thenReturn(new Response.Builder().status(success(OK)).build());

  when(proxy.facet(ViewFacet.class)).thenReturn(viewFacet);
  when(hosted.facet(ViewFacet.class)).thenReturn(viewFacet);

  when(request.getHeaders()).thenReturn(new Headers());
  when(request.getAttributes()).thenReturn(new AttributesMap());

  when(storageFacet.txSupplier()).thenReturn(() -> storageTx);

  UnitOfWork.beginBatch(storageTx);
}