org.sonatype.nexus.transaction.Transactional Java Examples

The following examples show how to use org.sonatype.nexus.transaction.Transactional. 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 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 #2
Source File: AptSnapshotFacetSupport.java    From nexus-repository-apt with Eclipse Public License 1.0 6 votes vote down vote up
@Transactional(retryOn = { ONeedRetryException.class })
@Override
public void createSnapshot(String id, SnapshotComponentSelector selector) throws IOException {
  StorageTx tx = UnitOfWork.currentTx();
  StorageFacet storageFacet = facet(StorageFacet.class);
  Bucket bucket = tx.findBucket(getRepository());
  Component component = tx.createComponent(bucket, getRepository().getFormat()).name(id);
  tx.saveComponent(component);
  for (SnapshotItem item : collectSnapshotItems(selector)) {
    String assetName = createAssetPath(id, item.specifier.path);
    Asset asset = tx.createAsset(bucket, component).name(assetName);
    try (final TempBlob streamSupplier = storageFacet.createTempBlob(item.content.openInputStream(), FacetHelper.hashAlgorithms)) {
      AssetBlob blob = tx.createBlob(item.specifier.path, streamSupplier, FacetHelper.hashAlgorithms, null,
          FacetHelper.determineContentType(item), true);
      tx.attachBlob(asset, blob);
    }
    finally {
      item.content.close();
    }
    tx.saveAsset(asset);
  }
}
 
Example #3
Source File: AptSnapshotFacetSupport.java    From nexus-repository-apt with Eclipse Public License 1.0 6 votes vote down vote up
@Transactional(retryOn = { ONeedRetryException.class })
@Override
public Content getSnapshotFile(String id, String path) throws IOException {
  StorageTx tx = UnitOfWork.currentTx();
  Bucket bucket = tx.findBucket(getRepository());
  Component component = tx.findComponentWithProperty(P_NAME, id, bucket);
  if (component == null) {
    return null;
  }

  final Asset asset = tx.findAssetWithProperty(P_NAME, createAssetPath(id, path), component);
  if (asset == null) {
    return null;
  }

  final Blob blob = tx.requireBlob(asset.requireBlobRef());
  return FacetHelper.toContent(asset, blob);
}
 
Example #4
Source File: MavenIndexPublisher.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Publishes MI index into {@code target}, sourced from repository's own CMA structures.
 */
public static void publishHostedIndex(final Repository repository,
                                      final DuplicateDetectionStrategy<Record> duplicateDetectionStrategy)
    throws IOException
{
  checkNotNull(repository);
  Transactional.operation.throwing(IOException.class).call(
      () -> {
        final StorageTx tx = UnitOfWork.currentTx();
        try (Maven2WritableResourceHandler resourceHandler = new Maven2WritableResourceHandler(repository)) {
          try (IndexWriter indexWriter = new IndexWriter(resourceHandler, repository.getName(), false)) {
            indexWriter.writeChunk(
                transform(
                    decorate(
                        filter(getHostedRecords(tx, repository), duplicateDetectionStrategy),
                        repository.getName()
                    ),
                    RECORD_COMPACTOR::apply
                ).iterator()
            );
          }
        }
        return null;
      }
  );
}
 
Example #5
Source File: CondaComponentMaintenanceFacet.java    From nexus-public 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 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 #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: DatastoreBrowseNodeStoreImpl.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
@Transactional
public void createComponentNode(
    final String repositoryName,
    final String format,
    final List<BrowsePath> paths,
    final Component component)
{
  checkNotNull(repositoryName);
  checkNotNull(format);
  checkNotNull(paths);
  checkArgument(!paths.isEmpty());
  checkNotNull(component);

  createNodes(repositoryName, paths).ifPresent(nodeId -> dao().linkComponent(nodeId, component));
}
 
Example #8
Source File: GolangHostedFacetImpl.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
@Nullable
@Transactional
public Content getInfo(final String path,
                       final GolangAttributes golangAttributes)
{
  checkNotNull(path);
  checkNotNull(golangAttributes);
  String newPath = getZipAssetPathFromInfoPath(path);

  StreamPayload streamPayload = extractInfoFromZip(golangAttributes, newPath);
  if (streamPayload == null) {
    return null;
  }
  return new Content(streamPayload);
}
 
