org.sonatype.nexus.common.stateguard.Guarded Java Examples

The following examples show how to use org.sonatype.nexus.common.stateguard.Guarded. 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: S3BlobStore.java    From nexus-blobstore-s3 with Eclipse Public License 1.0 6 votes vote down vote up
@Override
@Guarded(by = STARTED)
public Blob create(final InputStream blobData, final Map<String, String> headers) {
  checkNotNull(blobData);

  return create(headers, destination -> {
      try (InputStream data = blobData) {
        MetricsInputStream input = new MetricsInputStream(data);
        TransferManager transferManager = new TransferManager(s3);
        transferManager.upload(getConfiguredBucket(), destination, input, new ObjectMetadata())
            .waitForCompletion();
        return input.getMetrics();
      } catch (InterruptedException e) {
        throw new BlobStoreException("error uploading blob", e, null);
      }
    });
}
 
Example #2
Source File: StorageTxImpl.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
@Guarded(by = ACTIVE)
public AssetBlob createBlob(final String blobName,
                            final Supplier<InputStream> streamSupplier,
                            final Iterable<HashAlgorithm> hashAlgorithms,
                            @Nullable final Map<String, String> headers,
                            @Nullable final String declaredContentType,
                            final boolean skipContentVerification) throws IOException
{
  checkNotNull(blobName);
  checkNotNull(streamSupplier);
  checkNotNull(hashAlgorithms);

  if (!writePolicy.checkCreateAllowed()) {
    throw new IllegalOperationException("Repository is read only: " + repositoryName);
  }

  Map<String, String> storageHeadersMap = buildStorageHeaders(blobName, streamSupplier, headers, declaredContentType,
      skipContentVerification);
  return blobTx.create(
      streamSupplier.get(),
      storageHeadersMap,
      hashAlgorithms,
      storageHeadersMap.get(BlobStore.CONTENT_TYPE_HEADER)
  );
}
 
Example #3
Source File: RepositoryImpl.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
@Guarded(by = STOPPED)
public void update(final Configuration configuration) throws Exception {
  checkNotNull(configuration);

  // Ensure configuration sanity
  validate(configuration);
  this.configuration = configuration;

  MultipleFailures failures = new MultipleFailures();
  for (Facet facet : facets) {
    try {
      log.debug("Updating facet: {}", facet);
      facet.update();
    }
    catch (Throwable t) {
      log.error("Failed to update facet: {}", facet, t);
      failures.add(t);
    }
  }
  failures.maybePropagate("Failed to update facets");
}
 
Example #4
Source File: BlobStoreManagerImpl.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
@Guarded(by = STARTED)
public void forceDelete(final String name) throws Exception {
  checkNotNull(name);
  freezeService.checkWritable("Unable to delete a BlobStore while database is frozen.");

  BlobStore blobStore = blobStore(name);
  log.debug("Deleting BlobStore: {}", name);
  blobStore.shutdown();
  blobStore.remove();
  untrack(name);
  if (!EventHelper.isReplicating()) {
    store.delete(blobStore.getBlobStoreConfiguration());
  }
  eventManager.post(new BlobStoreDeletedEvent(blobStore));
}
 
Example #5
Source File: OrientBrowseNodeStoreImpl.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
@Guarded(by = STARTED)
public void deleteByRepository(final String repositoryName) {
  log.debug("Deleting all browse nodes for repository {}", repositoryName);

  ProgressLogIntervalHelper progressLogger = new ProgressLogIntervalHelper(log, 60);

  int deletedCount;
  do {
    deletedCount = inTxRetry(databaseInstance).call(
        db -> entityAdapter.deleteByRepository(db, repositoryName, deletePageSize));

    progressLogger.info("Deleted {} browse nodes for repository {} in {}",
        deletedCount, repositoryName, progressLogger.getElapsed());
  }
  while (deletedCount == deletePageSize);

  progressLogger.flush();

  log.debug("All browse nodes deleted for repository {} in {}", repositoryName, progressLogger.getElapsed());
}
 
Example #6
Source File: ComponentStoreImpl.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
@Guarded(by = STARTED)
public <T> List<Entry<T, EntityId>> getNextPage(final OIndexCursor cursor, final int limit) {
  List<Entry<T, EntityId>> page = new ArrayList<>(limit);

  // For reasons unknown Orient needs the connection despite the code not using it
  try (ODatabaseDocumentTx db = databaseInstance.get().acquire()) {
    cursor.setPrefetchSize(limit);
    while (page.size() < limit) {
      Entry<Object, OIdentifiable> entry = cursor.nextEntry();
      if (entry == null) {
        break;
      }

      @SuppressWarnings("unchecked")
      T key = (T) entry.getKey();
      EntityId value = new AttachedEntityId(entityAdapter, entry.getValue().getIdentity());
      page.add(new SimpleEntry<>(key, value));
    }
  }

  return page;
}
 
