org.sonatype.nexus.repository.storage.StorageFacet Java Examples

The following examples show how to use org.sonatype.nexus.repository.storage.StorageFacet. 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: BrowseServiceImpl.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public BrowseResult<Component> browseComponents(final Repository repository,
                                                final QueryOptions queryOptions)
{
  checkNotNull(repository);
  final List<Repository> repositories = getRepositories(repository);
  try (StorageTx storageTx = repository.facet(StorageFacet.class).txSupplier().get()) {
    storageTx.begin();
    List<String> bucketIds = getBucketIds(storageTx, repositories);
    List<Component> components = Collections.emptyList();
    // ensure there are components before incurring contentAuth overhead
    if (hasComponents(storageTx, repository, bucketIds, queryOptions)) {
      components = getComponents(storageTx.browse(
          browseComponentsSqlBuilder.buildBrowseSql(bucketIds, queryOptions),
          browseComponentsSqlBuilder.buildSqlParams(repository.getName(), queryOptions)));
    }
    return new BrowseResult<>(queryOptions, components);
  }
}
 
Example #2
Source File: OrientMavenGroupFacet.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
@Subscribe
@AllowConcurrentEvents
public void on(final AssetEvent event) {
  // only make DB changes on the originating node, as orient will also replicate those for us
  if (event.isLocal() && event.getComponentId() == null && member(event.getRepositoryName())) {
    final String path = event.getAsset().name();
    final MavenPath mavenPath = mavenFacet.getMavenPathParser().parsePath(path);
    // only trigger eviction on main metadata artifact (which may go on to evict its hashes)
    if (!mavenPath.isHash()) {
      UnitOfWork.begin(getRepository().facet(StorageFacet.class).txSupplier());
      try {
        evictCache(mavenPath, event instanceof AssetDeletedEvent);
      }
      finally {
        UnitOfWork.end();
      }
    }
  }
}
 
Example #3
Source File: CreateIndexServiceImpl.java    From nexus-repository-helm with Eclipse Public License 1.0 6 votes vote down vote up
@TransactionalStoreBlob
@Nullable
public TempBlob buildIndexYaml(final Repository repository) {
  StorageFacet storageFacet = repository.facet(StorageFacet.class);
  HelmFacet helmFacet = repository.facet(HelmFacet.class);
  StorageTx tx = UnitOfWork.currentTx();

  ChartIndex index = new ChartIndex();

  for (Asset asset : helmFacet.browseComponentAssets(tx, AssetKind.HELM_PACKAGE)) {
    parseAssetIntoChartEntry(index, asset);
  }

  index.setApiVersion(API_VERSION);
  index.setGenerated(new DateTime());
  return indexYamlBuilder.build(index, storageFacet);
}
 
Example #4
Source File: NpmFacetUtils.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
private static InputStream packageRootAssetToInputStream(final Repository repository, final Asset packageRootAsset) {
  BlobStore blobStore = repository.facet(StorageFacet.class).blobStore();
  if (isNull(blobStore)) {
    throw new MissingAssetBlobException(packageRootAsset);
  }

  BlobRef blobRef = packageRootAsset.requireBlobRef();
  Blob blob = blobStore.get(blobRef.getBlobId());
  if (isNull(blob)) {
    throw new MissingAssetBlobException(packageRootAsset);
  }

  try {
    return blob.getInputStream();
  }
  catch (BlobStoreException ignore) { // NOSONAR
    // we want any issue with the blob store stream to be caught during the getting of the input stream as throw the
    // the same type of exception as a missing asset blob, so that we can pass the associated asset around.
    throw new MissingAssetBlobException(packageRootAsset);
  }
}
 
