Search in sources :

Example 1 with BranchContext

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

the class RevisionIndexReadRequest method execute.

@Override
public B execute(final BranchContext context) {
    final String branchPath = context.path();
    RevisionIndex index = context.service(RevisionIndex.class);
    if (snapshot) {
        return index.read(branchPath, searcher -> {
            try {
                return next(context.inject().bind(RevisionSearcher.class, searcher).build());
            } catch (QueryParseException e) {
                throw new IllegalQueryParameterException(e.getMessage());
            }
        });
    } else {
        return next(context.inject().bind(RevisionSearcher.class, new RevisionSearcher() {

            @Override
            public <T> Aggregation<T> aggregate(AggregationBuilder<T> aggregation) throws IOException {
                return index.read(branchPath, searcher -> searcher.aggregate(aggregation));
            }

            @Override
            public Searcher searcher() {
                return index.read(branchPath, searcher -> searcher.searcher());
            }

            @Override
            public <T> Hits<T> search(Query<T> query) throws IOException {
                return index.read(branchPath, searcher -> searcher.search(query));
            }

            @Override
            public <T> Iterable<T> get(Class<T> type, Iterable<String> keys) throws IOException {
                return index.read(branchPath, searcher -> searcher.get(type, keys));
            }

            @Override
            public <T> T get(Class<T> type, String key) throws IOException {
                return index.read(branchPath, searcher -> searcher.get(type, key));
            }

            @Override
            public String branch() {
                return branchPath;
            }
        }).build());
    }
}
Also used : Searcher(com.b2international.index.Searcher) Query(com.b2international.index.query.Query) Hits(com.b2international.index.Hits) QueryParseException(com.b2international.index.query.QueryParseException) Request(com.b2international.snowowl.core.events.Request) IOException(java.io.IOException) Aggregation(com.b2international.index.aggregations.Aggregation) RevisionSearcher(com.b2international.index.revision.RevisionSearcher) AggregationBuilder(com.b2international.index.aggregations.AggregationBuilder) RevisionIndex(com.b2international.index.revision.RevisionIndex) DelegatingRequest(com.b2international.snowowl.core.events.DelegatingRequest) IllegalQueryParameterException(com.b2international.commons.exceptions.IllegalQueryParameterException) BranchContext(com.b2international.snowowl.core.domain.BranchContext) Hits(com.b2international.index.Hits) RevisionIndex(com.b2international.index.revision.RevisionIndex) Searcher(com.b2international.index.Searcher) RevisionSearcher(com.b2international.index.revision.RevisionSearcher) IOException(java.io.IOException) QueryParseException(com.b2international.index.query.QueryParseException) Aggregation(com.b2international.index.aggregations.Aggregation) IllegalQueryParameterException(com.b2international.commons.exceptions.IllegalQueryParameterException) RevisionSearcher(com.b2international.index.revision.RevisionSearcher)

Example 2 with BranchContext

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

the class SnomedRf2ExportRequest method getIdentifierConcepts.

