Java Code Examples for org.sonatype.nexus.transaction.UnitOfWork#currentTx()

The following examples show how to use org.sonatype.nexus.transaction.UnitOfWork#currentTx() . 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: NpmFacetImpl.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Nullable
@Override
public Asset putPackageRoot(final String packageId,
                            final AssetBlob assetBlob,
                            @Nullable final AttributesMap contentAttributes)
    throws IOException
{
  final Repository repository = getRepository();
  final StorageTx tx = UnitOfWork.currentTx();
  final Bucket bucket = tx.findBucket(repository);
  Asset asset = NpmFacetUtils.findPackageRootAsset(tx, bucket, NpmPackageId.parse(packageId));

  if (asset == null) {
    asset = tx.createAsset(bucket, repository.getFormat()).name(packageId);
    saveAsset(tx, asset, assetBlob, PACKAGE_ROOT, contentAttributes);
  }

  return asset;
}
 
Example 2
Source File: OrientNpmProxyFacet.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@TransactionalTouchMetadata
protected Content getDistTags(final NpmPackageId packageId) {
  checkNotNull(packageId);
  StorageTx tx = UnitOfWork.currentTx();
  Asset packageRootAsset = NpmFacetUtils.findPackageRootAsset(tx, tx.findBucket(getRepository()), packageId);
  if (packageRootAsset != null) {
    try {
      final NestedAttributesMap attributesMap = NpmFacetUtils.loadPackageRoot(tx, packageRootAsset);
      final NestedAttributesMap distTags = attributesMap.child(DIST_TAGS);
      return NpmFacetUtils.distTagsToContent(distTags);
    }
    catch (IOException e) {
      log.error("Unable to read packageRoot {}", packageId.id(), e);
    }
  }
  return null;
}
 
Example 3
Source File: OrientNpmHostedFacet.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@TransactionalStoreBlob
protected void putPublishRequest(final NpmPackageId packageId,
                                 @Nullable final String revision,
                                 final NpmPublishRequest request)
    throws IOException
{
  log.debug("Storing package: {}", packageId);
  StorageTx tx = UnitOfWork.currentTx();

  NestedAttributesMap packageRoot = request.getPackageRoot();

  // process attachments, if any
  NestedAttributesMap attachments = packageRoot.child("_attachments");
  if (!attachments.isEmpty()) {
    for (String name : attachments.keys()) {
      NestedAttributesMap attachment = attachments.child(name);
      NestedAttributesMap packageVersion = selectVersionByTarballName(packageRoot, name);
      putTarball(tx, packageId, packageVersion, attachment, request);
    }
  }

  putPackageRoot(packageId, revision, packageRoot);
}
 
Example 4
Source File: ElasticSearchCleanupComponentBrowse.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public PagedResponse<Component> browseByPage(final CleanupPolicy policy,
                                             final Repository repository,
                                             final QueryOptions options)
{
  checkNotNull(options.getStart());
  checkNotNull(options.getLimit());

  StorageTx tx = UnitOfWork.currentTx();

  QueryBuilder query = convertPolicyToQuery(policy, options);

  log.debug("Searching for components to cleanup using policy {}", policy);

  SearchResponse searchResponse = invokeSearchByPage(policy, repository, options, query);

  List<Component> components = stream(searchResponse.getHits().spliterator(), false)
      .map(searchHit -> tx.findComponent(new DetachedEntityId(searchHit.getId())))
      .filter(Objects::nonNull)
      .collect(toList());

  return new PagedResponse<>(searchResponse.getHits().getTotalHits(), components);
}
 
