Search in sources :

Example 6 with Request

use of com.b2international.snowowl.core.events.Request in project snow-owl by b2ihealthcare.

the class CommitInfoRequestTest method searchCommitInfoByTimestamp.

@Test
public void searchCommitInfoByTimestamp() {
    final String oid = UUID.randomUUID().toString();
    final String shortName = UUID.randomUUID().toString();
    final String comment = "Code system for commit info 5";
    createCodeSystem(shortName, oid, comment);
    final CommitInfo commitInfo = getCommitInfoByComment(comment);
    Request<RepositoryContext, CommitInfos> req = RepositoryRequests.commitInfos().prepareSearchCommitInfo().filterByTimestamp(commitInfo.getTimestamp()).build();
    final CommitInfos commitInfos = new ResourceRepositoryRequestBuilder<CommitInfos>() {

        @Override
        public Request<RepositoryContext, CommitInfos> build() {
            return req;
        }
    }.buildAsync().execute(bus).getSync();
    assertTrue(commitInfos.getTotal() == 1);
    assertEquals(commitInfo.getTimestamp(), Iterables.getOnlyElement(commitInfos.getItems()).getTimestamp());
}
Also used : CommitInfos(com.b2international.snowowl.core.commit.CommitInfos) RepositoryContext(com.b2international.snowowl.core.domain.RepositoryContext) Request(com.b2international.snowowl.core.events.Request) AuthorizedRequest(com.b2international.snowowl.core.authorization.AuthorizedRequest) CommitInfo(com.b2international.snowowl.core.commit.CommitInfo) Test(org.junit.Test)

Example 7 with Request

use of com.b2international.snowowl.core.events.Request in project snow-owl by b2ihealthcare.

the class CommitInfoRequestTest method searchCommitInfoByUserId.

@Test
public void searchCommitInfoByUserId() {
    final String oid = UUID.randomUUID().toString();
    final String shortName = UUID.randomUUID().toString();
    final String comment = "Code system for commit info 3";
    final String userId = "commitInfo";
    createCodeSystem(oid, shortName, comment, userId);
    Request<RepositoryContext, CommitInfos> req = RepositoryRequests.commitInfos().prepareSearchCommitInfo().filterByAuthor(userId).build();
    final CommitInfos commitInfos = new ResourceRepositoryRequestBuilder<CommitInfos>() {

        @Override
        public Request<RepositoryContext, CommitInfos> build() {
            return req;
        }
    }.buildAsync().execute(bus).getSync();
    assertEquals(commitInfos.getTotal(), 1);
    final CommitInfo commitInfo = Iterables.getOnlyElement(commitInfos);
    assertEquals(userId, commitInfo.getAuthor());
}
Also used : CommitInfos(com.b2international.snowowl.core.commit.CommitInfos) RepositoryContext(com.b2international.snowowl.core.domain.RepositoryContext) Request(com.b2international.snowowl.core.events.Request) AuthorizedRequest(com.b2international.snowowl.core.authorization.AuthorizedRequest) CommitInfo(com.b2international.snowowl.core.commit.CommitInfo) Test(org.junit.Test)

Example 8 with Request

use of com.b2international.snowowl.core.events.Request in project snow-owl by b2ihealthcare.

the class IdRequest method execute.

