org.sonatype.nexus.common.entity.EntityId Java Examples

The following examples show how to use org.sonatype.nexus.common.entity.EntityId. 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: OrientBrowseNodeManagerTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
private Asset createAsset(final String assetName, final String assetId, final String format, final EntityId componentId) {
  EntityMetadata entityMetadata = mock(EntityMetadata.class);
  when(entityMetadata.getId()).thenReturn(new DetachedEntityId(assetId));

  Asset asset = mock(Asset.class);
  when(asset.getEntityMetadata()).thenReturn(entityMetadata);
  when(asset.name()).thenReturn(assetName);
  when(asset.format()).thenReturn(format);
  when(asset.blobRef()).thenReturn(mock(BlobRef.class));

  if (componentId != null) {
    when(asset.componentId()).thenReturn(componentId);
  }

  Format fmt = mock(Format.class);
  when(fmt.getValue()).thenReturn(format);
  when(repository.getFormat()).thenReturn(fmt);

  return asset;
}
 
Example #2
Source File: AssetStoreImplTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void getNextPageStopsAtNullEntry() {
  int limit = 2;

  Asset asset1 = createAsset(bucket, "asset1", component);

  try (ODatabaseDocumentTx db = database.getInstance().connect()) {
    assetEntityAdapter.addEntity(db, asset1);
  }

  OIndexCursor cursor = underTest.getIndex(AssetEntityAdapter.I_BUCKET_COMPONENT_NAME).cursor();

  List<Entry<OCompositeKey, EntityId>> assetPage1 = underTest.getNextPage(cursor, limit);

  assertThat(assetPage1.size(), is(1));
  assertThat(assetPage1.get(0).getValue(), is(EntityHelper.id(asset1)));
}
 
Example #3
Source File: RepositoryBrowseResource.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Inject
public RepositoryBrowseResource(
    final RepositoryManager repositoryManager,
    final BrowseNodeStore<EntityId> browseNodeStore,
    final BrowseNodeConfiguration configuration,
    final BucketStore bucketStore,
    final TemplateHelper templateHelper,
    final SecurityHelper securityHelper)
{
  this.repositoryManager = checkNotNull(repositoryManager);
  this.browseNodeStore = checkNotNull(browseNodeStore);
  this.configuration = checkNotNull(configuration);
  this.templateHelper = checkNotNull(templateHelper);
  this.securityHelper = checkNotNull(securityHelper);
  this.bucketStore = checkNotNull(bucketStore);
  this.template = getClass().getResource(TEMPLATE_RESOURCE);
  checkNotNull(template);
}
 
Example #4
Source File: RoutingRulesApiResource.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
@DELETE
@Path("/{name}")
@RequiresAuthentication
@RequiresPermissions("nexus:*")
public void deleteRoutingRule(@PathParam("name") final String name) {
  RoutingRule routingRule = getRuleFromStore(name);
  EntityId routingRuleId = routingRule.id();
  Map<EntityId, List<Repository>> assignedRepositories = routingRuleHelper.calculateAssignedRepositories();

  List<Repository> repositories = assignedRepositories.computeIfAbsent(routingRuleId, id -> emptyList());
  if (!repositories.isEmpty()) {
    throw new WebApplicationMessageException(
        Status.BAD_REQUEST,
        "\"Routing rule is still in use by " + repositories.size() + " repositories.\"",
        APPLICATION_JSON);
  }

  routingRuleStore.delete(routingRule);
}
 
