Search in sources :

Example 1 with ServiceProvider

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

the class ConceptMapMappingSearchRequest method doExecute.

@Override
protected ConceptMapMappings doExecute(ServiceProvider context) throws IOException {
    final int limit = limit();
    Options options = Options.builder().putAll(options()).put(ConceptMapMappingSearchRequestEvaluator.OptionKey.AFTER, searchAfter()).put(ConceptMapMappingSearchRequestEvaluator.OptionKey.LIMIT, limit()).put(ConceptMapMappingSearchRequestEvaluator.OptionKey.LOCALES, locales()).put(SearchResourceRequest.OptionKey.SORT_BY, sortBy()).build();
    List<ConceptMapMappings> evaluatedMappings = context.service(RepositoryManager.class).repositories().stream().flatMap(repository -> {
        ConceptMapMappingSearchRequestEvaluator evaluator = repository.service(ConceptMapMappingSearchRequestEvaluator.class);
        Set<ResourceURI> targets = evaluator.evaluateSearchTargetResources(context, options);
        return targets.stream().map(uri -> {
            return evaluator.evaluate(uri, context, options);
        });
    }).collect(Collectors.toList());
    // calculate grand total
    int total = 0;
    for (ConceptMapMappings evaluatedMember : evaluatedMappings) {
        total += evaluatedMember.getTotal();
    }
    return new ConceptMapMappings(// TODO add manual sorting here if multiple resources have been fetched
    evaluatedMappings.stream().flatMap(ConceptMapMappings::stream).limit(limit).collect(Collectors.toList()), null, /* not supported across resources, TODO support it when a single Conceptmap is being fetched */
    limit, total);
}
Also used : List(java.util.List) Options(com.b2international.commons.options.Options) ConceptMapMappings(com.b2international.snowowl.core.domain.ConceptMapMappings) RepositoryManager(com.b2international.snowowl.core.RepositoryManager) ServiceProvider(com.b2international.snowowl.core.ServiceProvider) Set(java.util.Set) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) ResourceURI(com.b2international.snowowl.core.ResourceURI) Options(com.b2international.commons.options.Options) Set(java.util.Set) ConceptMapMappings(com.b2international.snowowl.core.domain.ConceptMapMappings)

Example 2 with ServiceProvider

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

the class ConceptSearchRequest method doExecute.

