Search in sources :

Example 1 with ApplicationContext.getServiceForClass

use of com.b2international.snowowl.core.ApplicationContext.getServiceForClass in project snow-owl by b2ihealthcare.

the class SnomedDescriptionApiTest method testDuplicateMemberCleanupEmptiesAcceptabilityMap.

@Test
public void testDuplicateMemberCleanupEmptiesAcceptabilityMap() throws Exception {
    String descriptionId = createNewDescription(branchPath);
    // Inject inactive language member with different acceptability (API won't allow it)
    String memberIdToUpdate = UUID.randomUUID().toString();
    SnomedRefSetMemberIndexEntry member = SnomedRefSetMemberIndexEntry.builder().id(memberIdToUpdate).active(false).released(false).moduleId(Concepts.MODULE_SCT_CORE).refsetId(Concepts.REFSET_LANGUAGE_TYPE_UK).referencedComponentId(descriptionId).referenceSetType(SnomedRefSetType.LANGUAGE).field(SnomedRf2Headers.FIELD_ACCEPTABILITY_ID, Concepts.REFSET_DESCRIPTION_ACCEPTABILITY_PREFERRED).build();
    new RepositoryRequest<>(SnomedTerminologyComponentConstants.TOOLING_ID, context -> {
        ApplicationContext.getServiceForClass(RepositoryManager.class).get(SnomedTerminologyComponentConstants.TOOLING_ID).service(RevisionIndex.class).prepareCommit(branchPath.getPath()).stageNew(member).withContext(context.inject().bind(ModuleIdProvider.class, c -> c.getModuleId()).build()).commit(ApplicationContext.getServiceForClass(TimestampProvider.class).getTimestamp(), "test", "Added duplicate language reference set member to " + descriptionId);
        return null;
    }).execute(ApplicationContext.getServiceForClass(Environment.class));
    // Check the acceptability map; the description should be acceptable in the UK reference set
    SnomedDescription description = getComponent(branchPath, SnomedComponentType.DESCRIPTION, descriptionId, "members()").statusCode(200).extract().as(SnomedDescription.class);
    assertEquals(Acceptability.ACCEPTABLE, description.getAcceptabilityMap().get(Concepts.REFSET_LANGUAGE_TYPE_UK));
    assertEquals(2, description.getMembers().getTotal());
    String memberIdToDelete = null;
    for (SnomedReferenceSetMember descriptionMember : description.getMembers()) {
        if (Concepts.REFSET_DESCRIPTION_ACCEPTABILITY_ACCEPTABLE.equals(descriptionMember.getProperties().get(SnomedRf2Headers.FIELD_ACCEPTABILITY_ID))) {
            memberIdToDelete = descriptionMember.getId();
            break;
        }
    }
    assertNotNull(memberIdToDelete);
    // Using bulk update, remove the currently active member and activate the inactive one, also changing its acceptability
    Json bulkRequest = Json.object("requests", Json.array(Json.object("action", "delete", "memberId", memberIdToDelete), Json.object("action", "update", "memberId", memberIdToUpdate, "active", true, "acceptabilityId", Concepts.REFSET_DESCRIPTION_ACCEPTABILITY_ACCEPTABLE)), "commitComment", "Consolidated language reference set members");
    bulkUpdateMembers(branchPath, Concepts.REFSET_LANGUAGE_TYPE_UK, bulkRequest).statusCode(204);
    // Verify that description acceptability is still acceptable, but only one member remains
    SnomedDescription newDescription = getComponent(branchPath, SnomedComponentType.DESCRIPTION, descriptionId, "members()").statusCode(200).extract().as(SnomedDescription.class);
    assertEquals(Acceptability.ACCEPTABLE, newDescription.getAcceptabilityMap().get(Concepts.REFSET_LANGUAGE_TYPE_UK));
    assertEquals(1, newDescription.getMembers().getTotal());
    SnomedReferenceSetMember languageMember = Iterables.getOnlyElement(newDescription.getMembers());
    assertEquals(memberIdToUpdate, languageMember.getId());
    assertEquals(true, languageMember.isActive());
}
Also used : SnomedRefSetMemberIndexEntry(com.b2international.snowowl.snomed.datastore.index.entry.SnomedRefSetMemberIndexEntry) CoreMatchers(org.hamcrest.CoreMatchers) RestExtensions.assertCreated(com.b2international.snowowl.test.commons.rest.RestExtensions.assertCreated) SnomedRefSetMemberIndexEntry(com.b2international.snowowl.snomed.datastore.index.entry.SnomedRefSetMemberIndexEntry) Json(com.b2international.commons.json.Json) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) SnomedRestFixtures(com.b2international.snowowl.snomed.core.rest.SnomedRestFixtures) SnomedComponentType(com.b2international.snowowl.snomed.core.rest.SnomedComponentType) IdentifierStatus(com.b2international.snowowl.snomed.cis.domain.IdentifierStatus) ApplicationContext.getServiceForClass(com.b2international.snowowl.core.ApplicationContext.getServiceForClass) Map(java.util.Map) RevisionIndex(com.b2international.index.revision.RevisionIndex) RepositoryRequest(com.b2international.snowowl.core.request.RepositoryRequest) ISnomedIdentifierService(com.b2international.snowowl.snomed.cis.ISnomedIdentifierService) ConflictException(com.b2international.commons.exceptions.ConflictException) BulkRequestBuilder(com.b2international.snowowl.core.events.bulk.BulkRequestBuilder) RepositoryManager(com.b2international.snowowl.core.RepositoryManager) ContentType(io.restassured.http.ContentType) TimestampProvider(com.b2international.index.revision.TimestampProvider) InactivationProperties(com.b2international.snowowl.snomed.core.domain.InactivationProperties) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) SnomedDescription(com.b2international.snowowl.snomed.core.domain.SnomedDescription) List(java.util.List) Lists.newArrayList(com.google.common.collect.Lists.newArrayList) LocalDate(java.time.LocalDate) AbstractSnomedApiTest(com.b2international.snowowl.snomed.core.rest.AbstractSnomedApiTest) SnomedComponentRestRequests(com.b2international.snowowl.snomed.core.rest.SnomedComponentRestRequests) CodeSystemVersionRestRequests.getNextAvailableEffectiveDate(com.b2international.snowowl.test.commons.codesystem.CodeSystemVersionRestRequests.getNextAvailableEffectiveDate) Acceptability(com.b2international.snowowl.snomed.core.domain.Acceptability) Iterables(com.google.common.collect.Iterables) CodeSystemVersionRestRequests.createVersion(com.b2international.snowowl.test.commons.codesystem.CodeSystemVersionRestRequests.createVersion) SnomedRefSetRestRequests.updateRefSetComponent(com.b2international.snowowl.snomed.core.rest.SnomedRefSetRestRequests.updateRefSetComponent) Concepts(com.b2international.snowowl.snomed.common.SnomedConstants.Concepts) ModuleIdProvider(com.b2international.snowowl.snomed.datastore.request.ModuleRequest.ModuleIdProvider) AssociationTarget(com.b2international.snowowl.snomed.core.domain.AssociationTarget) TermFilter(com.b2international.snowowl.core.request.TermFilter) Environment(com.b2international.snowowl.core.setup.Environment) SnomedRequests(com.b2international.snowowl.snomed.datastore.request.SnomedRequests) CodeSystemVersionRestRequests.createCodeSystemAndVersion(com.b2international.snowowl.test.commons.codesystem.CodeSystemVersionRestRequests.createCodeSystemAndVersion) BulkRequest(com.b2international.snowowl.core.events.bulk.BulkRequest) RestExtensions.givenAuthenticatedRequest(com.b2international.snowowl.test.commons.rest.RestExtensions.givenAuthenticatedRequest) SctId(com.b2international.snowowl.snomed.cis.domain.SctId) SnomedReferenceSetMembers(com.b2international.snowowl.snomed.core.domain.refset.SnomedReferenceSetMembers) BranchPathUtils(com.b2international.snowowl.core.branch.BranchPathUtils) SnomedApiTestConstants(com.b2international.snowowl.snomed.core.rest.SnomedApiTestConstants) SnomedRefSetRestRequests.bulkUpdateMembers(com.b2international.snowowl.snomed.core.rest.SnomedRefSetRestRequests.bulkUpdateMembers) Assert.assertNotNull(org.junit.Assert.assertNotNull) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) SnomedTerminologyComponentConstants(com.b2international.snowowl.snomed.common.SnomedTerminologyComponentConstants) TextConstants(com.b2international.index.compat.TextConstants) CodeSystemRestRequests.createCodeSystem(com.b2international.snowowl.test.commons.codesystem.CodeSystemRestRequests.createCodeSystem) TimeUnit(java.util.concurrent.TimeUnit) Assert.assertNull(org.junit.Assert.assertNull) TransactionContext(com.b2international.snowowl.core.domain.TransactionContext) SnomedReferenceSetMember(com.b2international.snowowl.snomed.core.domain.refset.SnomedReferenceSetMember) DateTimeFormatter(java.time.format.DateTimeFormatter) SnomedRf2Headers(com.b2international.snowowl.snomed.common.SnomedRf2Headers) Collections(java.util.Collections) IBranchPath(com.b2international.snowowl.core.api.IBranchPath) Assert.assertEquals(org.junit.Assert.assertEquals) ApplicationContext(com.b2international.snowowl.core.ApplicationContext) ComponentCategory(com.b2international.snowowl.core.terminology.ComponentCategory) SnomedRefSetType(com.b2international.snowowl.snomed.core.domain.refset.SnomedRefSetType) SnomedReferenceSetMember(com.b2international.snowowl.snomed.core.domain.refset.SnomedReferenceSetMember) TimestampProvider(com.b2international.index.revision.TimestampProvider) SnomedDescription(com.b2international.snowowl.snomed.core.domain.SnomedDescription) RevisionIndex(com.b2international.index.revision.RevisionIndex) Environment(com.b2international.snowowl.core.setup.Environment) RepositoryManager(com.b2international.snowowl.core.RepositoryManager) Json(com.b2international.commons.json.Json) AbstractSnomedApiTest(com.b2international.snowowl.snomed.core.rest.AbstractSnomedApiTest) Test(org.junit.Test)