Example #5
Source File: PurgeUnusedFacetImplTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Before
public void setup() throws Exception {
  Bucket bucket = mockBucket();
  when(tx.findBucket(repository)).thenReturn(bucket);
  when(tx.browse(any(), any())).thenReturn(componentDocsIterable);
  when(tx.findAssets(any(), any(), any(), any())).thenReturn(assetIterable);
  when(componentDocsIterable.iterator()).thenReturn(componentDocsIterator);
  when(assetIterable.iterator()).thenReturn(assetIterator);
  when(repository.facet(StorageFacet.class)).thenReturn(storageFacet);
  when(storageFacet.txSupplier()).thenReturn(() -> tx);

  uncaught = newArrayList();

  underTest = new PurgeUnusedFacetImpl(componentEntityAdapter);
  underTest.attach(repository);
}
 
Example #6
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 #7
Source File: OrientPyPiDeleteLegacyProxyAssetsTaskTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testCall() throws Exception {
  underTest.call();
  verify(otherProxy, never()).facet(StorageFacet.class);
  verify(pyPiHosted, never()).facet(StorageFacet.class);

  verify(pyPiProxy, times(1)).facet(StorageFacet.class);

  StorageTx tx = pyPiProxy.facet(StorageFacet.class).txSupplier().get();
  verify(tx).begin();

  ArgumentCaptor<Asset> assetCaptor = ArgumentCaptor.forClass(Asset.class);

  verify(tx, times(2)).deleteAsset(assetCaptor.capture());

  List<String> assetNames = assetCaptor.getAllValues().stream().map(Asset::name).collect(Collectors.toList());
  assertThat(assetNames, containsInAnyOrder("simple/foo", "packages/00/01/02/foo-123.whl"));

  verify(tx).commit();
}
 
Example #8
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 #9
Source File: P2RestoreBlobStrategyTest.java    From nexus-repository-p2 with Eclipse Public License 1.0 6 votes vote down vote up
@Before
public void setup() {
  restoreBlobStrategy = new P2RestoreBlobStrategy(nodeAccess, repositoryManager, blobStoreManager, new DryRunPrefix("dryrun"));

  when(repositoryManager.get(anyString())).thenReturn(repository);
  when(repository.facet(P2RestoreFacet.class)).thenReturn(p2RestoreFacet);
  when(repository.optionalFacet(P2RestoreFacet.class)).thenReturn(Optional.of(p2RestoreFacet));
  when(repository.optionalFacet(StorageFacet.class)).thenReturn(Optional.of(storageFacet));
  when(blob.getInputStream()).thenReturn(new ByteArrayInputStream(blobBytes));
  when(p2RestoreBlobData.getBlobData()).thenReturn(restoreBlobData);
  when(restoreBlobData.getBlobName()).thenReturn(PACKAGE_PATH);
  when(restoreBlobData.getRepository()).thenReturn(repository);
  when(restoreBlobData.getBlob()).thenReturn(blob);
  when(storageFacet.txSupplier()).thenReturn(() -> storageTx);
  when(blobStoreManager.get(TEST_BLOB_STORE_NAME)).thenReturn(blobStore);
  when(restoreBlobData.getRepository()).thenReturn(repository);

  properties.setProperty("@BlobStore.created-by", "anonymous");
  properties.setProperty("size", "894185");
  properties.setProperty("@Bucket.repo-name", "p2-proxy");
  properties.setProperty("creationTime", "1577179311620");
  properties.setProperty("@BlobStore.created-by-ip", "127.0.0.1");
  properties.setProperty("@BlobStore.content-type", "application/java-archive");
  properties.setProperty("@BlobStore.blob-name", PACKAGE_PATH);
  properties.setProperty("sha1", "ac7306bee8742701a1e81a702685a55c17b07e4a");
}
 
