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

The following examples show how to use org.sonatype.nexus.transaction.UnitOfWork#beginBatch() . 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: MetadataUpdaterTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void updateWithExisting() throws IOException {
  when(mavenFacet.get(mavenPath)).thenReturn(
      new Content(
          new StringPayload("<?xml version=\"1.0\" encoding=\"UTF-8\"?><metadata><groupId>group</groupId></metadata>",
              "text/xml")), content);
  UnitOfWork.beginBatch(tx);
  try {
    testSubject.update(mavenPath, Maven2Metadata.newGroupLevel(DateTime.now(), new ArrayList<Plugin>()));
  }
  finally {
    UnitOfWork.end();
  }
  verify(tx, times(1)).commit();
  verify(mavenFacet, times(1)).get(eq(mavenPath));
  verify(mavenFacet, times(0)).put(eq(mavenPath), any(Payload.class));
}
 
Example 2
Source File: PurgeUnusedSnapshotsFacetImplTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  clusterPosition = 1;
  purgeUnusedSnapshotsFacet =
      new PurgeUnusedSnapshotsFacetImpl(componentEntityAdapter, groupType, hostedType,
          FIND_USED_LIMIT);
  purgeUnusedSnapshotsFacet.attach(repository);

  when(repository.getName()).thenReturn("test-repo");
  when(repository.facet(MavenFacet.class)).thenReturn(mavenFacet);
  when(storageTx.findBucket(repository)).thenReturn(bucket);
  when(storageTx.countComponents(any(Query.class), any())).thenReturn(NUMBER_OF_COMPONENTS);
  when(storageTx.getDb()).thenReturn(oDatabaseDocumentTx);
  METADATA_PATHS.forEach(
      p -> when(storageTx.findAssetWithProperty(P_NAME, maven2MavenPathParser.parsePath(p).getPath(), bucket))
          .thenReturn(createMetadataAsset(p, INVALIDATED)));

  UnitOfWork.beginBatch(storageTx);

  mockBucket();
}
 
Example 3
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 4
Source File: RawContentFacetImplTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Before
public void setup() throws Exception {
  when(repository.getFormat()).thenReturn(format);

  when(component.group(any(String.class))).thenReturn(component);
  when(component.name(any(String.class))).thenReturn(component);

  when(asset.name(any(String.class))).thenReturn(asset);
  when(asset.attributes()).thenReturn(new NestedAttributesMap(P_ATTRIBUTES, newHashMap()));

  when(tx.getDb()).thenReturn(db);
  when(tx.findBucket(repository)).thenReturn(bucket);

  underTest = new RawContentFacetImpl(assetEntityAdapter);
  underTest.attach(repository);

  UnitOfWork.beginBatch(tx);
}
 
Example 5
Source File: NpmPackageRootMetadataUtilsTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Before
public void setUp() {
  // reset for every request
  BaseUrlHolder.unset();
    
  when(packageRootAsset.name()).thenReturn("@foo/bar");
  when(packageRootAsset.requireBlobRef()).thenReturn(packageRootBlobRef);
  when(packageRootAsset.formatAttributes()).thenReturn(new NestedAttributesMap("metadata", new HashMap<>()));
  when(packageRootAsset.getEntityMetadata())
      .thenReturn(new DetachedEntityMetadata(new DetachedEntityId("foo"), new DetachedEntityVersion("a")));

  when(storageTx.requireBlob(packageRootBlobRef)).thenReturn(packageRootBlob);
  when(storageTx.findAssetWithProperty(eq(P_NAME), eq("@foo/bar"), any(Bucket.class))).thenReturn(packageRootAsset);
  when(packageRootBlob.getInputStream())
      .thenReturn(new ByteArrayInputStream(("{\"" + DIST_TAGS + "\": {\"latest\":\"1.5.3\"}}").getBytes()));

  UnitOfWork.beginBatch(storageTx);
}
 