Example 2 with ApplicationContext.getServiceForClass

use of com.b2international.snowowl.core.ApplicationContext.getServiceForClass in project snow-owl by b2ihealthcare.

the class ClassifyOperation method run.

/**
 * Allocates a reasoner instance, performs the requested operation, then releases the borrowed instance back to the pool.
 * @param monitor an {@link IProgressMonitor} to monitor operation progress
 * @return the value returned by {@link #processResults(IProgressMonitor, long)}
 * @throws OperationCanceledException
 */
public T run(final IProgressMonitor monitor) throws OperationCanceledException {
    monitor.beginTask("Classification in progress...", IProgressMonitor.UNKNOWN);
    try {
        final String classificationId = UUID.randomUUID().toString();
        final String jobId = IDs.sha1(classificationId);
        final Notifications notifications = getServiceForClass(Notifications.class);
        final BlockingQueue<RemoteJobEntry> jobQueue = Queues.newArrayBlockingQueue(1);
        final Observable<RemoteJobEntry> jobObservable = notifications.ofType(RemoteJobNotification.class).filter(RemoteJobNotification::isChanged).filter(notification -> notification.getJobIds().contains(jobId)).concatMap(notification -> JobRequests.prepareSearch().one().filterById(jobId).buildAsync().execute(getEventBus())).map(RemoteJobs::first).map(Optional<RemoteJobEntry>::get).filter(RemoteJobEntry::isDone);
        // "One-shot" subscription; it should self-destruct after the first notification
        jobObservable.subscribe(new DisposableObserver<RemoteJobEntry>() {

            @Override
            public void onComplete() {
                dispose();
            }

            @Override
            public void onError(final Throwable t) {
                dispose();
            }

            @Override
            public void onNext(final RemoteJobEntry job) {
                try {
                    jobQueue.put(job);
                } catch (InterruptedException e) {
                    throw new SnowowlRuntimeException("Interrupted while trying to add a remote job entry to the queue.", e);
                } finally {
                    dispose();
                }
            }
        });
        ClassificationRequests.prepareCreateClassification().setClassificationId(classificationId).setReasonerId(reasonerId).setUserId(userId).addAllConcepts(additionalConcepts).setParentLockContext(parentLockContext).build(branch).get(ApplicationContext.getServiceForClass(Environment.class));
        while (true) {
            if (monitor.isCanceled()) {
                throw new OperationCanceledException();
            }
            try {
                final RemoteJobEntry jobEntry = jobQueue.poll(CHECK_JOB_INTERVAL_SECONDS, TimeUnit.SECONDS);
                if (jobEntry == null) {
                    continue;
                }
                switch(jobEntry.getState()) {
                    // $FALL-THROUGH$
                    case SCHEDULED:
                    case RUNNING:
                    case CANCEL_REQUESTED:
                        break;
                    case FINISHED:
                        try {
                            return processResults(classificationId);
                        } finally {
                            deleteEntry(jobId);
                        }
                    case CANCELED:
                        deleteEntry(jobId);
                        throw new OperationCanceledException();
                    case FAILED:
                        deleteEntry(jobId);
                        throw new SnowowlRuntimeException("Failed to retrieve the results of the classification.");
                    default:
                        throw new IllegalStateException("Unexpected state '" + jobEntry.getState() + "'.");
                }
            } catch (final InterruptedException e) {
            // Nothing to do
            }
        }
    } finally {
        monitor.done();
    }
}
Also used : SnomedConcept(com.b2international.snowowl.snomed.core.domain.SnomedConcept) Notifications(com.b2international.snowowl.core.events.Notifications) SnowowlRuntimeException(com.b2international.snowowl.core.api.SnowowlRuntimeException) ClassificationRequests(com.b2international.snowowl.snomed.reasoner.request.ClassificationRequests) BlockingQueue(java.util.concurrent.BlockingQueue) RemoteJobEntry(com.b2international.snowowl.core.jobs.RemoteJobEntry) IEventBus(com.b2international.snowowl.eventbus.IEventBus) UUID(java.util.UUID) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) IDs(com.b2international.snowowl.core.id.IDs) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) DatastoreLockContextDescriptions(com.b2international.snowowl.core.internal.locks.DatastoreLockContextDescriptions) RemoteJobNotification(com.b2international.snowowl.core.jobs.RemoteJobNotification) Environment(com.b2international.snowowl.core.setup.Environment) Queues(com.google.common.collect.Queues) DisposableObserver(io.reactivex.observers.DisposableObserver) ApplicationContext.getServiceForClass(com.b2international.snowowl.core.ApplicationContext.getServiceForClass) JobRequests(com.b2international.snowowl.core.jobs.JobRequests) RemoteJobs(com.b2international.snowowl.core.jobs.RemoteJobs) Optional(java.util.Optional) Observable(io.reactivex.Observable) ApplicationContext(com.b2international.snowowl.core.ApplicationContext) RemoteJobs(com.b2international.snowowl.core.jobs.RemoteJobs) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) RemoteJobEntry(com.b2international.snowowl.core.jobs.RemoteJobEntry) SnowowlRuntimeException(com.b2international.snowowl.core.api.SnowowlRuntimeException) Environment(com.b2international.snowowl.core.setup.Environment) Notifications(com.b2international.snowowl.core.events.Notifications)