@Override
public R execute(final C context) {
    final IdActionRecorder recorder = new IdActionRecorder(context);
    try {
        final Multimap<ComponentCategory, SnomedComponentCreateRequest> componentCreateRequests = getComponentCreateRequests(next());
        if (!componentCreateRequests.isEmpty()) {
            try {
                for (final ComponentCategory category : componentCreateRequests.keySet()) {
                    final Class<? extends SnomedDocument> documentClass = getDocumentClass(category);
                    final Collection<SnomedComponentCreateRequest> categoryRequests = componentCreateRequests.get(category);
                    final Set<String> coreComponentIds = FluentIterable.from(categoryRequests).filter(SnomedCoreComponentCreateRequest.class).filter(request -> request.getIdGenerationStrategy() instanceof ConstantIdStrategy).transform(request -> ((ConstantIdStrategy) request.getIdGenerationStrategy()).getId()).toSet();
                    final Set<String> refsetMemberIds = FluentIterable.from(categoryRequests).filter(SnomedRefSetMemberCreateRequest.class).transform(request -> request.getId()).toSet();
                    final Set<String> userRequestedIds = Sets.newHashSet(Iterables.concat(coreComponentIds, refsetMemberIds));
                    final Set<String> existingIds = getExistingIds(context, userRequestedIds, documentClass);
                    if (!existingIds.isEmpty()) {
                        // TODO: Report all existing identifiers
                        throw new AlreadyExistsException(category.getDisplayName(), Iterables.getFirst(existingIds, null));
                    } else {
                        if (!coreComponentIds.isEmpty()) {
                            recorder.register(coreComponentIds);
                        }
                    }
                    final Multimap<String, BaseSnomedComponentCreateRequest> requestsByNamespace = HashMultimap.create();
                    // index requests where an explicit namespace identifier is specified (use it directly)
                    categoryRequests.stream().filter(BaseSnomedComponentCreateRequest.class::isInstance).map(BaseSnomedComponentCreateRequest.class::cast).filter(request -> request.getIdGenerationStrategy() instanceof NamespaceIdStrategy).forEach(request -> {
                        requestsByNamespace.put(getNamespaceKey(request), request);
                    });
                    // convert requests that define a namespaceConceptId by extracting the namespaceId from the namespaceConcept's FSN
                    final Multimap<String, BaseSnomedComponentCreateRequest> requestsByNamespaceConceptId = HashMultimap.create();
                    categoryRequests.stream().filter(BaseSnomedComponentCreateRequest.class::isInstance).map(BaseSnomedComponentCreateRequest.class::cast).filter(request -> request.getIdGenerationStrategy() instanceof NamespaceConceptIdStrategy).forEach(request -> {
                        requestsByNamespaceConceptId.put(request.getIdGenerationStrategy().getNamespace(), request);
                    });
                    if (!requestsByNamespaceConceptId.isEmpty()) {
                        final Map<String, String> namespacesByNamespaceConceptId = context.service(NamespaceIdProvider.class).extractNamespaceIds(context, requestsByNamespaceConceptId.keySet(), false);
                        for (String namespaceConceptId : Set.copyOf(requestsByNamespaceConceptId.keySet())) {
                            Collection<BaseSnomedComponentCreateRequest> requests = requestsByNamespaceConceptId.removeAll(namespaceConceptId);
                            if (!namespacesByNamespaceConceptId.containsKey(namespaceConceptId)) {
                                throw new BadRequestException("There is no namespace value associated with the '%s' namespaceConcept's FSN.", namespaceConceptId);
                            }
                            requestsByNamespace.putAll(namespacesByNamespaceConceptId.get(namespaceConceptId), requests);
                        }
                    }
                    for (final String namespace : requestsByNamespace.keySet()) {
                        final String convertedNamespace = SnomedIdentifiers.INT_NAMESPACE.equals(namespace) ? null : namespace;
                        final Collection<BaseSnomedComponentCreateRequest> namespaceRequests = requestsByNamespace.get(namespace);
                        final int count = namespaceRequests.size();
                        final Set<String> uniqueIds = getUniqueIds(context, recorder, category, documentClass, count, convertedNamespace);
                        final Iterator<String> idsToUse = Iterators.consumingIterator(uniqueIds.iterator());
                        for (final BaseSnomedComponentCreateRequest createRequest : namespaceRequests) {
                            createRequest.setIdGenerationStrategy(new ConstantIdStrategy(idsToUse.next()));
                        }
                        checkState(!idsToUse.hasNext(), "More SNOMED CT ids have been requested than used.");
                    }
                }
            } finally {
            // idGenerationSample.stop(registry.timer("idGenerationTime"));
            }
        }
        final R commitInfo = next(context);
        recorder.commit();
        return commitInfo;
    } catch (final Exception e) {
        recorder.rollback();
        throw e;
    }
}
Also used : Query(com.b2international.index.query.Query) AlreadyExistsException(com.b2international.commons.exceptions.AlreadyExistsException) RevisionSearcher(com.b2international.index.revision.RevisionSearcher) IdActionRecorder(com.b2international.snowowl.snomed.cis.action.IdActionRecorder) NamespaceIdStrategy(com.b2international.snowowl.snomed.core.domain.NamespaceIdStrategy) Map(java.util.Map) BulkRequest(com.b2international.snowowl.core.events.bulk.BulkRequest) com.b2international.snowowl.snomed.datastore.index.entry(com.b2international.snowowl.snomed.datastore.index.entry) Sets.newHashSet(com.google.common.collect.Sets.newHashSet) CompareUtils(com.b2international.commons.CompareUtils) com.google.common.collect(com.google.common.collect) BadRequestException(com.b2international.commons.exceptions.BadRequestException) Iterator(java.util.Iterator) SnowowlRuntimeException(com.b2international.snowowl.core.api.SnowowlRuntimeException) RevisionDocument(com.b2international.snowowl.core.repository.RevisionDocument) Collection(java.util.Collection) Request(com.b2international.snowowl.core.events.Request) Set(java.util.Set) IOException(java.io.IOException) Preconditions.checkState(com.google.common.base.Preconditions.checkState) ConstantIdStrategy(com.b2international.snowowl.snomed.core.domain.ConstantIdStrategy) TransactionalRequest(com.b2international.snowowl.core.request.TransactionalRequest) IdGenerationStrategy(com.b2international.snowowl.snomed.core.domain.IdGenerationStrategy) DelegatingRequest(com.b2international.snowowl.core.events.DelegatingRequest) SnomedIdentifiers(com.b2international.snowowl.snomed.cis.SnomedIdentifiers) NamespaceConceptIdStrategy(com.b2international.snowowl.snomed.core.domain.NamespaceConceptIdStrategy) BranchContext(com.b2international.snowowl.core.domain.BranchContext) NotImplementedException(com.b2international.commons.exceptions.NotImplementedException) ComponentCategory(com.b2international.snowowl.core.terminology.ComponentCategory) IdActionRecorder(com.b2international.snowowl.snomed.cis.action.IdActionRecorder) AlreadyExistsException(com.b2international.commons.exceptions.AlreadyExistsException) ComponentCategory(com.b2international.snowowl.core.terminology.ComponentCategory) AlreadyExistsException(com.b2international.commons.exceptions.AlreadyExistsException) BadRequestException(com.b2international.commons.exceptions.BadRequestException) SnowowlRuntimeException(com.b2international.snowowl.core.api.SnowowlRuntimeException) IOException(java.io.IOException) NotImplementedException(com.b2international.commons.exceptions.NotImplementedException) ConstantIdStrategy(com.b2international.snowowl.snomed.core.domain.ConstantIdStrategy) BadRequestException(com.b2international.commons.exceptions.BadRequestException) NamespaceIdStrategy(com.b2international.snowowl.snomed.core.domain.NamespaceIdStrategy) NamespaceConceptIdStrategy(com.b2international.snowowl.snomed.core.domain.NamespaceConceptIdStrategy)