Example #9
Source File: GolangHostedFacetImpl.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Transactional
@Override
public Content getList(final String module) {
  checkNotNull(module);

  StorageTx tx = UnitOfWork.currentTx();

  Iterable<Asset> assetsForModule = golangDataAccess.findAssetsForModule(tx, getRepository(), module);

  List<String> collection = StreamSupport.stream(assetsForModule.spliterator(), false)
      .filter(asset -> PACKAGE.name().equals(asset.formatAttributes().get(P_ASSET_KIND)))
      .map(Asset::name)
      .map(name -> name.split("/@v/")[1])
      .map(name -> name.replaceAll(".zip", ""))
      .collect(Collectors.toList());

  if (collection.isEmpty()) {
    return null;
  }

  String listOfVersions = String.join("\n", collection);

  return new Content(new BytesPayload(listOfVersions.getBytes(UTF_8), TEXT_PLAIN));
}
 
Example #10
Source File: SecurityConfigurationImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Transactional
@Override
public void updatePrivilege(final CPrivilege privilege) {
  checkNotNull(privilege);

  privilege.setVersion(privilege.getVersion() + 1);
  if (!privilegeDAO().update(convert(privilege))) {
    throw new NoSuchPrivilegeException(privilege.getId());
  }
}
 
Example #11
Source File: SecurityConfigurationImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Transactional
@Override
public CPrivilege addPrivilege(final CPrivilege privilege) {
  checkNotNull(privilege);
  try {
    privilegeDAO().create(convert(privilege));
    return privilege;
  }
  catch (RuntimeException e) {
    if (causedByDuplicateKey(e)) {
      throw new DuplicatePrivilegeException(privilege.getId());
    }
    throw e;
  }
}
 
Example #12
Source File: SecurityConfigurationImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Transactional
@Override
public boolean removeUserRoleMapping(final String userId, final String source) {
  checkNotNull(userId);
  checkNotNull(source);

  return userRoleMappingDAO().delete(userId, source);
}
 
Example #13
Source File: OrientMetadataRebuilder.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns {@link Iterable} with Orient documents for GAVs.
 */
private Iterable<ODocument> browseGAVs() {
  return Transactional.operation.call(() -> {
    final StorageTx tx = UnitOfWork.currentTx();
    return tx.browse(sql, sqlParams, bufferSize, timeoutSeconds);
  });
}
 
Example #14
Source File: SecurityConfigurationImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Transactional
@Override
public boolean removeRole(final String id) {
  checkNotNull(id);

  if (!roleDAO().delete(id)) {
    throw new NoSuchRoleException(id);
  }
  return true;
}
 
Example #15
Source File: FormatStoreManagerTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private static void assertDaoBinding(final ContentStoreSupport<?> store,
                                     final Class<? extends ContentDataAccess> daoClass)
{
  // internal dao() method expects to be called from a transactional method, so mimic one here
  UnitOfWork.begin(store::openSession);
  try {
    Transactional.operation.run(() -> assertThat(store.dao(), is(instanceOf(daoClass))));
  }
  finally {
    UnitOfWork.end();
  }
}
 
Example #16
Source File: SecurityConfigurationImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Transactional
@Override
public boolean removePrivilege(final String id) {
  checkNotNull(id);

  if (!privilegeDAO().delete(id)) {
    throw new NoSuchPrivilegeException(id);
  }
  return true;
}
 
Example #17
Source File: OrientNpmGroupFacet.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Nullable
@Transactional(retryOn = ONeedRetryException.class, swallow = ORecordNotFoundException.class)
protected void doInvalidate(final NpmPackageId packageId) {
  StorageTx tx = UnitOfWork.currentTx();
  Bucket bucket = tx.findBucket(getRepository());

  Asset asset = findPackageRootAsset(tx, bucket, packageId);
  if (nonNull(asset) && invalidateAsset(asset)) {
    tx.saveAsset(asset);
  }
}
 
Example #18
Source File: SecurityConfigurationImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Transactional
@Override
public void updateUser(final CUser user) throws UserNotFoundException {
  checkNotNull(user);

  user.setVersion(user.getVersion() + 1);
  if (!userDAO().update(convert(user))) {
    throw new UserNotFoundException(user.getId());
  }
}
 
Example #19
Source File: ContentFacetSupport.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
@Transactional
protected void doDelete() throws Exception {
  if (configRepositoryId != null) {
    stores.assetStore.deleteAssets(contentRepositoryId);
    stores.componentStore.deleteComponents(contentRepositoryId);
    stores.contentRepositoryStore.deleteContentRepository(configRepositoryId);
  }
}
 