Example #10
Source File: OrientMetadataRebuilder.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Rebuilds/updates Maven metadata.
 *
 * @param repository  The repository whose metadata needs rebuild (Maven2 format, Hosted type only).
 * @param update      if {@code true}, updates existing metadata, otherwise overwrites them with newly generated
 *                    ones.
 * @param rebuildChecksums whether or not checksums should be checked and corrected if found                     
 *                           missing or incorrect                    
 * @param groupId     scope the work to given groupId.
 * @param artifactId  scope the work to given artifactId (groupId must be given).
 * @param baseVersion scope the work to given baseVersion (groupId and artifactId must ge given).
 *
 * @return whether the rebuild actually triggered
 */
@Override public boolean rebuild(final Repository repository,
                    final boolean update,
                    final boolean rebuildChecksums,
                    @Nullable final String groupId,
                    @Nullable final String artifactId,
                    @Nullable final String baseVersion)
{
  checkNotNull(repository);
  final StorageTx tx = repository.facet(StorageFacet.class).txSupplier().get();
  UnitOfWork.beginBatch(tx);
  try {
    return rebuildInTransaction(repository, update, rebuildChecksums, groupId, artifactId, baseVersion);
  }
  finally {
    UnitOfWork.end();
  }
}
 
Example #11
Source File: OrientNpmUploadHandler.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public UploadResponse handle(final Repository repository, final ComponentUpload upload) throws IOException {
  NpmHostedFacet facet = repository.facet(NpmHostedFacet.class);

  StorageFacet storageFacet = repository.facet(StorageFacet.class);

  try (TempBlob tempBlob = storageFacet.createTempBlob(upload.getAssetUploads().get(0).getPayload(),
      NpmFacetUtils.HASH_ALGORITHMS)) {
    final Map<String, Object> packageJson = npmPackageParser.parsePackageJson(tempBlob);
    ensureNpmPermitted(repository, packageJson);

    UnitOfWork.begin(storageFacet.txSupplier());
    try {
      return new UploadResponse(facet.putPackage(packageJson, tempBlob));
    }
    finally {
      UnitOfWork.end();
    }
  }
}
 
Example #12
Source File: RawUploadHandler.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected List<Content> getResponseContents(final Repository repository, final Map<String, PartPayload> pathToPayload)
    throws IOException
{
  RawContentFacet facet = repository.facet(RawContentFacet.class);

  List<Content> responseContents = Lists.newArrayList();
  UnitOfWork.begin(repository.facet(StorageFacet.class).txSupplier());
  try {
    for (Entry<String,PartPayload> entry : pathToPayload.entrySet()) {
      String path = entry.getKey();

      Content content = facet.put(path, entry.getValue());

      responseContents.add(content);
    }
  }
  finally {
    UnitOfWork.end();
  }
  return responseContents;
}
 
Example #13
Source File: ComponentComponentTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Before
public void setup() {
  objectMapper = new ObjectMapper();
  underTest = new ComponentComponent();
  underTest.setRepositoryManager(repositoryManager);
  underTest.setContentPermissionChecker(contentPermissionChecker);
  underTest.setVariableResolverAdapterManager(variableResolverAdapterManager);
  underTest.setMaintenanceService(maintenanceService);
  underTest.setBrowseService(browseService);
  underTest.setSelectorFactory(selectorFactory);
  underTest.setObjectMapper(objectMapper);
  underTest.setComponentFinders(componentFinders);
  underTest.setBucketStore(bucketStore);

  when(repositoryManager.get("testRepositoryName")).thenReturn(repository);
  when(repository.getName()).thenReturn("testRepositoryName");
  when(repository.getFormat()).thenReturn(new Format("testFormat") { });
  when(repository.facet(ComponentMaintenance.class)).thenReturn(componentMaintenance);
  when(repository.facet(StorageFacet.class)).thenReturn(storageFacet);
  when(variableResolverAdapterManager.get("testFormat")).thenReturn(assetVariableResolver);
  when(storageFacet.txSupplier()).thenReturn(Suppliers.ofInstance(storageTx));
  when(componentFinders.get(any(String.class))).thenReturn(defaultComponentFinder);
}
 