Example 6
Source File: PurgeUnusedFacetImpl.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
@Guarded(by = STARTED)
public void purgeUnused(final int numberOfDays) {
  checkArgument(numberOfDays > 0, "Number of days must be greater then zero");
  log.info("Purging unused components from repository {}", getRepository().getName());

  Date olderThan = DateTime.now().minusDays(numberOfDays).withTimeAtStartOfDay().toDate();

  UnitOfWork.beginBatch(facet(StorageFacet.class).txSupplier());
  try {
    deleteUnusedComponents(olderThan);
    deleteUnusedAssets(olderThan);
  }
  finally {
    UnitOfWork.end();
  }
}
 
Example 7
Source File: MetadataUpdaterTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void replaceWithUnchangedExisting() throws IOException {
  when(mavenFacet.get(mavenPath)).thenReturn(
      new Content(
          new StringPayload("<?xml version=\"1.0\" encoding=\"UTF-8\"?><metadata></metadata>",
              "text/xml")), content);
  UnitOfWork.beginBatch(tx);
  try {
    testSubject.replace(mavenPath, Maven2Metadata.newGroupLevel(DateTime.now(), new ArrayList<Plugin>()));
  }
  finally {
    UnitOfWork.end();
  }
  verify(tx, times(1)).commit();
  verify(mavenFacet, times(1)).get(eq(mavenPath));
  verify(mavenFacet, times(0)).put(eq(mavenPath), any(Payload.class));
}
 
Example 8
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 9
Source File: LastDownloadedHandlerTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
  configureHappyPath();

  underTest = new LastDownloadedHandler(assetManager);

  UnitOfWork.beginBatch(tx);
}
 
Example 10
Source File: MetadataUpdaterTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void updateWithExistingCorrupted() throws IOException {
  when(mavenFacet.get(mavenPath)).thenReturn(
      new Content(new StringPayload("ThisIsNotAnXml", "text/xml")), content);
  UnitOfWork.beginBatch(tx);
  try {
    testSubject.update(mavenPath, Maven2Metadata.newGroupLevel(DateTime.now(), new ArrayList<Plugin>()));
  }
  finally {
    UnitOfWork.end();
  }
  verify(tx, times(1)).commit();
  verify(mavenFacet, times(2)).get(eq(mavenPath));
  verify(mavenFacet, times(1)).put(eq(mavenPath), any(Payload.class));
}
 
Example 11
Source File: OrientPyPiRepairIndexComponentTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  underTest = new OrientPyPiRepairIndexComponent(repositoryManager, assetEntityAdapter, type, format);

  when(asset.formatAttributes()).thenReturn(attributes);

  UnitOfWork.beginBatch(tx);
}
 
Example 12
Source File: OrientPyPiFacetImplTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
  underTest = new OrientPyPiFacetImpl(assetEntityAdapter);
  underTest.attach(repository);

  UnitOfWork.beginBatch(tx);
}
 
Example 13
Source File: ComposerHostedFacetImplTest.java    From nexus-repository-composer with Eclipse Public License 1.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  when(repository.facet(ComposerContentFacet.class)).thenReturn(composerContentFacet);
  when(tx.findBucket(repository)).thenReturn(bucket);

  underTest = spy(new ComposerHostedFacetImpl(composerJsonProcessor));
  underTest.attach(repository);

  UnitOfWork.beginBatch(tx);
}
 
Example 14
Source File: MetadataUpdaterTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void replaceWithExistingCorrupted() throws IOException {
  when(mavenFacet.get(mavenPath)).thenReturn(
      new Content(new StringPayload("ThisIsNotAnXml", "text/xml")), content);
  UnitOfWork.beginBatch(tx);
  try {
    testSubject.replace(mavenPath, Maven2Metadata.newGroupLevel(DateTime.now(), new ArrayList<Plugin>()));
  }
  finally {
    UnitOfWork.end();
  }
  verify(tx, times(1)).commit();
  verify(mavenFacet, times(2)).get(eq(mavenPath));
  verify(mavenFacet, times(1)).put(eq(mavenPath), any(Payload.class));
}
 
Example 15
Source File: PurgeUnusedSnapshotsFacetImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Purges snapshots from the given repository, returning a set of the affected groups for metadata rebuilding.
 */