Example #20
Source File: ApiKeyStoreImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Transactional
@Override
public char[] getApiKey(final String domain, final PrincipalCollection principals) {
  return dao().findApiKey(domain, principals.getPrimaryPrincipal().toString())
      .map(ApiKeyToken::getChars)
      .orElse(null);
}
 
Example #21
Source File: AptProxyFacet.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Transactional(retryOn = {ONeedRetryException.class})
protected void doIndicateVerified(final Content content, final CacheInfo cacheInfo, final String assetPath) {
  StorageTx tx = UnitOfWork.currentTx();
  Bucket bucket = tx.findBucket(getRepository());

  Asset asset = Content.findAsset(tx, bucket, content);
  if (asset == null) {
    asset = tx.findAssetWithProperty(P_NAME, assetPath, bucket);
  }
  if (asset == null) {
    return;
  }
  CacheInfo.applyToAsset(asset, cacheInfo);
  tx.saveAsset(asset);
}
 
Example #22
Source File: AptHostedComponentMaintenanceFacet.java    From nexus-public with Eclipse Public License 1.0 5 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();
  }

  String assetKind = asset.formatAttributes().get(P_ASSET_KIND, String.class);
  Set<String> result = super.deleteAssetTx(assetId, deleteBlobs);
  if ("DEB".equals(assetKind)) {
    try {
      getRepository().facet(AptHostedFacet.class)
          .rebuildIndexes(Collections.singletonList(new AptHostedFacet.AssetChange(AssetAction.REMOVED, asset)));
    }
    catch (IOException e) {
      throw new UncheckedIOException(e);
    }
  }

  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 result;
}
 
Example #23
Source File: SearchFacetImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the JSON document representing the given component in the repository's index.
 */
@Nullable
@Transactional
protected String json(@Nullable final EntityId componentId) {
  if (componentId != null) {
    StorageTx tx = UnitOfWork.currentTx();
    Component component = componentEntityAdapter.read(tx.getDb(), componentId);
    if (component != null) {
      Iterable<Asset> assets = tx.browseAssets(component);
      return producer(component).getMetadata(component, assets, repositoryMetadata);
    }
  }
  return null;
}
 
Example #24
Source File: AptSnapshotFacetSupport.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Transactional(retryOn = {ONeedRetryException.class})
@Override
@Nullable
public Content getSnapshotFile(final String id, final String path) throws IOException {
  StorageTx tx = UnitOfWork.currentTx();
  Bucket bucket = tx.findBucket(getRepository());
  final Asset asset = tx.findAssetWithProperty(P_NAME, createAssetPath(id, path), bucket);
  if (asset == null) {
    return null;
  }

  final Blob blob = tx.requireBlob(asset.requireBlobRef());
  return FacetHelper.toContent(asset, blob);
}
 
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: DefaultIntegrityCheckStrategy.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private Iterable<Asset> getAssets(final Repository repository) {
  return Transactional.operation
      .withDb(repository.facet(StorageFacet.class).txSupplier())
      .call(() -> {
        final StorageTx tx = UnitOfWork.currentTx();
        return tx.browseAssets(tx.findBucket(repository));
      });

}
 
Example #27
Source File: ApiKeyStoreImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Transactional
@Override
public void persistApiKey(final String domain, final PrincipalCollection principals, final char[] apiKey) {
  ApiKeyData apiKeyData = new ApiKeyData();
  apiKeyData.setDomain(domain);
  apiKeyData.setPrincipals(principals);
  apiKeyData.setApiKey(apiKey);
  dao().save(apiKeyData);
}
 
Example #28
Source File: SecurityConfigurationImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Transactional
@Override
public CPrivilege getPrivilege(final String id) {
  checkNotNull(id);

  return privilegeDAO().read(id).orElse(null);
}
 
Example #29
Source File: CleanupPreviewHelperImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Transactional
protected PagedResponse<ComponentXO> searchForComponents(final Repository repository,
                                                         final CleanupPolicy cleanupPolicy,
                                                         final QueryOptions queryOptions)
{
  PagedResponse<Component> components = cleanupComponentBrowse.browseByPage(cleanupPolicy, repository, queryOptions);

  List<ComponentXO> componentXOS = components.getData().stream()
      .map(item -> COMPONENT_CONVERTER.apply(item, repository.getName()))
      .collect(toList());

  return new PagedResponse<>(components.getTotal(), componentXOS);
}
 
Example #30
Source File: SecurityConfigurationImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Transactional
@Override
public void addUserRoleMapping(final CUserRoleMapping mapping) {
  checkNotNull(mapping);

  userRoleMappingDAO().create(convert(mapping));
}