Example 5
Source File: ConanProxyFacet.java    From nexus-repository-conan with Eclipse Public License 1.0 6 votes vote down vote up
@TransactionalStoreBlob
protected Content doPutPackage(final TempBlob tempBlob,
                               final Payload content,
                               final ConanCoords coords,
                               final AssetKind assetKind) throws IOException
{
  StorageTx tx = UnitOfWork.currentTx();
  Bucket bucket = tx.findBucket(getRepository());
  Component component = getOrCreateComponent(tx, bucket, coords);

  String assetPath = getProxyAssetPath(coords, assetKind);
  Asset asset = findAsset(tx, bucket, assetPath);
  if (asset == null) {
    asset = tx.createAsset(bucket, component);
    asset.name(assetPath);
    asset.formatAttributes().set(P_ASSET_KIND, CONAN_PACKAGE.name());
  }
  else if (!asset.componentId().equals(EntityHelper.id(component))) {
    asset.componentId(EntityHelper.id(component));
  }
  return saveAsset(tx, asset, tempBlob, content, null);
}
 
Example 6
Source File: ComposerContentFacetImpl.java    From nexus-repository-composer with Eclipse Public License 1.0 6 votes vote down vote up
@Nullable
@Override
@TransactionalTouchBlob
public Content get(final String path) throws IOException {
  StorageTx tx = UnitOfWork.currentTx();

  final Asset asset = findAsset(tx, path);
  if (asset == null) {
    return null;
  }
  if (asset.markAsDownloaded()) {
    tx.saveAsset(asset);
  }

  final Blob blob = tx.requireBlob(asset.requireBlobRef());
  return toContent(asset, blob);
}
 
Example 7
Source File: P2ProxyFacetImpl.java    From nexus-repository-p2 with Eclipse Public License 1.0 6 votes vote down vote up
@TransactionalStoreBlob
protected Content saveMetadataAsAsset(final String assetPath,
                                      final TempBlob metadataContent,
                                      final Payload payload,
                                      final AssetKind assetKind) throws IOException
{
  StorageTx tx = UnitOfWork.currentTx();
  Bucket bucket = tx.findBucket(getRepository());

  Asset asset = facet(P2Facet.class).findAsset(tx, bucket, assetPath);
  if (asset == null) {
    asset = tx.createAsset(bucket, getRepository().getFormat());
    asset.name(assetPath);
    asset.formatAttributes().set(P_ASSET_KIND, assetKind.name());
  }

  return facet(P2Facet.class).saveAsset(tx, asset, metadataContent, payload);
}
 
Example 8
Source File: RawContentFacetImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
@TransactionalDeleteBlob
public boolean delete(final String path) throws IOException {
  StorageTx tx = UnitOfWork.currentTx();

  final Component component = findComponent(tx, tx.findBucket(getRepository()), path);
  if (component == null) {
    return false;
  }

  tx.deleteComponent(component);
  return true;
}
 
Example 9
Source File: OrientPyPiHostedFacetImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
protected Asset savePyPiWheelPayload(
    final String filename,
    final Map<String, String> attributes,
    final TempBlobPartPayload wheelPayload) throws IOException
{
  checkNotNull(filename);

  TempBlob tempBlob = wheelPayload.getTempBlob();

  final String name = checkNotNull(attributes.get(P_NAME));
  final String version = checkNotNull(attributes.get(P_VERSION));
  final String normalizedName = normalizeName(name);

  validateMd5Hash(attributes, tempBlob);

  PyPiIndexFacet indexFacet = facet(PyPiIndexFacet.class);
  // A package has been added or redeployed and therefore the cached index is no longer relevant
  indexFacet.deleteIndex(name);

  StorageTx tx = UnitOfWork.currentTx();
  Bucket bucket = tx.findBucket(getRepository());

  String packagePath = createPackagePath(name, version, filename);

  Component component = findOrCreateComponent(name, version, normalizedName, indexFacet, tx, bucket);

  component.formatAttributes().set(P_SUMMARY, attributes.get(P_SUMMARY)); // use the most recent summary received?
  tx.saveComponent(component);

  Asset asset = findOrCreateAsset(tx, bucket, packagePath, component, AssetKind.PACKAGE.name());

  copyAttributes(asset, attributes);
  saveAsset(tx, asset, tempBlob, wheelPayload);

  return asset;
}
 