private void purgeSnapshotsFromRepository(final int numberOfDays) {
  LocalDate olderThan = LocalDate.now().minusDays(numberOfDays);
  UnitOfWork.beginBatch(facet(StorageFacet.class).txSupplier());
  try {
    deleteUnusedSnapshotComponents(olderThan);
  }
  finally {
    UnitOfWork.end();
  }
}
 
Example 16
Source File: MetadataUpdaterTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void updateWithNonExisting() throws IOException {
  when(mavenFacet.get(mavenPath)).thenReturn(null, content);
  UnitOfWork.beginBatch(tx);
  try {
    testSubject.update(mavenPath, Maven2Metadata.newGroupLevel(DateTime.now(), new ArrayList<Plugin>()));
  }
  finally {
    UnitOfWork.end();
  }
  verify(tx, times(1)).commit();
  verify(mavenFacet, times(2)).get(eq(mavenPath));
  verify(mavenFacet, times(1)).put(eq(mavenPath), any(Payload.class));
}
 
Example 17
Source File: OrientPyPiHostedFacetImplTest.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
@Before
public void setUp() throws Exception {
  underTest = new OrientPyPiHostedFacetImpl(templateHelper);

  UnitOfWork.beginBatch(tx);
}
 
Example 18
Source File: OrientMetadataRebuilder.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Delete metadata for the given GAbV and rebuild metadata for the GA. If Group level metadata is present, rebuild
 * at that level to account for plugin deletion.
 * 
 * @param repository  The repository whose metadata needs rebuild (Maven2 format, Hosted type only).
 * @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 paths of deleted metadata files
 */
@Override public Set<String> deleteAndRebuild(final Repository repository, final String groupId,
                             final String artifactId, final String baseVersion)
{
  checkNotNull(repository);
  checkNotNull(groupId);
  checkNotNull(artifactId);
  checkNotNull(baseVersion);

  Set<String> deletedPaths = new HashSet<>();
  final StorageTx tx = repository.facet(StorageFacet.class).txSupplier().get();
  UnitOfWork.beginBatch(tx);
  boolean groupChange = false;
  try {
    // Delete the specific GAV
    MavenPath gavMetadataPath = metadataPath(groupId, artifactId, baseVersion);
    OrientMetadataUtils.delete(repository, gavMetadataPath);
    deletedPaths.addAll(MavenFacetUtils.getPathWithHashes(gavMetadataPath));
    // Delete the GA; will be rebuilt as necessary but may hold the last GAV in which case rebuild would ignore it
    MavenPath gaMetadataPath = metadataPath(groupId, artifactId, null);
    OrientMetadataUtils.delete(repository, gaMetadataPath);
    deletedPaths.addAll(MavenFacetUtils.getPathWithHashes(gaMetadataPath));

    // Check explicitly for whether or not we have Group level metadata that might need rebuilding, since this
    // is potentially the most expensive possible path to take.
    MavenPath groupPath = metadataPath(groupId, null, null);
    if (OrientMetadataUtils.exists(repository, groupPath)) {
      OrientMetadataUtils.delete(repository, groupPath);
      deletedPaths.addAll(MavenFacetUtils.getPathWithHashes(groupPath));
      // we have metadata for plugins at the Group level so we should build that as well
      groupChange = true;
    }
  }
  catch (IOException e) {
    throw new RuntimeException(e);
  }
  finally {
    UnitOfWork.end();
  }

  boolean rebuild;
  if (groupChange) {
    rebuild = rebuild(repository, true, false, groupId, null, null);
  }
  else {
    rebuild = rebuild(repository, true, false, groupId, artifactId, null);
  }

  if (rebuild) {
    return emptySet();
  } else {
    return deletedPaths;
  }
}
 