Aggregations

ApplicationContext (com.b2international.snowowl.core.ApplicationContext)2 ApplicationContext.getServiceForClass (com.b2international.snowowl.core.ApplicationContext.getServiceForClass)2 Environment (com.b2international.snowowl.core.setup.Environment)2 List (java.util.List)2 UUID (java.util.UUID)2 TimeUnit (java.util.concurrent.TimeUnit)2 ConflictException (com.b2international.commons.exceptions.ConflictException)1 Json (com.b2international.commons.json.Json)1 TextConstants (com.b2international.index.compat.TextConstants)1 RevisionIndex (com.b2international.index.revision.RevisionIndex)1 TimestampProvider (com.b2international.index.revision.TimestampProvider)1 RepositoryManager (com.b2international.snowowl.core.RepositoryManager)1 IBranchPath (com.b2international.snowowl.core.api.IBranchPath)1 SnowowlRuntimeException (com.b2international.snowowl.core.api.SnowowlRuntimeException)1 BranchPathUtils (com.b2international.snowowl.core.branch.BranchPathUtils)1 TransactionContext (com.b2international.snowowl.core.domain.TransactionContext)1 Notifications (com.b2international.snowowl.core.events.Notifications)1 BulkRequest (com.b2international.snowowl.core.events.bulk.BulkRequest)1 BulkRequestBuilder (com.b2international.snowowl.core.events.bulk.BulkRequestBuilder)1 IDs (com.b2international.snowowl.core.id.IDs)1