Example #5
Source File: RRoutingRuleIT.java    From nexus-repository-r with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testBlockedRoutingRule() throws Exception {
  String packageFileName = "agricolae_1.0-1.tar.gz";
  String allowedPackagePath = "bin/macosx/el-capitan/contrib/1.0/agricolae_1.0-1.tar.gz";
  String blockedPackagePath = "bin/macosx/el-capitan/contrib/1.1/agricolae_1.0-1.tar.gz";

  configureProxyBehaviour(allowedPackagePath, packageFileName);
  configureProxyBehaviour(blockedPackagePath, packageFileName);

  EntityId routingRuleId = createBlockedRoutingRule("r-blocking-rule", ".*/1.1/.*");
  Repository proxyRepo = repos.createRProxy("test-r-blocking-proxy", proxyServer.getUrl().toString());
  RClient client = rClient(proxyRepo);

  attachRuleToRepository(proxyRepo, routingRuleId);

  assertGetResponseStatus(client, proxyRepo, blockedPackagePath, 403);
  assertGetResponseStatus(client, proxyRepo, allowedPackagePath, 200);
  assertNoRequests(blockedPackagePath);
}
 
Example #6
Source File: HelmComponentMaintenanceFacet.java    From nexus-repository-helm with Eclipse Public License 1.0 6 votes vote down vote up
@Transactional(retryOn = ONeedRetryException.class)
@Override
protected Set<String> deleteAssetTx(final EntityId assetId, final boolean deleteBlobs) {
  StorageTx tx = UnitOfWork.currentTx();
  Bucket bucket = tx.findBucket(getRepository());
  Asset asset = tx.findAsset(assetId, bucket);

  if (asset == null) {
    return Collections.emptySet();
  }

  tx.deleteAsset(asset, deleteBlobs);

  if (asset.componentId() != null) {
    Component component = tx.findComponentInBucket(asset.componentId(), bucket);

    if (!tx.browseAssets(component).iterator().hasNext()) {
      log.debug("Deleting component: {}", component);
      tx.deleteComponent(component, deleteBlobs);
    }
  }
  return Collections.singleton(asset.name());
}
 
Example #7
Source File: IndexSyncService.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
private void syncIndex(final Map<ORID, EntityAdapter> changes) {
  IndexBatchRequest batch = new IndexBatchRequest();
  try (ODatabaseDocumentTx db = componentDatabase.get().acquire()) {
    changes.forEach((rid, adapter) -> {
      ODocument document = db.load(rid);
      if (document != null) {
        EntityId componentId = findComponentId(document);
        if (componentId != null) {
          batch.update(findRepositoryName(document), componentId);
        }
      }
      else if (adapter instanceof ComponentEntityAdapter) {
        batch.delete(null, componentId(rid));
      }
    });
  }
  indexRequestProcessor.process(batch);
}
 
Example #8
Source File: RebuildBrowseNodesManagerTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
private Asset createAsset(final String name, final String format, final Bucket bucket) throws Exception {
  Asset asset = new Asset();
  asset.name(name);

  Method m = MetadataNode.class.getDeclaredMethod("format", String.class);
  m.setAccessible(true);
  m.invoke(asset, format);

  m = MetadataNode.class.getDeclaredMethod("bucketId", EntityId.class);
  m.setAccessible(true);
  m.invoke(asset, EntityHelper.id(bucket));

  m = MetadataNode.class.getDeclaredMethod("attributes", NestedAttributesMap.class);
  m.setAccessible(true);
  m.invoke(asset, new NestedAttributesMap("attributes", new HashMap<>()));

  return asset;
}
 
Example #9
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 #10
Source File: AssetStoreImpl.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
@Guarded(by = STARTED)
public <T> List<Entry<T, EntityId>> getNextPage(final OIndexCursor cursor, final int limit) {
  List<Entry<T, EntityId>> page = new ArrayList<>(limit);

  // For reasons unknown Orient needs the connection despite the code not using it
  try (ODatabaseDocumentTx db = databaseInstance.get().acquire()) {
    cursor.setPrefetchSize(limit);
    while (page.size() < limit) {
      Entry<Object, OIdentifiable> entry = cursor.nextEntry();
      if (entry == null) {
        break;
      }

      @SuppressWarnings("unchecked")
      T key = (T) entry.getKey();
      EntityId value = new AttachedEntityId(entityAdapter, entry.getValue().getIdentity());
      page.add(new SimpleEntry<>(key, value));
    }
  }

  return page;
}
 