Example #14
Source File: DeleteFolderServiceImplTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  when(repository.facet(ComponentMaintenance.class)).thenReturn(componentMaintenance);
  when(repository.getName()).thenReturn("repo");
  when(repository.getFormat()).thenReturn(new Format("maven2") { });
  when(configuration.getMaxNodes()).thenReturn(1);
  when(browseNodeStore.getByPath(repository.getName(), Arrays.asList("com", "sonatype"), 1)).thenReturn(browseNodes);
  when(variableResolverAdapterManager.get("maven2")).thenReturn(assetVariableResolver);
  when(assetVariableResolver.fromAsset(any(Asset.class))).thenReturn(variableSource);
  when(repository.facet(StorageFacet.class)).thenReturn(storageFacet);
  when(storageFacet.txSupplier()).thenReturn(Suppliers.ofInstance(storageTx));
  when(securityHelper.isPermitted(new RepositoryViewPermission(repository, BreadActions.DELETE)))
      .thenReturn(new boolean[]{false});

  service = new DeleteFolderServiceImpl(browseNodeStore, configuration, assetStore, contentPermissionChecker,
      variableResolverAdapterManager, securityHelper);
}
 
Example #15
Source File: MavenFacetImplTest.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);
      bind(MavenMetadataContentValidator.class).toInstance(mavenMetadataContentValidator);
      bind(MetadataRebuilder.class).toInstance(metadataRebuilder);
      bindConstant().annotatedWith(named("${nexus.maven.metadata.validation.enabled:-true}")).to(true);
      bind(new TypeLiteral<Map<String, MavenPathParser>>() { })
          .toInstance(ImmutableMap.of(Maven2Format.NAME, maven2MavenPathParser));
    }
  }).getInstance(MavenFacetImpl.class);

  underTest.attach(repository);
  when(repository.getType()).thenReturn(new HostedType());
  when(repository.facet(StorageFacet.class)).thenReturn(storageFacet);
  when(storageFacet.txSupplier()).thenReturn(() -> storageTx);

  UnitOfWork.begin(() -> storageTx);
}
 
Example #16
Source File: OrientComponentAssetTestHelper.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public boolean assetWithComponentExists(
    final Repository repository,
    final String path,
    final String group,
    final String name)
{
  return findAssetByName(repository, path)
      .map(Asset::componentId)
      .flatMap(componentId -> {
        try (StorageTx tx = repository.facet(StorageFacet.class).txSupplier().get()) {
          tx.begin();
          return Optional.ofNullable(tx.findComponent(componentId));
        }
      })
      .filter(component -> Objects.equals(component.group(), group))
      .filter(component -> Objects.equals(component.name(), name))
      .isPresent();
}
 
Example #17
Source File: OrientPyPiDeleteLegacyProxyAssetsTask.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
private void deleteLegacyAssets(final Repository repository) {
  log.info("Deleting legacy assets in PyPi proxy repository: {}", repository);
  StorageFacet storageFacet = repository.facet(StorageFacet.class);

  try (StorageTx tx = storageFacet.txSupplier().get()) {
    tx.begin();
    Bucket bucket = tx.findBucket(repository);
    stream(tx.browseAssets(bucket))
        .peek(a -> log.debug("Evaluating asset: {}", a.name()))
        .filter(this::isInvalidPath)
        .forEach(a -> {
          CancelableHelper.checkCancellation();
          log.info("Deleting asset: {}", a.name());
          tx.deleteAsset(a);
        });
    tx.commit();
  }
}
 