@Override
protected Concepts doExecute(ServiceProvider context) throws IOException {
    final int limit = limit();
    Options conceptSearchOptions = Options.builder().putAll(options()).put(ConceptSearchRequestEvaluator.OptionKey.ID, componentIds()).put(ConceptSearchRequestEvaluator.OptionKey.AFTER, searchAfter()).put(ConceptSearchRequestEvaluator.OptionKey.LIMIT, limit).put(ConceptSearchRequestEvaluator.OptionKey.LOCALES, locales()).put(ConceptSearchRequestEvaluator.OptionKey.FIELDS, fields()).put(ConceptSearchRequestEvaluator.OptionKey.EXPAND, expand()).put(SearchResourceRequest.OptionKey.SORT_BY, sortBy()).build();
    final CodeSystemSearchRequestBuilder codeSystemSearchReq = CodeSystemRequests.prepareSearchCodeSystem().all();
    final Map<ResourceURI, ResourceURI> codeSystemResourceFiltersByResource;
    if (containsKey(OptionKey.CODESYSTEM)) {
        // remove path so we can use the code resource URI as key
        codeSystemResourceFiltersByResource = Maps.uniqueIndex(getCollection(OptionKey.CODESYSTEM, ResourceURI.class), uri -> uri.withoutPath());
        // for filtering use the keys
        codeSystemSearchReq.filterByIds(codeSystemResourceFiltersByResource.keySet().stream().map(ResourceURI::getResourceId).collect(Collectors.toSet()));
    } else {
        codeSystemResourceFiltersByResource = Collections.emptyMap();
    }
    // .filterByToolingIds(toolingIds) TODO perform TOOLING filtering
    // .filterByUrls(urls) TODO perform URL filtering
    List<Concepts> concepts = codeSystemSearchReq.buildAsync().execute(context).stream().map(codeSystem -> {
        final ResourceURI uriToEvaluateOn = codeSystemResourceFiltersByResource.getOrDefault(codeSystem.getResourceURI(), codeSystem.getResourceURI());
        return context.service(RepositoryManager.class).get(codeSystem.getToolingId()).service(ConceptSearchRequestEvaluator.class).evaluate(uriToEvaluateOn, context, conceptSearchOptions);
    }).collect(Collectors.toList());
    // for single CodeSystem searches, sorting, paging works as it should
    if (concepts.size() == 1) {
        return Iterables.getOnlyElement(concepts);
    }
    // otherwise, check if searchAfter was used, as it would return bogus results; it can not be applied across code systems
    if (searchAfter() != null) {
        throw new BadRequestException("searchAfter is not supported in Concept Search API for multiple code systems.");
    }
    // calculate grand total
    int total = 0;
    for (Concepts conceptsToAdd : concepts) {
        total += conceptsToAdd.getTotal();
    }
    return new Concepts(// TODO add manual sorting here if multiple resources have been fetched
    concepts.stream().flatMap(Concepts::stream).limit(limit).collect(Collectors.toList()), null, /* not supported across codesystems */
    limit, total);
}
Also used : BadRequestException(com.b2international.commons.exceptions.BadRequestException) Iterables(com.google.common.collect.Iterables) RepositoryManager(com.b2international.snowowl.core.RepositoryManager) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) Maps(com.google.common.collect.Maps) List(java.util.List) Options(com.b2international.commons.options.Options) Concepts(com.b2international.snowowl.core.domain.Concepts) CodeSystemSearchRequestBuilder(com.b2international.snowowl.core.codesystem.CodeSystemSearchRequestBuilder) Map(java.util.Map) ServiceProvider(com.b2international.snowowl.core.ServiceProvider) CodeSystemRequests(com.b2international.snowowl.core.codesystem.CodeSystemRequests) Collections(java.util.Collections) ResourceURI(com.b2international.snowowl.core.ResourceURI) Options(com.b2international.commons.options.Options) ResourceURI(com.b2international.snowowl.core.ResourceURI) Concepts(com.b2international.snowowl.core.domain.Concepts) CodeSystemSearchRequestBuilder(com.b2international.snowowl.core.codesystem.CodeSystemSearchRequestBuilder) BadRequestException(com.b2international.commons.exceptions.BadRequestException)

Example 3 with ServiceProvider

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

the class RemoteJob method run.

@Override
protected final IStatus run(IProgressMonitor monitor) {
    final ObjectMapper mapper = this.context.service(ObjectMapper.class);
    final IProgressMonitor trackerMonitor = this.context.service(RemoteJobTracker.class).createMonitor(id, monitor);
    try {
        // override user when necessary
        User user = context.service(User.class);
        if (User.isSystem(this.user)) {
            user = User.SYSTEM;
        } else if (!user.getUsername().equals(this.user)) {
            user = UserRequests.prepareGet(this.user).build().execute(this.context);
        }
        // seed the monitor instance into the current context, so the request can use it for progress reporting
        final ServiceProvider context = this.context.inject().bind(IProgressMonitor.class, trackerMonitor).bind(RemoteJob.class, this).bind(User.class, user).build();
        final Object response = request.execute(context);
        if (response != null) {
            final Class<? extends Object> responseType = response.getClass();
            if (Primitives.isWrapperType(responseType) || String.class.isAssignableFrom(responseType) || UUID.class.isAssignableFrom(responseType)) {
                this.response = toJson(mapper, ImmutableMap.of("value", response));
            } else {
                this.response = toJson(mapper, response);
            }
        }
        final IStatus status = (IStatus) getProperty(REQUEST_STATUS);
        return (status != null) ? status : Statuses.ok();
    } catch (OperationCanceledException e) {
        return Statuses.cancel();
    } catch (Throwable e) {
        final ApiError apiError;
        if (e instanceof ApiException) {
            apiError = ((ApiException) e).toApiError();
        } else {
            apiError = ApiError.builder(e.getMessage()).status(500).developerMessage("Exception caught while executing request in remote job.").addInfo("exception-class", e.getClass().getSimpleName()).build();
        }
        this.response = toJson(mapper, apiError);
        // XXX: Don't delete remote jobs with errors
        autoClean = false;
        return Statuses.error(CoreActivator.PLUGIN_ID, "Failed to execute long running request", e);
    } finally {
        if (autoClean) {
            context.service(RemoteJobTracker.class).requestDeletes(Collections.singleton(id));
        }
    }
}
Also used : IStatus(org.eclipse.core.runtime.IStatus) User(com.b2international.snowowl.core.identity.User) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) ServiceProvider(com.b2international.snowowl.core.ServiceProvider) ApiError(com.b2international.commons.exceptions.ApiError) UUID(java.util.UUID) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) ApiException(com.b2international.commons.exceptions.ApiException)