private List<SnomedConcept> getIdentifierConcepts(final RepositoryContext context, final String currentVersion) {
    final Collection<String> refSetsToLoad;
    if (refSets == null) {
        // Retrieve all reference sets if refSets is null
        final Request<BranchContext, SnomedReferenceSets> refSetRequest = SnomedRequests.prepareSearchRefSet().all().build();
        final SnomedReferenceSets allReferenceSets = execute(context, currentVersion, refSetRequest);
        refSetsToLoad = allReferenceSets.stream().map(r -> r.getId()).collect(Collectors.toSet());
    } else {
        refSetsToLoad = refSets;
    }
    final SnomedConceptSearchRequestBuilder refSetRequestBuilder = SnomedRequests.prepareSearchConcept().all().filterByIds(refSetsToLoad).setExpand("pt(),referenceSet()").setLocales(locales());
    final Request<BranchContext, SnomedConcepts> request = refSetRequestBuilder.build();
    final SnomedConcepts referenceSets = execute(context, currentVersion, request);
    // Return only the identifier concepts which have an existing reference set on this branch
    return referenceSets.stream().filter(c -> c.getReferenceSet() != null).collect(Collectors.toList());
}
Also used : JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) SnomedConceptSearchRequestBuilder(com.b2international.snowowl.snomed.datastore.request.SnomedConceptSearchRequestBuilder) SnomedRelationshipIndexEntry(com.b2international.snowowl.snomed.datastore.index.entry.SnomedRelationshipIndexEntry) SnomedReferenceSets(com.b2international.snowowl.snomed.core.domain.refset.SnomedReferenceSets) RepositoryRequests(com.b2international.snowowl.core.repository.RepositoryRequests) Sets.newTreeSet(com.google.common.collect.Sets.newTreeSet) Collections.singleton(java.util.Collections.singleton) AccessControl(com.b2international.snowowl.core.authorization.AccessControl) LocalTime(java.time.LocalTime) RevisionIndex(com.b2international.index.revision.RevisionIndex) Sets.newHashSet(com.google.common.collect.Sets.newHashSet) AttachmentRegistry(com.b2international.snowowl.core.attachments.AttachmentRegistry) Branches(com.b2international.snowowl.core.branch.Branches) Permission(com.b2international.snowowl.core.identity.Permission) CompareUtils(com.b2international.commons.CompareUtils) Path(java.nio.file.Path) com.google.common.collect(com.google.common.collect) Collectors.toSet(java.util.stream.Collectors.toSet) ResourceURI(com.b2international.snowowl.core.ResourceURI) com.b2international.snowowl.core.request(com.b2international.snowowl.core.request) Version(com.b2international.snowowl.core.version.Version) RepositoryContext(com.b2international.snowowl.core.domain.RepositoryContext) SnowowlRuntimeException(com.b2international.snowowl.core.api.SnowowlRuntimeException) Request(com.b2international.snowowl.core.events.Request) IEventBus(com.b2international.snowowl.eventbus.IEventBus) Instant(java.time.Instant) NotNull(javax.validation.constraints.NotNull) Collectors(java.util.stream.Collectors) Lists.newArrayList(com.google.common.collect.Lists.newArrayList) Stream(java.util.stream.Stream) VersionDocument(com.b2international.snowowl.core.version.VersionDocument) LocalDate(java.time.LocalDate) Sort(com.b2international.snowowl.core.request.SearchResourceRequest.Sort) Entry(java.util.Map.Entry) CodeSystemRequests(com.b2international.snowowl.core.codesystem.CodeSystemRequests) SnomedDescriptionIndexEntry(com.b2international.snowowl.snomed.datastore.index.entry.SnomedDescriptionIndexEntry) BranchContext(com.b2international.snowowl.core.domain.BranchContext) Builder(com.google.common.collect.ImmutableList.Builder) FileUtils(com.b2international.commons.FileUtils) CodeSystem(com.b2international.snowowl.core.codesystem.CodeSystem) EffectiveTimes(com.b2international.snowowl.core.date.EffectiveTimes) java.util(java.util) TerminologyResource(com.b2international.snowowl.core.TerminologyResource) LocalDateTime(java.time.LocalDateTime) com.b2international.snowowl.snomed.datastore.request.rf2.exporter(com.b2international.snowowl.snomed.datastore.request.rf2.exporter) com.b2international.snowowl.snomed.core.domain(com.b2international.snowowl.snomed.core.domain) Branch(com.b2international.snowowl.core.branch.Branch) Concepts(com.b2international.snowowl.snomed.common.SnomedConstants.Concepts) Strings(com.google.common.base.Strings) SnomedRequests(com.b2international.snowowl.snomed.datastore.request.SnomedRequests) Attachment(com.b2international.snowowl.core.attachments.Attachment) SnomedRefSetMemberSearchRequestBuilder(com.b2international.snowowl.snomed.datastore.request.SnomedRefSetMemberSearchRequestBuilder) BadRequestException(com.b2international.commons.exceptions.BadRequestException) BranchPathUtils(com.b2international.snowowl.core.branch.BranchPathUtils) DateFormats(com.b2international.snowowl.core.date.DateFormats) Files(java.nio.file.Files) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) SnomedTerminologyComponentConstants(com.b2international.snowowl.snomed.common.SnomedTerminologyComponentConstants) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) ChronoUnit(java.time.temporal.ChronoUnit) SnomedReferenceSetMember(com.b2international.snowowl.snomed.core.domain.refset.SnomedReferenceSetMember) NotEmpty(org.hibernate.validator.constraints.NotEmpty) DateTimeFormatter(java.time.format.DateTimeFormatter) IComponent(com.b2international.snowowl.core.domain.IComponent) SnomedRf2Headers(com.b2international.snowowl.snomed.common.SnomedRf2Headers) Versions(com.b2international.snowowl.core.version.Versions) SnomedRefSetType(com.b2international.snowowl.snomed.core.domain.refset.SnomedRefSetType) BranchContext(com.b2international.snowowl.core.domain.BranchContext) SnomedReferenceSets(com.b2international.snowowl.snomed.core.domain.refset.SnomedReferenceSets) SnomedConceptSearchRequestBuilder(com.b2international.snowowl.snomed.datastore.request.SnomedConceptSearchRequestBuilder)