Example #11
Source File: BrowseNodeEntityAdapter.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Removes the {@link BrowseNode} associated with the given asset id.
 */
public void deleteAssetNode(final ODatabaseDocumentTx db, final EntityId assetId) {
  // a given asset will only appear once in the tree
  ODocument document = getFirst(
      db.command(new OCommandSQL(FIND_BY_ASSET)).execute(
          ImmutableMap.of(P_ASSET_ID, recordIdentity(assetId))), null);

  if (document != null) {
    if (document.containsField(P_COMPONENT_ID)) {
      // component still exists, just remove asset details
      document.removeField(P_ASSET_ID);
      document.save();
    }
    else {
      maybeDeleteParents(db, document.field(P_REPOSITORY_NAME), document.field(P_PARENT_PATH));
      document.delete();
    }
  }
}
 
Example #12
Source File: AssetStoreImplTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void getNextPageReturnsEntriesByPages() {
  int limit = 2;

  Asset asset1 = createAsset(bucket, "asset1", component);
  Asset asset2 = createAsset(bucket, "asset2", component);
  Asset asset3 = createAsset(bucket, "asset3", component);

  try (ODatabaseDocumentTx db = database.getInstance().connect()) {
    assetEntityAdapter.addEntity(db, asset1);
    assetEntityAdapter.addEntity(db, asset2);
    assetEntityAdapter.addEntity(db, asset3);
  }

  OIndexCursor cursor = underTest.getIndex(AssetEntityAdapter.I_BUCKET_COMPONENT_NAME).cursor();

  List<Entry<OCompositeKey, EntityId>> assetPage1 = underTest.getNextPage(cursor, limit);
  List<Entry<OCompositeKey, EntityId>> assetPage2 = underTest.getNextPage(cursor, limit);
  assertThat(assetPage1.size(), is(2));
  assertThat(assetPage1.get(0).getValue(), is(EntityHelper.id(asset1)));
  assertThat(assetPage1.get(1).getValue(), is(EntityHelper.id(asset2)));
  assertThat(assetPage2.size(), is(1));
  assertThat(assetPage2.get(0).getValue(), is(EntityHelper.id(asset3)));
}
 
Example #13
Source File: DeleteFolderServiceImpl.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
private void deleteComponent(
    final Repository repository,
    final EntityId componentId,
    final DateTime timestamp,
    final ComponentMaintenance componentMaintenance)
{
  Optional<DateTime> lastUpdated;
  try (StorageTx tx = repository.facet(StorageFacet.class).txSupplier().get()) {
    lastUpdated = Optional.ofNullable(tx.findComponent(componentId)).map(component -> component.lastUpdated());
  }

  lastUpdated.ifPresent(lu -> {
    if (timestamp.isAfter(lu)) {
      componentMaintenance.deleteComponent(componentId);
    }
  });
}
 
Example #14
Source File: ComponentStoreImplTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void getNextPageReturnsEntriesByPages() {
  int limit = 2;

  Component entity1 = createComponent(bucket, "group1", "name1", "version1");
  Component entity2 = createComponent(bucket, "group2", "name2", "version2");
  Component entity3 = createComponent(bucket, "group3", "name3", "version3");

  try (ODatabaseDocumentTx db = database.getInstance().connect()) {
    entityAdapter.addEntity(db, entity1);
    entityAdapter.addEntity(db, entity2);
    entityAdapter.addEntity(db, entity3);
  }

  OIndexCursor cursor = underTest.getIndex(ComponentEntityAdapter.I_GROUP_NAME_VERSION_INSENSITIVE).cursor();

  List<Entry<OCompositeKey, EntityId>> page1 = underTest.getNextPage(cursor, limit);
  List<Entry<OCompositeKey, EntityId>> page2 = underTest.getNextPage(cursor, limit);
  assertThat(page1.size(), is(2));
  assertThat(page1.get(0).getValue(), is(EntityHelper.id(entity1)));
  assertThat(page1.get(1).getValue(), is(EntityHelper.id(entity2)));
  assertThat(page2.size(), is(1));
  assertThat(page2.get(0).getValue(), is(EntityHelper.id(entity3)));
}
 