Example 4 with ServiceProvider

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

the class SnomedBranchRequestTest method createBranchAndCommitToParent.

@Test
public void createBranchAndCommitToParent() throws Exception {
    final Branching branches = RepositoryRequests.branching();
    final Merging merges = RepositoryRequests.merging();
    final String branchA = UUID.randomUUID().toString();
    final String branchB = UUID.randomUUID().toString();
    final String first = branches.prepareCreate().setParent(branchPath).setName(branchA).build(REPOSITORY_ID).execute(bus).getSync();
    final SnomedDescriptionCreateRequestBuilder fsnBuilder = SnomedRequests.prepareNewDescription().setIdFromNamespace(SnomedIdentifiers.INT_NAMESPACE).setModuleId(Concepts.MODULE_ROOT).setTerm("FSN " + branchA).setTypeId(Concepts.FULLY_SPECIFIED_NAME).setAcceptability(ImmutableMap.of(Concepts.REFSET_LANGUAGE_TYPE_UK, Acceptability.PREFERRED));
    final SnomedDescriptionCreateRequestBuilder ptBuilder = SnomedRequests.prepareNewDescription().setIdFromNamespace(SnomedIdentifiers.INT_NAMESPACE).setModuleId(Concepts.MODULE_ROOT).setTerm("PT " + branchA).setTypeId(Concepts.SYNONYM).setAcceptability(ImmutableMap.of(Concepts.REFSET_LANGUAGE_TYPE_UK, Acceptability.PREFERRED));
    final AsyncRequest<CommitResult> conceptRequest = SnomedRequests.prepareNewConcept().setModuleId(Concepts.MODULE_ROOT).setIdFromNamespace(SnomedIdentifiers.INT_NAMESPACE).addParent(Concepts.ROOT_CONCEPT).addDescription(fsnBuilder).addDescription(ptBuilder).build(first, RestExtensions.USER, "Created new concept");
    final CommitResult info = conceptRequest.execute(bus).getSync();
    final String conceptId = info.getResultAs(String.class);
    final String firstParentPath = BranchPathUtils.createPath(first).getParentPath();
    final Request<ServiceProvider, Merge> mergeRequest = merges.prepareCreate().setSource(first).setTarget(firstParentPath).setUserId(User.SYSTEM.getUsername()).setCommitComment("Merging changes").build(REPOSITORY_ID).getRequest();
    final String mergeJobId = JobRequests.prepareSchedule().setDescription("Merging changes").setRequest(mergeRequest).setUser(User.SYSTEM.getUsername()).buildAsync().execute(bus).getSync();
    final RemoteJobEntry mergeJobResult = JobRequests.waitForJob(bus, mergeJobId);
    final Merge merge = mergeJobResult.getResultAs(JsonSupport.getDefaultObjectMapper(), Merge.class);
    assertEquals(true, merge.getConflicts().isEmpty());
    String second = branches.prepareCreate().setParent(firstParentPath).setName(branchB).build(REPOSITORY_ID).execute(bus).getSync();
    final Branch sourceBranch = branches.prepareGet(merge.getSource()).build(REPOSITORY_ID).execute(bus).getSync();
    final Branch secondBranch = branches.prepareGet(second).build(REPOSITORY_ID).execute(bus).getSync();
    assertBranchesCreated(branchA, branchB, sourceBranch, secondBranch);
    assertBranchSegmentsValid(merge.getTarget(), sourceBranch.path(), secondBranch.path());
    // Check that the concept is visible on parent
    SnomedRequests.prepareGetConcept(conceptId).build(firstParentPath).execute(bus).getSync();
}
Also used : BaseRevisionBranching(com.b2international.index.revision.BaseRevisionBranching) Branching(com.b2international.snowowl.core.branch.Branching) Merge(com.b2international.snowowl.core.merge.Merge) Merging(com.b2international.snowowl.core.branch.Merging) CommitResult(com.b2international.snowowl.core.request.CommitResult) RevisionBranch(com.b2international.index.revision.RevisionBranch) Branch(com.b2international.snowowl.core.branch.Branch) ServiceProvider(com.b2international.snowowl.core.ServiceProvider) SnomedDescriptionCreateRequestBuilder(com.b2international.snowowl.snomed.datastore.request.SnomedDescriptionCreateRequestBuilder) RemoteJobEntry(com.b2international.snowowl.core.jobs.RemoteJobEntry) Test(org.junit.Test)

