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

The following examples show how to use org.sonatype.nexus.transaction.UnitOfWork#begin() . 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: 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 2
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 3
Source File: OrientMavenTestHelper.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void verifyHashesExistAndCorrect(final Repository repository, final String path) throws Exception {
  final MavenFacet mavenFacet = repository.facet(MavenFacet.class);
  final MavenPath mavenPath = mavenFacet.getMavenPathParser().parsePath(path);
  UnitOfWork.begin(repository.facet(StorageFacet.class).txSupplier());
  try {
    final Content content = mavenFacet.get(mavenPath);
    assertThat(content, notNullValue());
    final Map<HashAlgorithm, HashCode> hashCodes =
        content.getAttributes().require(Content.CONTENT_HASH_CODES_MAP, Content.T_CONTENT_HASH_CODES_MAP);
    for (HashType hashType : HashType.values()) {
      final Content contentHash = mavenFacet.get(mavenPath.hash(hashType));
      final String storageHash = hashCodes.get(hashType.getHashAlgorithm()).toString();
      assertThat(storageHash, notNullValue());
      try (InputStream is = contentHash.openInputStream()) {
        final String mavenHash = CharStreams.toString(new InputStreamReader(is, StandardCharsets.UTF_8));
        assertThat(storageHash, equalTo(mavenHash));
      }
    }
  }
  finally {
    UnitOfWork.end();
  }
}
 
Example 4
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 5
Source File: AptComponentDirector.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void afterMove(final List<Map<String, String>> components, final Repository destination) {
  destination.facet(StorageFacet.class).txSupplier();
  UnitOfWork.begin(destination.facet(StorageFacet.class).txSupplier());
  try {
    AptHostedFacet hostedFacet = destination.facet(AptHostedFacet.class);
    hostedFacet.rebuildIndexes();
  }
  catch (IOException e) {
    log.error("Failed to update metadata, repository: {}", destination.getName(), e);
    throw new UncheckedIOException(e);
  }
  finally {
    UnitOfWork.end();
  }
}
 
Example 6
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 7
Source File: RawITSupport.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
protected Content read(final Repository repository, final String path) throws IOException {
  RawContentFacet rawFacet = repository.facet(RawContentFacet.class);
  UnitOfWork.begin(repository.facet(StorageFacet.class).txSupplier());
  try {
    return rawFacet.get(path);
  }
  finally {
    UnitOfWork.end();
  }
}
 
Example 8
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 9
Source File: SearchFacetImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
@Guarded(by = STARTED)
public void rebuildIndex() {
  log.info("Rebuilding index of repository {}", getRepository().getName());
  searchIndexService.rebuildIndex(getRepository());
  UnitOfWork.begin(facet(StorageFacet.class).txSupplier());
  try {
    rebuildComponentIndex();
  }
  finally {
    UnitOfWork.end();
  }
}
 
Example 10
Source File: MavenIndexPublisher.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private static Iterable<Iterable<Record>> getGroupRecords(final List<Repository> repositories, final Closer closer)
    throws IOException
{
  UnitOfWork paused = UnitOfWork.pause();
  try {
    List<Iterable<Record>> records = new ArrayList<>();
    for (Repository repository : repositories) {
      UnitOfWork.begin(repository.facet(StorageFacet.class).txSupplier());
      try {
        ResourceHandler resourceHandler = closer.register(new Maven2WritableResourceHandler(repository));
        IndexReader indexReader = closer.register(new IndexReader(null, resourceHandler));
        ChunkReader chunkReader = closer.register(indexReader.iterator().next());
        records.add(filter(transform(chunkReader, RECORD_EXPANDER::apply), new RecordTypeFilter(Type.ARTIFACT_ADD)));
      }
      catch (IllegalArgumentException e) {
        throw new IOException(e.getMessage(), e);
      }
      finally {
        UnitOfWork.end();
      }
    }
    return records;
  }
  finally {
    UnitOfWork.resume(paused);
  }
}
 
Example 11
Source File: OrientMavenHostedIndexFacet.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void publishIndex() throws IOException {
  UnitOfWork.begin(getRepository().facet(StorageFacet.class).txSupplier());
  try (DuplicateDetectionStrategy<Record> strategy = duplicateDetectionStrategyProvider.get()) {
    MavenIndexPublisher.publishHostedIndex(getRepository(), strategy);
  }
  finally {
    UnitOfWork.end();
  }
}
 
Example 12
Source File: MavenIndexFacetSupport.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void unpublishIndex() throws IOException {
  UnitOfWork.begin(getRepository().facet(StorageFacet.class).txSupplier());
  try {
    MavenIndexPublisher.unpublishIndexFiles(getRepository());
  }
  finally {
    UnitOfWork.end();
  }
}
 
Example 13
Source File: CleanupPreviewHelperImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public PagedResponse<ComponentXO> getSearchResults(final CleanupPolicyPreviewXO previewXO,
                                                   final Repository repository,
                                                   final QueryOptions queryOptions)
{
  CleanupPolicy cleanupPolicy = toCleanupPolicy(previewXO);

  UnitOfWork.begin(repository.facet(StorageFacet.class).txSupplier());
  try {
    return searchForComponents(repository, cleanupPolicy, queryOptions);
  } finally {
    UnitOfWork.end();
  }
}
 