Example 3 with BranchContext

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

the class SnomedRf2ImportRequest method updateCodeSystemSettings.

private void updateCodeSystemSettings(final BranchContext context, final ResourceURI codeSystemUri) throws Exception {
    SnomedReferenceSets languageReferenceSets = SnomedRequests.prepareSearchRefSet().all().filterByType(SnomedRefSetType.LANGUAGE).filterByActive(true).setFields(SnomedConceptDocument.Fields.ID).sortBy(Sort.fieldAsc(SnomedConceptDocument.Fields.ID)).build().execute(context);
    /*
		 * XXX: The default language in locales is always "en", as there is no
		 * machine-readable information about what language code each language type
		 * reference set is associated with.
		 */
    final List<ExtendedLocale> locales = languageReferenceSets.stream().map(refSet -> new ExtendedLocale("en", "", refSet.getId())).collect(Collectors.toList());
    // fetch codesystem again to get the latest settings
    CodeSystem currentSnomedCodeSystem = CodeSystemRequests.prepareGetCodeSystem(codeSystemUri.getResourceId()).buildAsync().get(context);
    Map<String, SnomedLanguageConfig> mergedLanguagesConfiguration = Maps.newLinkedHashMap();
    SnomedDescriptionUtils.getLanguagesConfiguration(context.service(ObjectMapper.class), currentSnomedCodeSystem).forEach(config -> {
        mergedLanguagesConfiguration.put(config.getLanguageTag(), config);
    });
    languageReferenceSets.stream().map(SnomedReferenceSet::getId).filter(SnomedTerminologyComponentConstants.LANG_REFSET_DIALECT_ALIASES::containsKey).forEach(langRefsetId -> {
        final String dialect = SnomedTerminologyComponentConstants.LANG_REFSET_DIALECT_ALIASES.get(langRefsetId);
        // ignore any aliases that are already defined by using computeIfAbsent
        mergedLanguagesConfiguration.computeIfAbsent(dialect, languageTag -> new SnomedLanguageConfig(languageTag, langRefsetId));
    });
    CodeSystemRequests.prepareUpdateCodeSystem(codeSystemUri.getResourceId()).setSettings(Map.of(CodeSystem.CommonSettings.LOCALES, locales, SnomedTerminologyComponentConstants.CODESYSTEM_LANGUAGE_CONFIG_KEY, mergedLanguagesConfiguration.values())).build(context.service(User.class).getUsername(), String.format("Update '%s' settings based on RF2 import", codeSystemUri.getResourceId())).execute(context.service(IEventBus.class)).getSync(2, TimeUnit.MINUTES);
}
Also used : JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) Query(com.b2international.index.query.Query) MappingIterator(com.fasterxml.jackson.databind.MappingIterator) LoggerFactory(org.slf4j.LoggerFactory) SnomedReferenceSets(com.b2international.snowowl.snomed.core.domain.refset.SnomedReferenceSets) ObjectReader(com.fasterxml.jackson.databind.ObjectReader) SnomedDescriptionUtils(com.b2international.snowowl.snomed.datastore.SnomedDescriptionUtils) AccessControl(com.b2international.snowowl.core.authorization.AccessControl) Map(java.util.Map) AttachmentRegistry(com.b2international.snowowl.core.attachments.AttachmentRegistry) SnomedLanguageConfig(com.b2international.snowowl.snomed.datastore.config.SnomedLanguageConfig) ZipFile(java.util.zip.ZipFile) Permission(com.b2international.snowowl.core.identity.Permission) ZipEntry(java.util.zip.ZipEntry) ResourceURI(com.b2international.snowowl.core.ResourceURI) Version(com.b2international.snowowl.core.version.Version) Rf2ReleaseType(com.b2international.snowowl.snomed.core.domain.Rf2ReleaseType) ResourceRequests(com.b2international.snowowl.core.request.ResourceRequests) ImmutableSet(com.google.common.collect.ImmutableSet) Rf2ValidationIssueReporter(com.b2international.snowowl.snomed.datastore.request.rf2.validation.Rf2ValidationIssueReporter) SnowowlRuntimeException(com.b2international.snowowl.core.api.SnowowlRuntimeException) Request(com.b2international.snowowl.core.events.Request) CsvSchema(com.fasterxml.jackson.dataformat.csv.CsvSchema) Set(java.util.Set) IEventBus(com.b2international.snowowl.eventbus.IEventBus) NotNull(javax.validation.constraints.NotNull) Collectors(java.util.stream.Collectors) List(java.util.List) DatastoreLockContextDescriptions(com.b2international.snowowl.core.internal.locks.DatastoreLockContextDescriptions) LocalDate(java.time.LocalDate) Sort(com.b2international.snowowl.core.request.SearchResourceRequest.Sort) DBMaker(org.mapdb.DBMaker) CodeSystemRequests(com.b2international.snowowl.core.codesystem.CodeSystemRequests) BranchContext(com.b2international.snowowl.core.domain.BranchContext) com.b2international.snowowl.snomed.datastore.request.rf2.importer(com.b2international.snowowl.snomed.datastore.request.rf2.importer) Maker(org.mapdb.DBMaker.Maker) CodeSystem(com.b2international.snowowl.core.codesystem.CodeSystem) EffectiveTimes(com.b2international.snowowl.core.date.EffectiveTimes) TerminologyResource(com.b2international.snowowl.core.TerminologyResource) Locks(com.b2international.snowowl.core.locks.Locks) ImportResponse(com.b2international.snowowl.core.request.io.ImportResponse) Stopwatch(com.google.common.base.Stopwatch) Strings(com.google.common.base.Strings) ExtendedLocale(com.b2international.commons.http.ExtendedLocale) SnomedRequests(com.b2international.snowowl.snomed.datastore.request.SnomedRequests) RevisionSearcher(com.b2international.index.revision.RevisionSearcher) InternalAttachmentRegistry(com.b2international.snowowl.core.attachments.InternalAttachmentRegistry) com.b2international.snowowl.snomed.datastore.index.entry(com.b2international.snowowl.snomed.datastore.index.entry) Attachment(com.b2international.snowowl.core.attachments.Attachment) ApiException(com.b2international.commons.exceptions.ApiException) BadRequestException(com.b2international.commons.exceptions.BadRequestException) ImportDefectAcceptor(com.b2international.snowowl.core.request.io.ImportDefectAcceptor) Logger(org.slf4j.Logger) DateFormats(com.b2international.snowowl.core.date.DateFormats) CsvParser(com.fasterxml.jackson.dataformat.csv.CsvParser) Files(java.nio.file.Files) CsvMapper(com.fasterxml.jackson.dataformat.csv.CsvMapper) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) ComponentURI(com.b2international.snowowl.core.uri.ComponentURI) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) SnomedTerminologyComponentConstants(com.b2international.snowowl.snomed.common.SnomedTerminologyComponentConstants) Maps(com.google.common.collect.Maps) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) Paths(java.nio.file.Paths) Rf2GlobalValidator(com.b2international.snowowl.snomed.datastore.request.rf2.validation.Rf2GlobalValidator) User(com.b2international.snowowl.core.identity.User) SnomedReferenceSet(com.b2international.snowowl.snomed.core.domain.refset.SnomedReferenceSet) DB(org.mapdb.DB) Collections(java.util.Collections) ContentAvailabilityInfoProvider(com.b2international.snowowl.core.repository.ContentAvailabilityInfoProvider) InputStream(java.io.InputStream) ImportDefectBuilder(com.b2international.snowowl.core.request.io.ImportDefectAcceptor.ImportDefectBuilder) SnomedRefSetType(com.b2international.snowowl.snomed.core.domain.refset.SnomedRefSetType) SnomedReferenceSet(com.b2international.snowowl.snomed.core.domain.refset.SnomedReferenceSet) ExtendedLocale(com.b2international.commons.http.ExtendedLocale) SnomedTerminologyComponentConstants(com.b2international.snowowl.snomed.common.SnomedTerminologyComponentConstants) SnomedReferenceSets(com.b2international.snowowl.snomed.core.domain.refset.SnomedReferenceSets) CodeSystem(com.b2international.snowowl.core.codesystem.CodeSystem) SnomedLanguageConfig(com.b2international.snowowl.snomed.datastore.config.SnomedLanguageConfig)