Example #18
Source File: OrientPyPiHostedFacetImpl.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
private Asset createIndexAsset(final String name,
                               final StorageTx tx,
                               final String indexPath,
                               final Bucket bucket) throws IOException
{
  String html = buildIndex(name, tx);

  Asset savedIndex = tx.createAsset(bucket, getRepository().getFormat());
  savedIndex.name(indexPath);
  savedIndex.formatAttributes().set(P_ASSET_KIND, AssetKind.INDEX.name());

  StorageFacet storageFacet = getRepository().facet(StorageFacet.class);
  TempBlob tempBlob = storageFacet.createTempBlob(new ByteArrayInputStream(html.getBytes(UTF_8)), HASH_ALGORITHMS);

  saveAsset(tx, savedIndex, tempBlob, TEXT_HTML, new AttributesMap());

  return savedIndex;
}
 
Example #19
Source File: DefaultIntegrityCheckStrategyTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Before
public void setup() throws Exception {
  defaultIntegrityCheckStrategy = spy(new TestIntegrityCheckFacet());

  checkFailed = false;

  assets = new HashSet<>();

  BlobStoreConfiguration blobStoreConfiguration = mock(BlobStoreConfiguration.class);
  when(blobStoreConfiguration.getName()).thenReturn("reponame");
  when(blobStore.getBlobStoreConfiguration()).thenReturn(blobStoreConfiguration);

  StorageFacet storageFacet = mock(StorageFacet.class);
  when(storageFacet.txSupplier()).thenReturn(() -> storageTx);
  when(repository.facet(StorageFacet.class)).thenReturn(storageFacet);

  when(storageTx.findBucket(repository)).thenReturn(bucket);
  when(storageTx.browseAssets(bucket)).thenReturn(assets);
}
 
Example #20
Source File: MavenProxyIndexFacet.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void publishIndex() throws IOException {
  log.debug("Fetching maven index properties from remote");
  UnitOfWork.begin(getRepository().facet(StorageFacet.class).txSupplier());
  try(DuplicateDetectionStrategy<Record> strategy = duplicateDetectionStrategyProvider.get()) {
    if (!prefetchIndexFiles(getRepository())) {
      if (Boolean.TRUE.equals(config.cacheFallback)) {
        log.debug("No remote index found... generating partial index from caches");
        publishHostedIndex(getRepository(), strategy);
      }
      else {
        log.debug("No remote index found... nothing to publish");
      }
    }
  }
  finally {
    UnitOfWork.end();
  }
}
 
Example #21
Source File: AptSnapshotFacetSupport.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Transactional(retryOn = {ONeedRetryException.class})
protected void createSnapshot(final String id, final Iterable<SnapshotItem> snapshots) throws IOException {
  StorageTx tx = UnitOfWork.currentTx();
  StorageFacet storageFacet = facet(StorageFacet.class);
  Bucket bucket = tx.findBucket(getRepository());
  for (SnapshotItem item : snapshots) {
    String assetName = createAssetPath(id, item.specifier.path);
    Asset asset = tx.createAsset(bucket, getRepository().getFormat()).name(assetName);
    try (final TempBlob streamSupplier = storageFacet
        .createTempBlob(item.content.openInputStream(), FacetHelper.hashAlgorithms)) {
      AssetBlob blob = tx.createBlob(item.specifier.path, streamSupplier, FacetHelper.hashAlgorithms, null,
          item.specifier.role.getMimeType(), true);
      tx.attachBlob(asset, blob);
    }
    finally {
      item.content.close();
    }
    tx.saveAsset(asset);
  }
}
 
Example #22
Source File: BaseRestoreBlobStrategy.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void restore(final Properties properties,
                    final Blob blob,
                    final String blobStoreName,
                    final boolean isDryRun)
{
  RestoreBlobData blobData = new RestoreBlobData(blob, properties, blobStoreName, repositoryManager);
  Optional<StorageFacet> storageFacet = blobData.getRepository().optionalFacet(StorageFacet.class);
  T restoreData = createRestoreData(blobData);

  if (storageFacet.isPresent() && canAttemptRestore(restoreData)) {
    doRestore(storageFacet.get(), blobData, restoreData, isDryRun);
  }
  else {
    log.debug("Skipping asset, blob store: {}, repository: {}, blob name: {}, blob id: {}",
        blobStoreName, blobData.getRepository().getName(), blobData.getBlobName(), blob.getId());
  }
}
 