Example 5 with ServiceProvider

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

the class SnomedConceptMapSearchRequestEvaluator method toCollectionResource.

private ConceptMapMappings toCollectionResource(SnomedReferenceSetMembers referenceSetMembers, ResourceURI uri, ServiceProvider context, Options search, SnomedDisplayTermType snomedDisplayTermType) {
    final Set<String> refSetsToFetch = referenceSetMembers.stream().map(SnomedReferenceSetMember::getRefsetId).collect(Collectors.toSet());
    final Map<String, SnomedConcept> refSetsById = SnomedRequests.prepareSearchConcept().all().filterByIds(refSetsToFetch).setLocales(search.getList(OptionKey.LOCALES, ExtendedLocale.class)).setExpand("pt(),referenceSet()").build(uri).execute(context.service(IEventBus.class)).getSync(1, TimeUnit.MINUTES).stream().collect(Collectors.toMap(SnomedConcept::getId, concept -> concept));
    final Map<String, ComponentURI> targetComponentsByRefSetId = getTargetComponentsByRefSetId(context, refSetsById);
    List<ConceptMapMapping> mappings = referenceSetMembers.stream().filter(m -> SnomedConcept.TYPE.equals(m.getReferencedComponent().getComponentType())).map(m -> {
        return toMapping(m, uri, targetComponentsByRefSetId.get(m.getRefsetId()), snomedDisplayTermType, refSetsById);
    }).collect(Collectors.toList());
    if (!mappings.isEmpty()) {
        final Map<String, Concept> conceptsById = Multimaps.index(mappings, mapping -> mapping.getTargetComponentURI().resourceUri()).asMap().entrySet().stream().filter(entry -> !TerminologyRegistry.UNSPECIFIED.equals(entry.getKey().getResourceId())).map(entry -> {
            final Set<String> idsToFetch = entry.getValue().stream().map(map -> map.getTargetComponentURI().identifier()).collect(Collectors.toSet());
            return CodeSystemRequests.prepareSearchConcepts().all().filterByCodeSystemUri(entry.getKey()).filterByIds(idsToFetch).buildAsync().execute(context.service(IEventBus.class)).getSync(5, TimeUnit.MINUTES).stream().collect(Collectors.toMap(Concept::getId, c -> c));
        }).flatMap(map -> map.entrySet().stream()).collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue(), (concept1, concept2) -> concept1));
        mappings = mappings.stream().map(mapping -> {
            final String mapTargetId = mapping.getTargetComponentURI().identifier();
            if (conceptsById.containsKey(mapTargetId) && !mapping.getTargetComponentURI().isUnspecified()) {
                final Concept concept = conceptsById.get(mapTargetId);
                return mapping.toBuilder().targetTerm(concept.getTerm()).targetIconId(concept.getIconId()).build();
            } else {
                return mapping;
            }
        }).collect(Collectors.toList());
    }
    return new ConceptMapMappings(mappings, referenceSetMembers.getSearchAfter(), referenceSetMembers.getLimit(), referenceSetMembers.getTotal());
}
Also used : CodeSystem(com.b2international.snowowl.core.codesystem.CodeSystem) SnomedConcept(com.b2international.snowowl.snomed.core.domain.SnomedConcept) SnomedRefSetUtil(com.b2international.snowowl.snomed.datastore.SnomedRefSetUtil) ConceptMapMappingSearchRequestEvaluator(com.b2international.snowowl.core.request.ConceptMapMappingSearchRequestEvaluator) SnomedDisplayTermType(com.b2international.snowowl.snomed.core.SnomedDisplayTermType) Concepts(com.b2international.snowowl.snomed.common.SnomedConstants.Concepts) Multimaps(com.google.common.collect.Multimaps) Strings(com.google.common.base.Strings) ExtendedLocale(com.b2international.commons.http.ExtendedLocale) Options(com.b2international.commons.options.Options) ConceptMapMappings(com.b2international.snowowl.core.domain.ConceptMapMappings) Map(java.util.Map) ResourceURI(com.b2international.snowowl.core.ResourceURI) SnomedReferenceSetMembers(com.b2international.snowowl.snomed.core.domain.refset.SnomedReferenceSetMembers) ConceptMapMapping(com.b2international.snowowl.core.domain.ConceptMapMapping) Collection(java.util.Collection) MappingCorrelation(com.b2international.snowowl.core.request.MappingCorrelation) Set(java.util.Set) ComponentURI(com.b2international.snowowl.core.uri.ComponentURI) Builder(com.b2international.snowowl.core.domain.ConceptMapMapping.Builder) IEventBus(com.b2international.snowowl.eventbus.IEventBus) Collectors(java.util.stream.Collectors) TerminologyRegistry(com.b2international.snowowl.core.terminology.TerminologyRegistry) TimeUnit(java.util.concurrent.TimeUnit) ResourceDocument(com.b2international.snowowl.core.internal.ResourceDocument) List(java.util.List) Concept(com.b2international.snowowl.core.domain.Concept) SnomedReferenceSetMember(com.b2international.snowowl.snomed.core.domain.refset.SnomedReferenceSetMember) ServiceProvider(com.b2international.snowowl.core.ServiceProvider) CodeSystemRequests(com.b2international.snowowl.core.codesystem.CodeSystemRequests) SnomedRf2Headers(com.b2international.snowowl.snomed.common.SnomedRf2Headers) SnomedReferenceSet(com.b2international.snowowl.snomed.core.domain.refset.SnomedReferenceSet) OptionsBuilder(com.b2international.commons.options.OptionsBuilder) SnomedRefSetType(com.b2international.snowowl.snomed.core.domain.refset.SnomedRefSetType) SnomedConcept(com.b2international.snowowl.snomed.core.domain.SnomedConcept) Concept(com.b2international.snowowl.core.domain.Concept) ConceptMapMapping(com.b2international.snowowl.core.domain.ConceptMapMapping) ComponentURI(com.b2international.snowowl.core.uri.ComponentURI) ExtendedLocale(com.b2international.commons.http.ExtendedLocale) SnomedConcept(com.b2international.snowowl.snomed.core.domain.SnomedConcept) ConceptMapMappings(com.b2international.snowowl.core.domain.ConceptMapMappings)

Aggregations

ServiceProvider (com.b2international.snowowl.core.ServiceProvider)16 List (java.util.List)9 Collectors (java.util.stream.Collectors)9 Set (java.util.Set)8 IOException (java.io.IOException)6 ResourceURI (com.b2international.snowowl.core.ResourceURI)5 Map (java.util.Map)5 Options (com.b2international.commons.options.Options)4 BadRequestException (com.b2international.commons.exceptions.BadRequestException)3 RepositoryManager (com.b2international.snowowl.core.RepositoryManager)3 CodeSystemRequests (com.b2international.snowowl.core.codesystem.CodeSystemRequests)3 Request (com.b2international.snowowl.core.events.Request)3 User (com.b2international.snowowl.core.identity.User)3 ApiException (com.b2international.commons.exceptions.ApiException)2 Branch (com.b2international.snowowl.core.branch.Branch)2 Concept (com.b2international.snowowl.core.domain.Concept)2 ConceptMapMappings (com.b2international.snowowl.core.domain.ConceptMapMappings)2 RequestHeaders (com.b2international.snowowl.core.events.util.RequestHeaders)2 Permission (com.b2international.snowowl.core.identity.Permission)2 IEventBus (com.b2international.snowowl.eventbus.IEventBus)2