Example #7
Source File: StorageFacetManagerImpl.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
@Guarded(by = STARTED)
public void enqueueDeletion(final Repository repository, final BlobStore blobStore, final Bucket bucket)
{
  checkNotNull(repository);
  checkNotNull(blobStore);
  checkNotNull(bucket);

  // The bucket associated with repository needs a new "repository name" created for it in order to avoid clashes.
  // Consider what happens if the bucket is still being deleted and someone tries to reuse that repository name.
  String generatedRepositoryName = repository.getName() + '$' + UUID.randomUUID();
  bucket.setRepositoryName(generatedRepositoryName);
  bucket.attributes().set(P_PENDING_DELETION, true);

  updateBucket(bucket);
}
 
Example #8
Source File: DataStoreManagerImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
@Guarded(by = STARTED)
public Optional<DataStore<?>> get(final String storeName) {
  checkNotNull(storeName);

  return ofNullable(dataStores.get(lower(storeName)));
}
 
Example #9
Source File: NegativeCacheFacetImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
@Guarded(by = STARTED)
public void invalidate(final NegativeCacheKey key) {
  checkNotNull(key);
  if (cache != null && cache.remove(key)) {
    log.debug("Removing {} from negative-cache of {}", key, getRepository());
  }
}
 
Example #10
Source File: DatabaseFreezeServiceImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
@Guarded(by = STARTED)
public synchronized boolean releaseUserInitiatedIfPresent() {
  Optional<FreezeRequest> request = getState().stream()
      .filter(it -> InitiatorType.USER_INITIATED.equals(it.getInitiatorType()))
      .findAny();
  if (request.isPresent()) {
    return releaseRequest(request.get());
  }
  return false;
}
 
Example #11
Source File: RepositoryImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
@Guarded(by = NEW)
public void attach(final Facet facet) throws Exception {
  checkNotNull(facet);
  log.debug("Attaching facet: {}", facet);
  facet.attach(this);
  facets.add(facet);
}
 
Example #12
Source File: BlobStoreMetricsStoreSupport.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Guarded(by = STARTED)
public BlobStoreMetrics getMetrics() {
  try {
    return getCombinedMetrics(backingFiles());
  }
  catch (BlobStoreMetricsNotAvailableException e) {
    log.error("Blob store metrics cannot be accessed", e);
    return UnavailableBlobStoreMetrics.getInstance();
  }
}
 
Example #13
Source File: StorageTxImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
@Guarded(by = ACTIVE)
public AssetBlob setBlob(final Asset asset,
                         final String blobName,
                         final Path sourceFile,
                         final Map<HashAlgorithm, HashCode> hashes,
                         @Nullable final Map<String, String> headers,
                         final String declaredContentType,
                         final long size) throws IOException
{
  checkNotNull(asset);
  checkArgument(!Strings2.isBlank(declaredContentType), "no declaredContentType provided");

  // Enforce write policy ahead, as we have asset here
  BlobRef oldBlobRef = asset.blobRef();
  if (oldBlobRef != null) {
    if (!writePolicySelector.select(asset, writePolicy).checkUpdateAllowed()) {
      throw new IllegalOperationException( "Repository does not allow updating assets: " + repositoryName);
    }
  }
  final AssetBlob assetBlob = createBlob(
      blobName,
      sourceFile,
      hashes,
      headers,
      declaredContentType,
      size
  );
  attachBlob(asset, assetBlob);
  return assetBlob;
}
 
Example #14
Source File: BlobStoreGroup.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
@Guarded(by = STARTED)
public BlobStoreMetrics getMetrics() {
  Iterable<BlobStoreMetrics> membersMetrics = (Iterable<BlobStoreMetrics>) members.get().stream()
    .map((BlobStore member) -> member.getMetrics())
    ::iterator;
  return new BlobStoreGroupMetrics(membersMetrics);
}
 
Example #15
Source File: PurgeUnusedFacetImpl.java    From nexus-public with Eclipse Public License 1.0 5 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());
  ContentFacetSupport contentFacetSupport = (ContentFacetSupport) getRepository().facet(ContentFacet.class);

  deleteComponentsOlderThan(numberOfDays, contentFacetSupport);
  deleteAssetsOlderThan(numberOfDays, contentFacetSupport);
}
 