Example #15
Source File: RoutingRuleHelperImplTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testAssignedRepositories_multipleRulesAndRepositories() throws Exception {
  Repository repository2 = mock(Repository.class);
  Repository repository3 = mock(Repository.class);

  when(repository2.getName()).thenReturn("test-repo-2");
  when(repository3.getName()).thenReturn("test-repo-3");
  when(repositoryManager.browse()).thenReturn(ImmutableList.of(repository, repository2, repository3));

  configureRepositoryMock(repository, "rule-1");
  configureRepositoryMock(repository2, "rule-2");
  configureRepositoryMock(repository3, "rule-2");

  Map<EntityId, List<Repository>> assignedRepositoryMap = underTest.calculateAssignedRepositories();
  assertEquals(2, assignedRepositoryMap.size());
  assertEquals(ImmutableList.of(repository), assignedRepositoryMap.get(new DetachedEntityId("rule-1")));
  assertEquals(ImmutableList.of(repository2, repository3), assignedRepositoryMap.get(new DetachedEntityId("rule-2")));
}
 
Example #16
Source File: P2ComponentMaintenance.java    From nexus-repository-p2 with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Deletes the asset and its component if it's the only asset in it.
 */
@Override
@Guarded(by = STARTED)
@TransactionalDeleteBlob
protected Set<String> deleteAssetTx(final EntityId assetId, final boolean deleteBlob) {
  StorageTx tx = UnitOfWork.currentTx();
  final Asset asset = tx.findAsset(assetId, tx.findBucket(getRepository()));
  if (asset == null) {
    return Collections.emptySet();
  }

  final EntityId componentId = asset.componentId();
  if (componentId == null) {
    // Assets without components should be deleted on their own
    return super.deleteAssetTx(assetId, deleteBlob);
  }

  final Component component = tx.findComponent(componentId);
  if (component == null) {
    return Collections.emptySet();
  }
  return deleteComponentTx(componentId, deleteBlob).getAssets();
}
 
Example #17
Source File: OrientBrowseNodeManagerTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void maybeCreateFromUpdatedAssetSkipsAssetsWithExistingBrowseNode() {
  List<BrowsePaths> assetPath = toBrowsePaths(singletonList("asset"));
  Asset asset = createAsset("asset", "assetId", "otherFormat", null);
  EntityId assetId = asset.getEntityMetadata().getId();

  when(browseNodeStore.assetNodeExists(asset)).thenReturn(true);

  when(defaultBrowseNodeGenerator.computeAssetPaths(asset, null)).thenReturn(assetPath);
  when(defaultBrowseNodeGenerator.computeComponentPaths(asset, null)).thenReturn(emptyList());

  manager.maybeCreateFromUpdatedAsset(REPOSITORY_NAME, assetId, asset);

  verify(browseNodeStore).assetNodeExists(asset);
  verifyNoMoreInteractions(browseNodeStore);
}
 
Example #18
Source File: RoutingRulesResourceTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testGetRoutingRules_AssignedRepositoriesMultipleHiddenByPerms() {
  when(routingRuleStore.list()).thenReturn(Arrays.asList(rule1, rule2, rule3));

  Map<EntityId,List<Repository>> ruleRepoMap = new HashMap<>();
  ruleRepoMap.put(new DetachedEntityId("rule1"), Arrays.asList(repository1, repository2, repository3));
  ruleRepoMap.put(new DetachedEntityId("rule2"), Collections.emptyList());
  ruleRepoMap.put(new DetachedEntityId("rule3"), Collections.emptyList());

  when(routingRuleHelper.calculateAssignedRepositories()).thenReturn(ruleRepoMap);

  when(repositoryPermissionChecker
      .userHasRepositoryAdminPermission(Arrays.asList(repository1, repository2, repository3), "read"))
      .thenReturn(Arrays.asList(repository1, repository3));

  when(repositoryPermissionChecker.userCanBrowseRepository(repository1)).thenReturn(true);
  when(repositoryPermissionChecker.userCanBrowseRepository(repository2)).thenReturn(false);
  when(repositoryPermissionChecker.userCanBrowseRepository(repository3)).thenReturn(true);

  List<RoutingRuleXO> xos = underTest.getRoutingRules(true);

  assertThat(xos.size(), is(3));
  assertXO(xos.get(0), "rule1", 3, "repository1", "repository3");
  assertXO(xos.get(1), "rule2", 0);
  assertXO(xos.get(2), "rule3", 0);
}
 