Example 4 with BranchContext

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

the class SnomedValidationIssueDetailExtension method extendRelationshipIssueLabels.

private void extendRelationshipIssueLabels(BranchContext context, Collection<ValidationIssue> issues, Map<String, Object> ruleParameters) {
    final RevisionSearcher searcher = context.service(RevisionSearcher.class);
    final List<ValidationIssue> relationshipIssues = issues.stream().filter(issue -> SnomedRelationship.TYPE == issue.getAffectedComponent().getComponentType()).collect(Collectors.toList());
    if (relationshipIssues.isEmpty()) {
        return;
    }
    final Multimap<String, ValidationIssue> issuesByRelationshipId = Multimaps.index(relationshipIssues, issue -> issue.getAffectedComponent().getComponentId());
    final Set<String> conceptsToFetch = newHashSet();
    final Map<String, String> relationshipFragmentsByRelationshipId = Maps.newHashMap();
    searcher.stream(Query.select(String[].class).from(SnomedRelationshipIndexEntry.class).fields(SnomedRelationshipIndexEntry.Fields.ID, SnomedRelationshipIndexEntry.Fields.SOURCE_ID, SnomedRelationshipIndexEntry.Fields.TYPE_ID, SnomedRelationshipIndexEntry.Fields.DESTINATION_ID, SnomedRelationshipIndexEntry.Fields.VALUE_TYPE, SnomedRelationshipIndexEntry.Fields.NUMERIC_VALUE, SnomedRelationshipIndexEntry.Fields.STRING_VALUE).where(SnomedRelationshipIndexEntry.Expressions.ids(issuesByRelationshipId.keySet())).limit(SCROLL_SIZE).build()).forEach(hits -> {
        for (String[] hit : hits) {
            final String id = hit[0];
            final String sourceId = hit[1];
            final String typeId = hit[2];
            final String destinationId = hit[3];
            final String valueType = hit[4];
            final String numericValue = hit[5];
            final String stringValue = hit[6];
            String destination = "";
            conceptsToFetch.add(sourceId);
            conceptsToFetch.add(typeId);
            if (!Strings.isNullOrEmpty(destinationId)) {
                conceptsToFetch.add(destinationId);
                destination = destinationId;
            } else {
                if (RelationshipValueType.DECIMAL.name().equals(valueType) || RelationshipValueType.INTEGER.name().equals(valueType)) {
                    destination = DecimalUtils.decode(numericValue).toString();
                } else if (RelationshipValueType.STRING.name().equals(valueType)) {
                    destination = stringValue;
                }
            }
            relationshipFragmentsByRelationshipId.put(id, String.format("%s|%s|%s", sourceId, typeId, destination));
        }
    });
    Map<String, String> affectedComponentLabelsByConcept = getAffectedComponentLabels(context, ruleParameters, conceptsToFetch);
    if (!affectedComponentLabelsByConcept.isEmpty()) {
        issuesByRelationshipId.values().forEach(issue -> {
            final String[] relationshipFragments = relationshipFragmentsByRelationshipId.get(issue.getAffectedComponent().getComponentId()).split("[|]");
            final String sourceId = relationshipFragments[0];
            final String typeId = relationshipFragments[1];
            final String destinationIdOrValue = relationshipFragments[2];
            final String sourceTerm = affectedComponentLabelsByConcept.getOrDefault(sourceId, sourceId);
            final String typeTerm = affectedComponentLabelsByConcept.getOrDefault(typeId, typeId);
            final String destinationTerm = affectedComponentLabelsByConcept.getOrDefault(destinationIdOrValue, destinationIdOrValue);
            issue.setAffectedComponentLabels(ImmutableList.of(String.format("%s - %s - %s", sourceTerm, typeTerm, destinationTerm)));
        });
    }
}
Also used : EffectiveTimes(com.b2international.snowowl.core.date.EffectiveTimes) RelationshipValueType(com.b2international.snowowl.snomed.core.domain.RelationshipValueType) SnomedConcept(com.b2international.snowowl.snomed.core.domain.SnomedConcept) java.util(java.util) Query(com.b2international.index.query.Query) Hits(com.b2international.index.Hits) ValidationIssue(com.b2international.snowowl.core.validation.issue.ValidationIssue) QueryBuilder(com.b2international.index.query.Query.QueryBuilder) SET_MEMBER(com.b2international.snowowl.core.terminology.ComponentCategory.SET_MEMBER) ValidationIssueDetailExtension(com.b2international.snowowl.core.validation.issue.ValidationIssueDetailExtension) Concepts(com.b2international.snowowl.snomed.common.SnomedConstants.Concepts) Strings(com.google.common.base.Strings) ExtendedLocale(com.b2international.commons.http.ExtendedLocale) SnomedDescriptionUtils(com.b2international.snowowl.snomed.datastore.SnomedDescriptionUtils) SnomedRequests(com.b2international.snowowl.snomed.datastore.request.SnomedRequests) Options(com.b2international.commons.options.Options) RevisionSearcher(com.b2international.index.revision.RevisionSearcher) ExpressionBuilder(com.b2international.index.query.Expressions.ExpressionBuilder) SnomedDescriptions(com.b2international.snowowl.snomed.core.domain.SnomedDescriptions) com.b2international.snowowl.snomed.datastore.index.entry(com.b2international.snowowl.snomed.datastore.index.entry) Sets.newHashSet(com.google.common.collect.Sets.newHashSet) com.google.common.collect(com.google.common.collect) CONCEPT(com.b2international.snowowl.core.terminology.ComponentCategory.CONCEPT) SnomedTerminologyComponentConstants(com.b2international.snowowl.snomed.common.SnomedTerminologyComponentConstants) Collectors(java.util.stream.Collectors) SnomedIssueDetailFilterFields(com.b2international.snowowl.snomed.validation.detail.SnomedValidationIssueDetailExtension.SnomedIssueDetailFilterFields) SnomedRelationship(com.b2international.snowowl.snomed.core.domain.SnomedRelationship) DESCRIPTION(com.b2international.snowowl.core.terminology.ComponentCategory.DESCRIPTION) SnomedDescription(com.b2international.snowowl.snomed.core.domain.SnomedDescription) Expressions(com.b2international.index.query.Expressions) DecimalUtils(com.b2international.index.util.DecimalUtils) SnomedReferenceSetMember(com.b2international.snowowl.snomed.core.domain.refset.SnomedReferenceSetMember) ValidationConfiguration(com.b2international.snowowl.core.internal.validation.ValidationConfiguration) RELATIONSHIP(com.b2international.snowowl.core.terminology.ComponentCategory.RELATIONSHIP) Expression(com.b2international.index.query.Expression) Component(com.b2international.snowowl.core.plugin.Component) Builder(com.google.common.collect.ImmutableMultimap.Builder) BranchContext(com.b2international.snowowl.core.domain.BranchContext) ComponentCategory(com.b2international.snowowl.core.terminology.ComponentCategory) ValidationIssue(com.b2international.snowowl.core.validation.issue.ValidationIssue) RevisionSearcher(com.b2international.index.revision.RevisionSearcher)

