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);
}
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);
}
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));
}
}
}
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();
}
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());
}
Aggregations