Example 10
Source File: HelmProxyFacetImpl.java    From nexus-repository-helm with Eclipse Public License 1.0 5 votes vote down vote up
@TransactionalTouchMetadata
public void setCacheInfo(final Content content, final CacheInfo cacheInfo) {
  StorageTx tx = UnitOfWork.currentTx();
  Asset asset = Content.findAsset(tx, tx.findBucket(getRepository()), content);
  if (asset == null) {
    log.debug(
        "Attempting to set cache info for non-existent Helm asset {}", content.getAttributes().require(Asset.class)
    );
    return;
  }
  log.debug("Updating cacheInfo of {} to {}", asset, cacheInfo);
  CacheInfo.applyToAsset(asset, cacheInfo);
  tx.saveAsset(asset);
}
 
Example 11
Source File: HelmRestoreFacetImpl.java    From nexus-repository-helm with Eclipse Public License 1.0 5 votes vote down vote up
@Override
@TransactionalTouchBlob
public void restore(final AssetBlob assetBlob, final String path) throws IOException {
  StorageTx tx = UnitOfWork.currentTx();
  AssetKind assetKind = AssetKind.getAssetKindByFileName(path);
  HelmAttributes attributes = helmAttributeParser.getAttributes(assetKind, assetBlob.getBlob().getInputStream());
  Asset asset = helmFacet.findOrCreateAsset(tx, path, assetKind, attributes);
  tx.attachBlob(asset, assetBlob);
  Content.applyToAsset(asset, Content.maintainLastModified(asset, new AttributesMap()));
  tx.saveAsset(asset);
}
 
Example 12
Source File: OrientMavenGroupFacet.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Tries to invalidate the current main cached asset for the given {@link MavenPath}.
 */
@Transactional(retryOn = ONeedRetryException.class, swallow = ORecordNotFoundException.class)
protected void doInvalidate(final MavenPath mavenPath) {
  StorageTx tx = UnitOfWork.currentTx();
  final Asset asset = findAsset(tx, tx.findBucket(getRepository()), mavenPath.main());
  if (asset != null && CacheInfo.invalidateAsset(asset)) {
    tx.saveAsset(asset);
  }
}
 
Example 13
Source File: MavenFacetImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@TransactionalStoreBlob
protected Content doPut(final MavenPath path,
                        final TempBlob blob,
                        final String contentType,
                        final AttributesMap contentAttributes)
    throws IOException
{
  StorageTx tx = UnitOfWork.currentTx();

  AssetBlob assetBlob = tx.createBlob(path.getPath(), blob, null, contentType, true);

  return doPutAssetBlob(path, contentAttributes, tx, assetBlob);
}
 
Example 14
Source File: PurgeUnusedFacetImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Delete all unused assets.
 */
@TransactionalDeleteBlob
protected void deleteUnusedAssets(final Date olderThan) {
  StorageTx tx = UnitOfWork.currentTx();

  for (Asset asset : findUnusedAssets(tx, olderThan)) {
    checkCancellation();
    log.debug("Deleting unused asset {}", asset);
    tx.deleteAsset(asset); // TODO: commit in batches
  }
}
 
Example 15
Source File: RProxyFacetImpl.java    From nexus-repository-r with Eclipse Public License 1.0 5 votes vote down vote up
@TransactionalTouchBlob
protected Content getAsset(final String name) {
  StorageTx tx = UnitOfWork.currentTx();

  Asset asset = findAsset(tx, tx.findBucket(getRepository()), name);
  if (asset == null) {
    return null;
  }
  if (asset.markAsDownloaded()) {
    tx.saveAsset(asset);
  }
  return toContent(asset, tx.requireBlob(asset.requireBlobRef()));
}
 