Example #19
Source File: OrientBrowseNodeManagerTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void maybeCreateFromUpdatedAssetCreatesForAssetWithContentAndNoExistingBrowseNode() {
  List<BrowsePaths> assetPath = toBrowsePaths(singletonList("asset"));
  Asset asset = createAsset("asset", "assetId", "otherFormat", null);
  EntityId assetId = asset.getEntityMetadata().getId();

  when(browseNodeStore.assetNodeExists(asset)).thenReturn(false);

  when(defaultBrowseNodeGenerator.computeAssetPaths(asset, null)).thenReturn(assetPath);
  when(defaultBrowseNodeGenerator.computeComponentPaths(asset, null)).thenReturn(emptyList());

  manager.maybeCreateFromUpdatedAsset(REPOSITORY_NAME, assetId, asset);

  verify(browseNodeStore).assetNodeExists(asset);
  verify(browseNodeStore)
      .createAssetNode(REPOSITORY_NAME, "otherFormat", toBrowsePaths(singletonList(asset.name())), asset);
  verifyNoMoreInteractions(browseNodeStore);
}
 
Example #20
Source File: BrowseServiceImpl.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public Asset getAssetById(final EntityId assetId, final Repository repository) {
  List<Repository> members = allMembers(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 assetBucketRepositoryName = bucketStore.getById(candidate.bucketId()).getRepositoryName();
      if (members.stream().anyMatch(repo -> repo.getName().equals(assetBucketRepositoryName))) {
        return candidate;
      }
    }
    return null;
  });
}
 
Example #21
Source File: OrientPyPiComponentMaintenance.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Deletes the root AND package index if a component has been deleted
 */
@TransactionalDeleteBlob
@Override
protected DeletionResult deleteComponentTx(final EntityId componentId, final boolean deleteBlobs) {
  StorageTx tx = UnitOfWork.currentTx();
  Component component = tx.findComponentInBucket(componentId, tx.findBucket(getRepository()));
  if (component == null) {
    return new DeletionResult(null, Collections.emptySet());
  }

  deleteRootIndex();

  deleteCachedIndex(component.name());

  log.debug("Deleting component: {}", component.toStringExternal());
  return new DeletionResult(component, tx.deleteComponent(component, deleteBlobs));
}
 
Example #22
Source File: StorageTxImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Nullable
@Override
@Guarded(by = ACTIVE)
public Asset findAsset(final EntityId id, final Bucket bucket) {
  checkNotNull(id);
  checkNotNull(bucket);
  Asset asset = assetEntityAdapter.read(db, id);
  return bucketOwns(bucket, asset) ? asset : null;
}
 
Example #23
Source File: ComponentStoreImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
@Guarded(by = STARTED)
public Component read(final EntityId id)
{
  try (ODatabaseDocumentTx db = databaseInstance.get().acquire()) {
    return entityAdapter.read(db, id);
  }
}
 
Example #24
Source File: OrientBrowseNodeManager.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates the browse nodes if they don't already exist.  This handles the case where a format creates contentless
 * metadata without browse nodes and later updates the asset with content.
 *
 * @param repositoryName of the repository that the asset is stored in
 * @param assetId        of the existing asset
 * @param asset          that needs to be accessible from the browse nodes
 */