Example 19
Source File: RemoveSnapshotsFacetImpl.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
@Override
@Guarded(by = STARTED)
public void removeSnapshots(RemoveSnapshotsConfig config)
{
  Repository repository = getRepository();
  String repositoryName = repository.getName();
  log.info("Beginning snapshot removal on repository '{}' with configuration: {}", repositoryName, config);
  UnitOfWork.beginBatch(facet(StorageFacet.class).txSupplier());
  Set<GAV> metadataUpdateRequired = new HashSet<>();
  try {
    if (groupType.equals(repository.getType())) {
      processGroup(repository.facet(MavenGroupFacet.class), config);
    }
    else {
      metadataUpdateRequired.addAll(processRepository(repository, config));
    }
  }
  finally {
    UnitOfWork.end();
  }

  //only update metadata for non-proxy repos
  if (!repository.optionalFacet(ProxyFacet.class).isPresent()) {
    log.info("Updating metadata on repository '{}'", repositoryName);
    ProgressLogIntervalHelper intervalLogger = new ProgressLogIntervalHelper(log, 60);

    int processed = 0;
    for (GAV gav : metadataUpdateRequired) {
      Optional<MavenHostedFacet> mavenHostedFacet = repository.optionalFacet(MavenHostedFacet.class);
      if (mavenHostedFacet.isPresent()) {
        try {
          mavenHostedFacet.get().deleteMetadata(gav.group, gav.name, gav.baseVersion);
          intervalLogger
              .info("Elapsed time: {}, updated metadata for {} GAVs", intervalLogger.getElapsed(), ++processed);
        }
        catch (Exception e) {
          log.warn("Unable to delete/rebuild {} {} {}", gav.group, gav.name, gav.baseVersion,
              log.isDebugEnabled() ? e : null);
        }
      }
    }

    intervalLogger.flush();
  }
  else {
    log.info("Skipping metadata updates on proxy repository '{}'", repositoryName);
  }

  log.info("Completed snapshot removal on repository '{}'", repositoryName);
}
 
Example 20
Source File: ComposerContentFacetImplTest.java    From nexus-repository-composer with Eclipse Public License 1.0 4 votes vote down vote up
@Before
public void setUp() throws Exception {
  underTest = new ComposerContentFacetImpl(COMPOSER_FORMAT, composerFormatAttributesExtractor);
  underTest.attach(repository);

  when(tx.findBucket(repository)).thenReturn(bucket);
  when(tx.requireBlob(blobRef)).thenReturn(blob);
  when(tx.createAsset(bucket, COMPOSER_FORMAT)).thenReturn(asset);
  when(tx.createAsset(bucket, component)).thenReturn(asset);
  when(tx.findComponents(any(Query.class), eq(singletonList(repository)))).thenReturn(emptyList());
  when(tx.createComponent(bucket, COMPOSER_FORMAT)).thenReturn(component);

  when(repository.facet(StorageFacet.class)).thenReturn(storageFacet);

  when(asset.attributes()).thenReturn(assetAttributes);
  when(asset.formatAttributes()).thenReturn(formatAttributes);
  when(asset.requireBlobRef()).thenReturn(blobRef);
  when(asset.requireContentType()).thenReturn(CONTENT_TYPE);
  when(asset.getChecksums(HASH_ALGORITHMS)).thenReturn(CHECKSUMS);

  when(assetAttributes.child("cache")).thenReturn(cacheAttributes);
  when(assetAttributes.child("composer")).thenReturn(formatAttributes);
  when(assetAttributes.child("content")).thenReturn(contentAttributes);

  when(assetBlob.getBlob()).thenReturn(blob);
  when(assetBlob.getBlobRef()).thenReturn(blobRef);

  when(contentAttributes.get("last_modified", Date.class)).thenReturn(LAST_MODIFIED);
  when(contentAttributes.get("etag")).thenReturn(ETAG);

  when(cacheAttributes.get("last_verified", Date.class)).thenReturn(LAST_VERIFIED);

  when(storageFacet.createTempBlob(upload, HASH_ALGORITHMS)).thenReturn(tempBlob);

  when(blob.getInputStream()).thenReturn(blobInputStream);

  when(upload.getContentType()).thenReturn(CONTENT_TYPE);

  when(component.group(any(String.class))).thenReturn(component);
  when(component.name(any(String.class))).thenReturn(component);
  when(component.version(any(String.class))).thenReturn(component);

  doThrow(new RuntimeException("Test")).when(composerFormatAttributesExtractor)
      .extractFromZip(tempBlob, formatAttributes);

  UnitOfWork.beginBatch(tx);
}