Example 16
Source File: AptFacetImpl.java    From nexus-repository-apt with Eclipse Public License 1.0 5 votes vote down vote up
@Override
@Nullable
@TransactionalTouchBlob
public Content get(String path) throws IOException {
  final StorageTx tx = UnitOfWork.currentTx();
  final Asset asset = tx.findAssetWithProperty(P_NAME, path, tx.findBucket(getRepository()));
  if (asset == null) {
    return null;
  }

  return FacetHelper.toContent(asset, tx.requireBlob(asset.requireBlobRef()));
}
 
Example 17
Source File: BaseRestoreBlobStrategy.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@TransactionalDeleteBlob
protected void deleteAsset(final Repository repository, final String assetName) throws IOException {
  StorageTx tx = UnitOfWork.currentTx();
  Asset asset = findAsset(repository, assetName);
  if (asset != null) {
    tx.deleteAsset(asset, false);
  }
}
 
Example 18
Source File: LastDownloadedHandler.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Transactional(swallow = {
    // silently skip if the record has been deleted, someone else updated it, or the system is in read-only mode
    ORecordNotFoundException.class, ONeedRetryException.class, OModificationOperationProhibitedException.class })
@VisibleForTesting
protected void tryPersistLastDownloadedTime(final Asset asset) {
  StorageTx tx = UnitOfWork.currentTx();
  // reload asset in case it's changed since it was stored in the response
  Asset latestAsset = tx.findAsset(EntityHelper.id(asset));
  if (latestAsset != null && assetManager.maybeUpdateLastDownloaded(latestAsset)) {
    tx.saveAsset(latestAsset);
  }
}
 
Example 19
Source File: RepairMetadataComponent.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
protected Iterable<Asset> readAssets(final Repository repository, final String lastId) {
  StorageTx storageTx = UnitOfWork.currentTx();
  Map<String, Object> parameters = ImmutableMap.of("rid", lastId, "limit", BATCH_SIZE);
  return storageTx.findAssets(ASSETS_WHERE, parameters, singletonList(repository), ASSETS_SUFFIX);
}
 
Example 20
Source File: SearchFacetImpl.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
@Transactional
protected void rebuildComponentIndex() {
  try {
    Repository repository = getRepository();
    StorageTx tx = UnitOfWork.currentTx();
    Bucket bucket = tx.findBucket(repository);
    ORID bucketId = bucketEntityAdapter.recordIdentity(bucket);

    if (bucket == null) {
      log.warn("Unable to rebuild search index for repository {}", repository.getName());
      return;
    }

    long processed = 0;
    long total = componentStore.countComponents(ImmutableList.of(bucket));

    if (total > 0) {
      ProgressLogIntervalHelper progressLogger = new ProgressLogIntervalHelper(log, 60);
      Stopwatch sw = Stopwatch.createStarted();

      OIndexCursor cursor = componentStore.getIndex(ComponentEntityAdapter.I_BUCKET_GROUP_NAME_VERSION).cursor();
      List<Entry<OCompositeKey, EntityId>> nextPage = componentStore.getNextPage(cursor, PAGE_SIZE);
      while (!Iterables.isEmpty(nextPage)) {
        List<EntityId> componentIds = nextPage.stream()
            .filter(entry -> bucketId.equals(entry.getKey().getKeys().get(BUCKET)))
            .map(Entry::getValue)
            .collect(toList());

        processed += componentIds.size();

        bulkPut(componentIds);

        long elapsed = sw.elapsed(TimeUnit.MILLISECONDS);
        progressLogger
            .info("Indexed {} / {} {} components in {} ms", processed, total, repository.getName(), elapsed);

        nextPage = componentStore.getNextPage(cursor, PAGE_SIZE);
      }
      progressLogger.flush(); // ensure the final progress message is flushed
    }
  }
  catch (Exception e) {
    log.error("Unable to rebuild search index for repository {}", getRepository().getName(), e);
  }
}