Example #23
Source File: RUploadHandler.java    From nexus-repository-r with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public UploadResponse handle(final Repository repository, final ComponentUpload upload) throws IOException {
  final AssetUpload assetUpload = upload.getAssetUploads().get(0);
  final PartPayload payload = assetUpload.getPayload();
  final Map<String, String> fields = assetUpload.getFields();
  final String uploadPath = removeInitialSlashFromPath(fields.get(PATH_ID));
  final String assetPath = buildPath(uploadPath, payload.getName());

  ensurePermitted(repository.getName(), RFormat.NAME, assetPath, Collections.emptyMap());
  validateArchiveUploadPath(assetPath);

  try {
    UnitOfWork.begin(repository.facet(StorageFacet.class).txSupplier());
    Asset asset = repository.facet(RHostedFacet.class).upload(assetPath, payload);
    return new UploadResponse(asset);
  }
  finally {
    UnitOfWork.end();
  }
}
 
Example #24
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 #25
Source File: AttributesFacetImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public ImmutableNestedAttributesMap getAttributes() {
  return Transactional.operation.withDb(facet(StorageFacet.class).txSupplier()).call(() -> {
    final StorageTx tx = UnitOfWork.currentTx();
    final NestedAttributesMap attributes = tx.findBucket(getRepository()).attributes();
    return new ImmutableNestedAttributesMap(null, attributes.getKey(), attributes.backing());
  });
}
 
Example #26
Source File: CleanupPreviewComponentTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  policyPreviewXO = new CleanupPolicyPreviewXO();
  policyPreviewXO.setRepositoryName("repositoryName");
  policyPreviewXO.setCriteria(new CleanupPolicyCriteria());

  policy = MAPPER.writeValueAsString(policyPreviewXO);

  Filter filter = new Filter();
  filter.setProperty("cleanupPolicy");
  filter.setValue(policy);
  storeLoadParameters = new StoreLoadParameters();
  storeLoadParameters.setFilter(ImmutableList.of(filter));
  storeLoadParameters.setSort(ImmutableList.of(new Sort()));

  DefaultComponent component = new DefaultComponent();
  component.name("name");
  component.version("1.0.0");
  component.group("group");
  component.format("format");
  componentsFromSearch = new PagedResponse<>(1, ImmutableList.of(component));

  when(storageFacet.txSupplier()).thenReturn(() -> tx);
  when(repository.facet(StorageFacet.class)).thenReturn(storageFacet);

  when(cleanupPolicyStorage.newCleanupPolicy()).thenReturn(cleanupPolicy);

  underTest = new CleanupPreviewComponent(
      () -> new CleanupPreviewHelperImpl(cleanupPolicyStorage, cleanupComponentBrowse), repositoryManager);

  when(configuration.getConfiguration()).thenReturn(ImmutableMap.of(LAST_BLOB_UPDATED_KEY, true));
}
 
Example #27
Source File: OrientNpmHostedFacetTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
  underTest = new OrientNpmHostedFacet(npmRequestParser);
  underTest.attach(repository);

  when(npmFacet.putTarball(any(), any(), any(), any())).thenReturn(mockAsset);

  when(storageFacet.createTempBlob(any(Payload.class), any())).thenAnswer(invocation -> {
    when(tempBlob.get()).thenReturn(((Payload) invocation.getArguments()[0]).openInputStream());
    return tempBlob;
  });
  when(storageFacet.txSupplier()).thenReturn(() -> storageTx);
  when(repository.facet(StorageFacet.class)).thenReturn(storageFacet);

  when(storageTx.createAsset(any(), any(Format.class))).thenReturn(packageRootAsset);
  when(packageRootAsset.formatAttributes()).thenReturn(new NestedAttributesMap("metadata", new HashMap<>()));
  when(packageRootAsset.name(any())).thenReturn(packageRootAsset);

  when(repository.facet(NpmFacet.class)).thenReturn(npmFacet);

  when(tempBlob.getHashes())
      .thenReturn(Collections.singletonMap(HashAlgorithm.SHA1, HashCode.fromBytes("abcd".getBytes())));
  when(storageTx.createBlob(anyString(), Matchers.<Supplier<InputStream>> any(), anyCollection(), anyMap(),
      anyString(), anyBoolean()))
      .thenReturn(assetBlob);

  UnitOfWork.beginBatch(storageTx);
}
 