Example 5 with BranchContext

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

the class SnomedQueryValidationRuleEvaluator method eval.

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public List<?> eval(BranchContext context, ValidationRule rule, Map<String, Object> params) throws Exception {
    checkArgument(type().equals(rule.getType()), "'%s' is not recognizable by this evaluator (accepts: %s)", rule, type());
    SnomedComponentValidationQuery<?, PageableCollectionResource<SnomedComponent>, SnomedComponent> validationQuery = context.service(ObjectMapper.class).<SnomedComponentValidationQuery<?, PageableCollectionResource<SnomedComponent>, SnomedComponent>>readValue(rule.getImplementation(), TYPE_REF);
    SnomedSearchRequestBuilder<?, PageableCollectionResource<SnomedComponent>> req = validationQuery.prepareSearch();
    String extensionModules = params != null && params.containsKey(ValidationConfiguration.MODULES) ? Strings.nullToEmpty((String) params.get(ValidationConfiguration.MODULES)) : "";
    String module = validationQuery.module;
    if (!Strings.isNullOrEmpty(module)) {
        // If there is a module given assume that it must be more specific and provided on purpose
        req.filterByModule(module);
    } else if (Boolean.TRUE.equals(validationQuery.extensionScope) && !Strings.isNullOrEmpty(extensionModules)) {
        req.filterByModule(extensionModules);
    }
    SearchIndexResourceRequest<BranchContext, ?, ? extends SnomedDocument> searchReq = (SearchIndexResourceRequest<BranchContext, ?, ? extends SnomedDocument>) req.build();
    final ExpressionBuilder expressionBuilder = Expressions.builder().filter(searchReq.toRawQuery(context));
    if (params != null && params.containsKey(ValidationConfiguration.IS_UNPUBLISHED_ONLY) && Boolean.TRUE.equals(params.get(ValidationConfiguration.IS_UNPUBLISHED_ONLY))) {
        expressionBuilder.filter(SnomedDocument.Expressions.effectiveTime(EffectiveTimes.UNSET_EFFECTIVE_TIME));
    }
    Expression where = expressionBuilder.build();
    // TODO check if the expression contains only the ID list, then skip scrolling and just report them
    List[] issues = { null };
    Query.select(String.class).from(validationQuery.getDocType()).fields(SnomedDocument.Fields.ID).where(where).limit(RULE_LIMIT).withScores(false).build().stream(context.service(RevisionSearcher.class)).forEachOrdered(page -> {
        if (issues[0] == null) {
            issues[0] = newArrayListWithExpectedSize(page.getTotal());
        }
        for (String affectedComponentId : page) {
            String affectedComponentType = SnomedComponent.getTypeSafe(affectedComponentId);
            if (TerminologyRegistry.UNKNOWN_COMPONENT_TYPE.equals(affectedComponentType)) {
                affectedComponentType = SnomedReferenceSetMember.TYPE;
            }
            issues[0].add(ComponentIdentifier.of(affectedComponentType, affectedComponentId));
        }
    });
    return issues[0] == null ? Collections.emptyList() : issues[0];
}
Also used : ExpressionBuilder(com.b2international.index.query.Expressions.ExpressionBuilder) SearchIndexResourceRequest(com.b2international.snowowl.core.request.SearchIndexResourceRequest) Expression(com.b2international.index.query.Expression) BranchContext(com.b2international.snowowl.core.domain.BranchContext) PageableCollectionResource(com.b2international.snowowl.core.domain.PageableCollectionResource) List(java.util.List) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Aggregations