Example 9 with Request

use of com.b2international.snowowl.core.events.Request in project snow-owl by b2ihealthcare.

the class SnomedBulkRequest method execute.

@Override
public R execute(TransactionContext context) {
    ImmutableList.Builder<SnomedComponentRequest<?>> requests = ImmutableList.builder();
    ImmutableList.Builder<DeleteRequest> deletions = ImmutableList.builder();
    collectNestedRequests(next(), requests, deletions);
    // Prefetch all component IDs mentioned in reference set member creation requests, abort if any of them can not be found
    final Set<String> requiredComponentIds = requests.build().stream().flatMap(request -> request.getRequiredComponentIds(context).stream()).filter(// just in case filter out invalid component IDs
    componentId -> SnomedComponent.getTypeSafe(componentId) != null || isMember(componentId)).collect(Collectors.toSet());
    final Multimap<Class<? extends SnomedDocument>, String> componentIdsByType = HashMultimap.create();
    for (String requiredComponentId : requiredComponentIds) {
        if (!Strings.isNullOrEmpty(requiredComponentId)) {
            componentIdsByType.put(this.getDocType(requiredComponentId), requiredComponentId);
        }
    }
    // collect all deleted IDs as well
    deletions.build().stream().map(DeleteRequest::getComponentId).forEach(componentId -> componentIdsByType.put(getDocType(componentId), componentId));
    try {
        for (final Entry<Class<? extends SnomedDocument>, Collection<String>> idsForType : componentIdsByType.asMap().entrySet()) {
            context.lookup(idsForType.getValue(), idsForType.getKey());
        }
    } catch (final ComponentNotFoundException e) {
        throw e.toBadRequestException();
    }
    // bind additional caches to the context
    TransactionContext newContext = context.inject().bind(SnomedOWLExpressionConverter.class, new SnomedOWLExpressionConverter(context)).build();
    return next(newContext);
}
Also used : BadRequestException(com.b2international.commons.exceptions.BadRequestException) SnomedConcept(com.b2international.snowowl.snomed.core.domain.SnomedConcept) Collection(java.util.Collection) Request(com.b2international.snowowl.core.events.Request) Set(java.util.Set) UUID(java.util.UUID) Multimap(com.google.common.collect.Multimap) Collectors(java.util.stream.Collectors) DeleteRequest(com.b2international.snowowl.core.request.DeleteRequest) SnomedRelationship(com.b2international.snowowl.snomed.core.domain.SnomedRelationship) SnomedDescription(com.b2international.snowowl.snomed.core.domain.SnomedDescription) Strings(com.google.common.base.Strings) TransactionContext(com.b2international.snowowl.core.domain.TransactionContext) HashMultimap(com.google.common.collect.HashMultimap) ImmutableList(com.google.common.collect.ImmutableList) Entry(java.util.Map.Entry) BulkRequest(com.b2international.snowowl.core.events.bulk.BulkRequest) com.b2international.snowowl.snomed.datastore.index.entry(com.b2international.snowowl.snomed.datastore.index.entry) DelegatingRequest(com.b2international.snowowl.core.events.DelegatingRequest) SnomedComponent(com.b2international.snowowl.snomed.core.domain.SnomedComponent) ComponentNotFoundException(com.b2international.snowowl.core.exceptions.ComponentNotFoundException) ImmutableList(com.google.common.collect.ImmutableList) ComponentNotFoundException(com.b2international.snowowl.core.exceptions.ComponentNotFoundException) TransactionContext(com.b2international.snowowl.core.domain.TransactionContext) Collection(java.util.Collection) DeleteRequest(com.b2international.snowowl.core.request.DeleteRequest)