Example #28
Source File: NpmRequestParserTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  underTest = spy(new NpmRequestParser(securitySystem));

  when(tempBlob.get()).thenReturn(inputStream);
  when(tempBlob.getBlob()).thenReturn(blob);
  when(blob.getId()).thenReturn(blobId);
  when(blobId.toString()).thenReturn("blob-id");
  when(repository.facet(StorageFacet.class)).thenReturn(storageFacet);
  when(storageFacet.createTempBlob(eq(payload), any(Iterable.class))).thenAnswer(invocation -> tempBlob);
  when(parser.parse(null)).thenReturn(request);
  when(securitySystem.currentUser()).thenThrow(UserNotFoundException.class);
}
 
Example #29
Source File: OrientPyPiUploadHandler.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public UploadResponse handle(final Repository repository, final ComponentUpload upload) throws IOException {
  OrientPyPiHostedFacet facet = repository.facet(OrientPyPiHostedFacet.class);

  StorageFacet storageFacet = repository.facet(StorageFacet.class);
  PartPayload payload = upload.getAssetUploads().get(0).getPayload();
  try (TempBlob tempBlob = storageFacet.createTempBlob(payload, HASH_ALGORITHMS)) {
    final Map<String, String> metadata = facet.extractMetadata(tempBlob);

    if (metadata.isEmpty()) {
      throw new ValidationErrorsException("Unable to extract PyPI metadata from provided archive.");
    }

    String name = metadata.get(PyPiAttributes.P_NAME);
    String version = metadata.get(PyPiAttributes.P_VERSION);

    if (isBlank(name)) {
      throw new ValidationErrorsException("Metadata is missing the name attribute");
    }

    if (isBlank(version)) {
      throw new ValidationErrorsException("Metadata is missing the version attribute");
    }

    String filename = isNotBlank(payload.getName()) ? payload.getName() :
        name + '-' + version + '.' + metadata.get(P_ARCHIVE_TYPE);

    String path = facet.createPackagePath(name, version, filename);

    ensurePermitted(repository.getName(), PyPiFormat.NAME, path, coordinatesFromMetadata(metadata));

    return TransactionalStoreBlob.operation.withDb(storageFacet.txSupplier()).throwing(IOException.class)
        .call(() -> new UploadResponse(facet.upload(filename, metadata, new TempBlobPartPayload(payload, tempBlob))));
  }
}
 
Example #30
Source File: OrientMetadataRebuilderTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Before
public void setup() {
  bucket = new Bucket();
  bucket.setEntityMetadata(mockBucketEntityMetadata());

  when(storageFacet.txSupplier()).thenReturn(() -> storageTx);
  when(repository.facet(StorageFacet.class)).thenReturn(storageFacet);
  when(repository.facet(MavenFacet.class)).thenReturn(mavenFacet);
  when(storageTx.findBucket(repository)).thenReturn(bucket);
  when(mavenFacet.getMavenPathParser()).thenReturn(mavenPathParser);
  when(mavenPathParser.parsePath(anyString())).thenReturn(mock(MavenPath.class));

  Logger logger = (Logger)LoggerFactory.getLogger(ROOT_LOGGER_NAME);
  logger.addAppender(mockAppender);
}