BranchContext (com.b2international.snowowl.core.domain.BranchContext)27 Collectors (java.util.stream.Collectors)18 SnomedRequests (com.b2international.snowowl.snomed.datastore.request.SnomedRequests)16 Options (com.b2international.commons.options.Options)15 List (java.util.List)15 Set (java.util.Set)14 Sets.newHashSet (com.google.common.collect.Sets.newHashSet)13 IOException (java.io.IOException)13 BadRequestException (com.b2international.commons.exceptions.BadRequestException)12 RevisionSearcher (com.b2international.index.revision.RevisionSearcher)12 Query (com.b2international.index.query.Query)11 ResourceURI (com.b2international.snowowl.core.ResourceURI)11 SnowowlRuntimeException (com.b2international.snowowl.core.api.SnowowlRuntimeException)11 Request (com.b2international.snowowl.core.events.Request)11 Concepts (com.b2international.snowowl.snomed.common.SnomedConstants.Concepts)11 Expression (com.b2international.index.query.Expression)10 SnomedRf2Headers (com.b2international.snowowl.snomed.common.SnomedRf2Headers)10 Expressions (com.b2international.index.query.Expressions)9 ExpressionBuilder (com.b2international.index.query.Expressions.ExpressionBuilder)9 Function (com.google.common.base.Function)9