Example #16
Source File: QuartzSchedulerSPI.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Used by {@link QuartzTaskFuture#cancel(boolean)}.
 */
@Guarded(by = STARTED)
public boolean cancelJob(final JobKey jobKey) {
  checkNotNull(jobKey);

  try (TcclBlock tccl = TcclBlock.begin(this)) {
    return scheduler.interrupt(jobKey);
  }
  catch (UnableToInterruptJobException e) {
    log.debug("Unable to interrupt job with key: {}", jobKey, e);
  }
  return false;
}
 
Example #17
Source File: NegativeCacheFacetImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
@Guarded(by = STARTED)
public void invalidate() {
  if (cache != null) {
    log.debug("Removing all from negative-cache of {}", getRepository());
    cache.removeAll();
  }
}
 
Example #18
Source File: BlobStoreManagerImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
@Guarded(by = STARTED)
@Nullable
public BlobStore get(final String name) {
  checkNotNull(name);

  return stores.get(name);
}
 
Example #19
Source File: StorageTxImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
@Guarded(by = ACTIVE)
public boolean assetExists(final String name,
                           final Repository repository)
{
  checkNotNull(name);
  checkNotNull(repository);

  return assetEntityAdapter.exists(db, name, bucketOf(repository.getName()));
}
 
Example #20
Source File: DatastoreCselToSql.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
@Guarded(by = STARTED)
public void transformCselToSql(final ASTJexlScript script, final SelectorSqlBuilder builder) {
  final DatastoreSqlTransformer transformer = dataStoreId
      .map(transformerMap::get)
      .orElseThrow(() -> new IllegalStateException("Cannot find sql transformer for " + dataStoreId));

  script.childrenAccept(transformer, builder);
}
 
Example #21
Source File: PeriodicJobServiceImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
@Guarded(by = STARTED)
public PeriodicJob schedule(final Runnable runnable, final int repeatPeriodSeconds) {
  ScheduledFuture<?> scheduledFuture = executor.scheduleAtFixedRate(
      wrap(runnable),
      repeatPeriodSeconds,
      repeatPeriodSeconds,
      TimeUnit.SECONDS);

  return () -> scheduledFuture.cancel(false);
}
 
Example #22
Source File: OrientNpmGroupFacet.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Subscribe
@Guarded(by = STARTED)
@AllowConcurrentEvents
public void on(final AssetUpdatedEvent updated) {
  if (matchingEvent(updated) && hasBlobBeenUpdated(updated)) {
    invalidatePackageRoot(updated);
  }
}
 
Example #23
Source File: OrientNpmGroupFacet.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Subscribe
@Guarded(by = STARTED)
@AllowConcurrentEvents
public void on(final AssetDeletedEvent deleted) {
  if (matchingEvent(deleted)) {
    invalidatePackageRoot(deleted);
  }
}
 
Example #24
Source File: OrientApiKeyStore.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
@Guarded(by = STARTED)
public void persistApiKey(final String domain, final PrincipalCollection principals, final char[] apiKey) {
  checkNotNull(domain);
  checkNotNull(principals);
  checkNotNull(apiKey);
  final OrientApiKey entity = entityAdapter.newEntity();
  entity.setDomain(domain);
  entity.setApiKey(apiKey);
  entity.setPrincipals(principals);
  inTxRetry(databaseInstance).run(db -> entityAdapter.addEntity(db, entity));
}
 
Example #25
Source File: ModelVersionStore.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Guarded(by = STARTED)
public synchronized Map<String, String> load() {
  Map<String, String> modelVersions = new HashMap<>();
  load(modelVersions, upgradeManager.getLocalModels(), localModelVersions::getProperty);
  load(modelVersions, upgradeManager.getClusteredModels(), clusteredModelVersions::get);
  return modelVersions;
}
 
Example #26
Source File: OrientConfigurationStoreImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
@Guarded(by = STARTED)
public void create(final Configuration configuration) {
  checkNotNull(configuration);

  inTxRetry(databaseInstance).run(db -> entityAdapter.addEntity(db, cast(configuration)));
}
 
Example #27
Source File: OrientBlobStoreConfigurationStore.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
@Guarded(by = STARTED)
public void delete(final BlobStoreConfiguration configuration) {
  checkBlobStoreConfiguration(configuration);

  inTxRetry(databaseInstance).run(db -> entityAdapter.deleteEntity(db, (OrientBlobStoreConfiguration) configuration));
}
 
Example #28
Source File: OrientRoutingRuleStore.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
@Guarded(by = STARTED)
public void update(final RoutingRule rule) {
  checkNotNull(rule);
  validate(rule);

  persist(entityAdapter::editEntity, rule);
}
 
Example #29
Source File: GoogleCloudBlobStore.java    From nexus-blobstore-google-cloud with Eclipse Public License 1.0 5 votes vote down vote up
@Override
@Guarded(by = STARTED)
public Blob copy(final BlobId blobId, final Map<String, String> headers) {
  GoogleCloudStorageBlob sourceBlob = (GoogleCloudStorageBlob) checkNotNull(get(blobId));

  return createInternal(headers, destination -> {
    sourceBlob.getBlob().copyTo(getConfiguredBucketName(), destination);
    BlobMetrics metrics = sourceBlob.getMetrics();
    return new StreamMetrics(metrics.getContentSize(), metrics.getSha1Hash());
  }, null);
}
 
Example #30
Source File: AssetStoreImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
@Guarded(by = STARTED)
public Asset save(Asset asset) {
  if (hasMetadata(asset)) {
    inTxRetry(databaseInstance).run(db -> entityAdapter.editEntity(db, asset));
    return asset;
  }
  else {
    return inTxRetry(databaseInstance).call(db -> entityAdapter.readEntity(entityAdapter.addEntity(db, asset)));
  }
}