Example 10 with Request

use of com.b2international.snowowl.core.events.Request in project snow-owl by b2ihealthcare.

the class SaveJobRequest method persistChanges.

private Boolean persistChanges(final BranchContext context, final IProgressMonitor monitor) {
    // Repeat the same checks as in ClassificationSaveRequest, now within the lock
    final ClassificationTask classification = ClassificationRequests.prepareGetClassification(classificationId).build().execute(context);
    final String branchPath = classification.getBranch();
    final Branch branch = RepositoryRequests.branching().prepareGet(branchPath).build().execute(context);
    if (!ClassificationSaveRequest.SAVEABLE_STATUSES.contains(classification.getStatus())) {
        throw new BadRequestException("Classification '%s' is not in the expected state to start saving changes.", classificationId);
    }
    if (classification.getTimestamp() < branch.headTimestamp()) {
        throw new BadRequestException("Classification '%s' on branch '%s' is stale (classification timestamp: %s, head timestamp: %s).", classificationId, branchPath, classification.getTimestamp(), branch.headTimestamp());
    }
    final ClassificationTracker classificationTracker = context.service(ClassificationTracker.class);
    // Signal the state change
    classificationTracker.classificationSaving(classificationId);
    final SubMonitor subMonitor = SubMonitor.convert(monitor, "Persisting changes", 6);
    final BulkRequestBuilder<TransactionContext> bulkRequestBuilder = BulkRequest.create();
    applyChanges(subMonitor, context, bulkRequestBuilder);
    long resultTimeStamp = Commit.NO_COMMIT_TIMESTAMP;
    for (List<Request<TransactionContext, ?>> partition : Iterables.partition(bulkRequestBuilder.build().getRequests(), getCommitLimit(context))) {
        final BulkRequestBuilder<TransactionContext> batchRequest = BulkRequest.create();
        partition.forEach(request -> batchRequest.add(request));
        final Request<BranchContext, CommitResult> commitRequest = SnomedRequests.prepareCommit().setBody(batchRequest.build()).setCommitComment(commitComment).setParentContextDescription(DatastoreLockContextDescriptions.SAVE_CLASSIFICATION_RESULTS).setAuthor(userId).build();
        final CommitResult commitResult = new IdRequest<>(commitRequest).execute(context);
        resultTimeStamp = commitResult.getCommitTimestamp();
    }
    if (Commit.NO_COMMIT_TIMESTAMP == resultTimeStamp) {
        classificationTracker.classificationSaveFailed(classificationId);
        return Boolean.FALSE;
    } else {
        classificationTracker.classificationSaved(classificationId, resultTimeStamp);
        return Boolean.TRUE;
    }
}
Also used : CommitResult(com.b2international.snowowl.core.request.CommitResult) SubMonitor(org.eclipse.core.runtime.SubMonitor) Request(com.b2international.snowowl.core.events.Request) BulkRequest(com.b2international.snowowl.core.events.bulk.BulkRequest) Branch(com.b2international.snowowl.core.branch.Branch) TransactionContext(com.b2international.snowowl.core.domain.TransactionContext) BranchContext(com.b2international.snowowl.core.domain.BranchContext) BadRequestException(com.b2international.commons.exceptions.BadRequestException) ClassificationTracker(com.b2international.snowowl.snomed.reasoner.classification.ClassificationTracker)