Example 14
Source File: AptUploadHandler.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 {
  AptHostedFacet hostedFacet = repository.facet(AptHostedFacet.class);
  StorageFacet storageFacet = repository.facet(StorageFacet.class);

  try (TempBlob tempBlob = storageFacet
      .createTempBlob(upload.getAssetUploads().get(0).getPayload(), FacetHelper.hashAlgorithms)) {
    ControlFile controlFile = AptPackageParser.parsePackage(tempBlob);
    if (controlFile == null) {
      throw new IOException("Invalid debian package:  no control file");
    }
    String name = controlFile.getField("Package").map(f -> f.value).get();
    String version = controlFile.getField("Version").map(f -> f.value).get();
    String architecture = controlFile.getField("Architecture").map(f -> f.value).get();
    String assetPath = FacetHelper.buildAssetPath(name, version, architecture);

    doValidation(repository, assetPath);

    UnitOfWork.begin(storageFacet.txSupplier());
    try {
      Asset asset = hostedFacet.ingestAsset(upload.getAssetUploads().get(0).getPayload());
      return new UploadResponse(asset);
    }
    finally {
      UnitOfWork.end();
    }
  }
}
 
Example 15
Source File: OrientMavenTestHelper.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Payload read(final Repository repository, final String path) throws IOException {
  final MavenFacet mavenFacet = repository.facet(MavenFacet.class);
  final MavenPath mavenPath = mavenFacet.getMavenPathParser().parsePath(path);
  UnitOfWork.begin(repository.facet(StorageFacet.class).txSupplier());
  try {
    return mavenFacet.get(mavenPath);
  }
  finally {
    UnitOfWork.end();
  }
}
 
Example 16
Source File: OrientMavenTestHelper.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void write(final Repository repository, final String path, final Payload payload) throws IOException {
  final MavenFacet mavenFacet = repository.facet(MavenFacet.class);
  final MavenPath mavenPath = mavenFacet.getMavenPathParser().parsePath(path);
  UnitOfWork.begin(repository.facet(StorageFacet.class).txSupplier());
  try {
    mavenFacet.put(mavenPath, payload);
  }
  finally {
    UnitOfWork.end();
  }
}
 
Example 17
Source File: AptUploadHandler.java    From nexus-repository-apt with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public UploadResponse handle(Repository repository, ComponentUpload upload) throws IOException {
  AptHostedFacet hostedFacet = repository.facet(AptHostedFacet.class);
  StorageFacet storageFacet = repository.facet(StorageFacet.class);

  try (TempBlob tempBlob = storageFacet.createTempBlob(upload.getAssetUploads().get(0).getPayload(), FacetHelper.hashAlgorithms)) {
    ControlFile controlFile = AptPackageParser.parsePackage(tempBlob);
    if (controlFile == null) {
      throw new IOException("Invalid debian package:  no control file");
    }
    String name = controlFile.getField("Package").map(f -> f.value).get();
    String version = controlFile.getField("Version").map(f -> f.value).get();
    String architecture = controlFile.getField("Architecture").map(f -> f.value).get();
    String assetPath = FacetHelper.buildAssetPath(name, version, architecture);

    doValidation(repository, assetPath);

    UnitOfWork.begin(storageFacet.txSupplier());
    try {
      Asset asset = hostedFacet.ingestAsset(upload.getAssetUploads().get(0).getPayload());
      return new UploadResponse(asset);
    }
    catch (PGPException e) {
      throw new IOException(e);
    }
    finally {
      UnitOfWork.end();
    }
  }
}
 
Example 18
Source File: UnitOfWorkHandler.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Response handle(Context context) throws Exception {
  UnitOfWork.begin(context.getRepository().facet(StorageFacet.class).txSupplier());
  try {
    return context.proceed();
  }
  finally {
    UnitOfWork.end();
  }
}
 
Example 19
Source File: BaseRestoreBlobStrategy.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
private void doRestore(StorageFacet storageFacet, RestoreBlobData blobData, T restoreData, boolean isDryRun) {
  String logPrefix = isDryRun ? dryRunPrefix.get() : "";
  String path = getAssetPath(restoreData);
  String blobStoreName = blobData.getBlobStoreName();
  String repoName = blobData.getRepository().getName();
  String blobName = blobData.getBlobName();
  Blob blob = blobData.getBlob();

  UnitOfWork.begin(storageFacet.txSupplier());
  try {
    if (assetExists(restoreData)) {
      if (shouldDeleteAsset(restoreData, blobData, path)) {
        log.debug(
            "Deleting asset as component is required but is not found, blob store: {}, repository: {}, path: {}, "
            + "blob name: {}, blob id: {}", blobStoreName, repoName, path, blobName, blob.getId());
        if (!isDryRun) {
          deleteAsset(blobData.getRepository(), path);
        }
      }
      else {
        log.debug(
            "Skipping as asset already exists, blob store: {}, repository: {}, path: {}, blob name: {}, blob id: {}",
            blobStoreName, repoName, path, blobName, blob.getId());
        return;
      }
    }

    if (!isDryRun) {
      doCreateAssetFromBlob(blobData, restoreData, blob);
    }

    log.info("{}Restored asset, blob store: {}, repository: {}, path: {}, blob name: {}, blob id: {}",
        logPrefix, blobStoreName, repoName, path, blobName, blob.getId());
  }
  catch (Exception e) {
    log.error("Error while restoring asset: blob store: {}, repository: {}, path: {}, blob name: {}, blob id: {}",
        blobStoreName, repoName, path, blobName, blob.getId(), e);
  }
  finally {
    UnitOfWork.end();
  }
}
 
Example 20
Source File: CreateIndexServiceImplTest.java    From nexus-repository-helm with Eclipse Public License 1.0 4 votes vote down vote up
@Before
public void setUp() throws Exception {
  initializeSystemUnderTest();
  setupMocks();
  UnitOfWork.begin(() -> storageTx);
}