public void maybeCreateFromUpdatedAsset(final String repositoryName, final EntityId assetId, final Asset asset) {
  checkNotNull(assetId);

  if (asset.blobRef() == null) {
    log.trace("asset {} has no content, not creating browse node", assetId);
  }
  else if (browseNodeStore.assetNodeExists(asset)) {
    log.trace("browse node already exists for {} on update", assetId);
  }
  else {
    log.trace("adding browse node for {} on update", assetId);
    createFromAsset(repositoryName, asset);
  }
}
 
Example #25
Source File: DeleteCleanupMethod.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public DeletionProgress run(final Repository repository,
                            final Iterable<EntityId> components,
                            final BooleanSupplier cancelledCheck)
{
  return repository.facet(ComponentMaintenance.class).deleteComponents(components, cancelledCheck, batchSize);
}
 
Example #26
Source File: CleanupServiceImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
protected Long deleteByPolicy(final Repository repository,
                              final CleanupPolicy policy,
                              final BooleanSupplier cancelledCheck)
{
  log.info("Deleting components in repository {} using policy {}", repository.getName(), policy.getName());

  DeletionProgress deletionProgress = new DeletionProgress(cleanupRetryLimit);

  if (!policy.getCriteria().isEmpty()) {
    do {
      try {
        Iterable<EntityId> componentsToDelete = browseService.browse(policy, repository);
        DeletionProgress currentProgress = cleanupMethod.run(repository, componentsToDelete, cancelledCheck);
        deletionProgress.update(currentProgress);
      }
      catch (Exception e) {
        deletionProgress.setFailed(true);
        if (ExceptionUtils.getRootCause(e) instanceof SearchContextMissingException) {
          log.warn("Search scroll timed out, continuing with new scrollId.", log.isDebugEnabled() ? e : null);
          deletionProgress.setAttempts(0);
        }
        else {
          log.error("Failed to delete components.", e);
        }
      }
    } while (!deletionProgress.isFinished());

    if (deletionProgress.isFailed()) {
      log.warn("Deletion attempts exceeded for repository {}", repository.getName());
    }
    return deletionProgress.getCount();
  }
  else {
    log.info("Policy {} has no criteria and will therefore be ignored (i.e. no components will be deleted)",
        policy.getName());
    return 0L;
  }
}
 
Example #27
Source File: SimpleApiRepositoryAdapterTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testAdapt_proxyRepositoryRoutingRule() throws Exception {
  Repository repository = createRepository(new ProxyType());
  EntityId entityId = mock(EntityId.class);
  repository.getConfiguration().setRoutingRuleId(entityId);

  SimpleApiProxyRepository proxyRepository = (SimpleApiProxyRepository) underTest.adapt(repository);
  assertThat(proxyRepository.getRoutingRuleName(), nullValue());

  when(routingRuleStore.getById(any())).thenReturn(new OrientRoutingRule(ROUTING_RULE_NAME, null, null, null));

  proxyRepository = (SimpleApiProxyRepository) underTest.adapt(repository);
  assertThat(proxyRepository.getRoutingRuleName(), is(ROUTING_RULE_NAME));
}
 
Example #28
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 #29
Source File: BrowseServiceImplTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testGetAssetById_withEntityId_wrongRepository() {
  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("some-other-repository");

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

  assertNull(underTest.getAssetById(assetId, mavenReleases));
}
 
Example #30
Source File: BaseRestoreBlobStrategy.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * In cases when performing restore and a component has been deleted, it is possible
 * for existing assets to become orphaned during the restore process. In the context
 * of the restore process, this method determines if an asset is associated with the
 * component found (using coordinates from the restored data) using the component's entity id.
 */
private boolean assetIsAssociatedWithComponent(final T data,
                                               final Repository repository,
                                               final String name) throws IOException
{
  Optional<EntityId> componentEntityId = componentEntityId(data);
  return componentEntityId.isPresent() && componentEntityId.equals(assetComponentEntityId(repository, name));
}