Aggregations

Request (com.b2international.snowowl.core.events.Request)14 RepositoryContext (com.b2international.snowowl.core.domain.RepositoryContext)10 BranchContext (com.b2international.snowowl.core.domain.BranchContext)7 Collectors (java.util.stream.Collectors)7 BadRequestException (com.b2international.commons.exceptions.BadRequestException)6 Collection (java.util.Collection)6 SnomedRequests (com.b2international.snowowl.snomed.datastore.request.SnomedRequests)5 Multimap (com.google.common.collect.Multimap)5 Map (java.util.Map)5 Set (java.util.Set)5 ExtendedLocale (com.b2international.commons.http.ExtendedLocale)4 Options (com.b2international.commons.options.Options)4 AuthorizedRequest (com.b2international.snowowl.core.authorization.AuthorizedRequest)4 BaseResourceConverter (com.b2international.snowowl.core.request.BaseResourceConverter)4 BranchRequest (com.b2international.snowowl.core.request.BranchRequest)4 RevisionIndexReadRequest (com.b2international.snowowl.core.request.RevisionIndexReadRequest)4 List (java.util.List)4 CompareUtils (com.b2international.commons.CompareUtils)3 Branch (com.b2international.snowowl.core.branch.Branch)3 CommitInfo (com.b2international.snowowl.core.commit.CommitInfo)3