Search in sources :

Example 11 with Options

use of com.b2international.commons.options.Options 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)

Example 12 with Options

use of com.b2international.commons.options.Options in project snow-owl by b2ihealthcare.

the class EvaluateQueryRefSetMemberRequest method execute.

@Override
public QueryRefSetMemberEvaluation execute(BranchContext context) {
    // TODO support pre-population???
    final boolean active;
    final String query;
    final String targetReferenceSet;
    if (context instanceof TransactionContext) {
        SnomedRefSetMemberIndexEntry member = ((TransactionContext) context).lookup(memberId, SnomedRefSetMemberIndexEntry.class);
        query = member.getQuery();
        targetReferenceSet = member.getReferencedComponentId();
        active = member.isActive();
    } else {
        final SnomedReferenceSetMember member = SnomedRequests.prepareGetMember(memberId).build().execute(context);
        query = (String) member.getProperties().get(SnomedRf2Headers.FIELD_QUERY);
        targetReferenceSet = member.getReferencedComponent().getId();
        active = member.isActive();
    }
    if (!active) {
        return new QueryRefSetMemberEvaluationImpl(memberId, targetReferenceSet, Collections.emptyList());
    }
    if (Strings.isNullOrEmpty(query)) {
        return new QueryRefSetMemberEvaluationImpl(memberId, targetReferenceSet, Collections.emptyList());
    }
    // add all matching first
    final Map<String, SnomedConcept> conceptsToAdd = newHashMap();
    // GET matching members of a query
    SnomedRequests.prepareSearchConcept().filterByEcl(query).setLimit(10_000).stream(context).flatMap(SnomedConcepts::stream).forEach(match -> conceptsToAdd.put(match.getId(), match));
    final Collection<SnomedReferenceSetMember> membersToRemove = newHashSet();
    final Collection<SnomedReferenceSetMember> conceptsToActivate = newHashSet();
    // then re-evaluate all current members of the target simple type reference set
    SnomedRequests.prepareSearchMember().filterByRefSet(targetReferenceSet).setLimit(10_000).stream(context).flatMap(SnomedReferenceSetMembers::stream).forEach(member -> {
        final String referencedComponentId = member.getReferencedComponent().getId();
        if (conceptsToAdd.containsKey(referencedComponentId)) {
            if (!member.isActive()) {
                conceptsToAdd.remove(referencedComponentId);
                conceptsToActivate.add(member);
            } else {
                conceptsToAdd.remove(referencedComponentId);
            }
        } else {
            if (member.isActive()) {
                membersToRemove.add(member);
            }
        }
    });
    // fetch all referenced components
    final Set<String> referencedConceptIds = newHashSet();
    referencedConceptIds.addAll(conceptsToAdd.keySet());
    referencedConceptIds.addAll(FluentIterable.from(membersToRemove).transform(SnomedReferenceSetMember::getReferencedComponent).transform(IComponent::getId).toSet());
    referencedConceptIds.addAll(FluentIterable.from(conceptsToActivate).transform(SnomedReferenceSetMember::getReferencedComponent).transform(IComponent::getId).toSet());
    final Map<String, SnomedConcept> concepts;
    if (expand().containsKey("referencedComponent")) {
        final Options expandOptions = expand().getOptions("referencedComponent");
        concepts = Maps.uniqueIndex(SnomedRequests.prepareSearchConcept().filterByIds(referencedConceptIds).setLimit(referencedConceptIds.size()).setExpand(expandOptions.getOptions("expand")).setLocales(locales()).build().execute(context), IComponent::getId);
    } else {
        // initialize with empty SnomedConcept resources
        concepts = newHashMap();
        for (String referencedConceptId : referencedConceptIds) {
            concepts.put(referencedConceptId, new SnomedConcept(referencedConceptId));
        }
    }
    final Collection<MemberChange> changes = newArrayList();
    for (String id : conceptsToAdd.keySet()) {
        changes.add(MemberChangeImpl.added(concepts.get(id)));
    }
    for (SnomedReferenceSetMember memberToRemove : membersToRemove) {
        changes.add(MemberChangeImpl.removed(concepts.get(memberToRemove.getReferencedComponent().getId()), memberToRemove.getId()));
    }
    for (SnomedReferenceSetMember conceptToActivate : conceptsToActivate) {
        changes.add(MemberChangeImpl.changed(concepts.get(conceptToActivate.getReferencedComponent().getId()), conceptToActivate.getId()));
    }
    return new QueryRefSetMemberEvaluationImpl(memberId, targetReferenceSet, changes);
}
Also used : Options(com.b2international.commons.options.Options) IComponent(com.b2international.snowowl.core.domain.IComponent) SnomedConcept(com.b2international.snowowl.snomed.core.domain.SnomedConcept) SnomedRefSetMemberIndexEntry(com.b2international.snowowl.snomed.datastore.index.entry.SnomedRefSetMemberIndexEntry) TransactionContext(com.b2international.snowowl.core.domain.TransactionContext)

Example 13 with Options

use of com.b2international.commons.options.Options in project snow-owl by b2ihealthcare.

the class SnomedRefSetMemberSearchRequest method prepareQuery.

@Override
protected Expression prepareQuery(BranchContext context) {
    final Collection<String> referencedComponentIds = getCollection(OptionKey.REFERENCED_COMPONENT, String.class);
    final Collection<SnomedRefSetType> refSetTypes = getCollection(OptionKey.REFSET_TYPE, SnomedRefSetType.class);
    final Options propsFilter = getOptions(OptionKey.PROPS);
    ExpressionBuilder queryBuilder = Expressions.builder();
    addActiveClause(queryBuilder);
    addReleasedClause(queryBuilder);
    addEclFilter(context, queryBuilder, SnomedSearchRequest.OptionKey.MODULE, SnomedDocument.Expressions::modules);
    addIdFilter(queryBuilder, RevisionDocument.Expressions::ids);
    addEffectiveTimeClause(queryBuilder);
    addEclFilter(context, queryBuilder, OptionKey.REFSET, SnomedRefSetMemberIndexEntry.Expressions::refsetIds);
    addComponentClause(queryBuilder);
    if (containsKey(OptionKey.REFERENCED_COMPONENT_TYPE)) {
        queryBuilder.filter(referencedComponentTypes(getCollection(OptionKey.REFERENCED_COMPONENT_TYPE, String.class)));
    }
    if (!referencedComponentIds.isEmpty()) {
        queryBuilder.filter(referencedComponentIds(referencedComponentIds));
    }
    if (!refSetTypes.isEmpty()) {
        queryBuilder.filter(refSetTypes(refSetTypes));
    }
    if (!propsFilter.isEmpty()) {
        final Set<String> propKeys = newHashSet(propsFilter.keySet());
        if (propKeys.remove(SnomedRf2Headers.FIELD_ACCEPTABILITY_ID)) {
            queryBuilder.filter(acceptabilityIds(propsFilter.getCollection(SnomedRf2Headers.FIELD_ACCEPTABILITY_ID, String.class)));
        }
        if (propKeys.remove(SnomedRf2Headers.FIELD_RELATIONSHIP_GROUP)) {
            final String operatorKey = SearchResourceRequest.operator(SnomedRf2Headers.FIELD_RELATIONSHIP_GROUP);
            SearchResourceRequest.Operator op;
            if (propKeys.remove(operatorKey)) {
                op = propsFilter.get(operatorKey, Operator.class);
            } else {
                op = SearchResourceRequest.Operator.EQUALS;
            }
            switch(op) {
                case EQUALS:
                    queryBuilder.filter(relationshipGroup(propsFilter.get(SnomedRf2Headers.FIELD_RELATIONSHIP_GROUP, Integer.class)));
                    break;
                case NOT_EQUALS:
                    queryBuilder.mustNot(relationshipGroup(propsFilter.get(SnomedRf2Headers.FIELD_RELATIONSHIP_GROUP, Integer.class)));
                    break;
                default:
                    throw new NotImplementedException("Unsupported relationship group operator %s", op);
            }
        }
        if (propKeys.remove(SnomedRf2Headers.FIELD_CHARACTERISTIC_TYPE_ID)) {
            addEclFilter(context, queryBuilder, propsFilter.getCollection(SnomedRf2Headers.FIELD_CHARACTERISTIC_TYPE_ID, String.class), SnomedRefSetMemberIndexEntry.Expressions::characteristicTypeIds);
        }
        if (propKeys.remove(SnomedRf2Headers.FIELD_CORRELATION_ID)) {
            addEclFilter(context, queryBuilder, propsFilter.getCollection(SnomedRf2Headers.FIELD_CORRELATION_ID, String.class), SnomedRefSetMemberIndexEntry.Expressions::correlationIds);
        }
        if (propKeys.remove(SnomedRf2Headers.FIELD_DESCRIPTION_FORMAT)) {
            addEclFilter(context, queryBuilder, propsFilter.getCollection(SnomedRf2Headers.FIELD_DESCRIPTION_FORMAT, String.class), SnomedRefSetMemberIndexEntry.Expressions::descriptionFormats);
        }
        if (propKeys.remove(SnomedRf2Headers.FIELD_MAP_CATEGORY_ID)) {
            addEclFilter(context, queryBuilder, propsFilter.getCollection(SnomedRf2Headers.FIELD_MAP_CATEGORY_ID, String.class), SnomedRefSetMemberIndexEntry.Expressions::mapCategoryIds);
        }
        if (propKeys.remove(SnomedRf2Headers.FIELD_TARGET_COMPONENT_ID)) {
            addEclFilter(context, queryBuilder, propsFilter.getCollection(SnomedRf2Headers.FIELD_TARGET_COMPONENT_ID, String.class), SnomedRefSetMemberIndexEntry.Expressions::targetComponentIds);
        }
        if (propKeys.remove(SnomedRf2Headers.FIELD_MAP_TARGET)) {
            queryBuilder.filter(mapTargets(propsFilter.getCollection(SnomedRf2Headers.FIELD_MAP_TARGET, String.class)));
        }
        if (propKeys.remove(SnomedRf2Headers.FIELD_MAP_TARGET_DESCRIPTION)) {
            queryBuilder.filter(mapTargetDescriptions(propsFilter.getCollection(SnomedRf2Headers.FIELD_MAP_TARGET_DESCRIPTION, String.class)));
        }
        if (propKeys.remove(SnomedRf2Headers.FIELD_MAP_GROUP)) {
            queryBuilder.filter(mapGroups(propsFilter.getCollection(SnomedRf2Headers.FIELD_MAP_GROUP, Integer.class)));
        }
        if (propKeys.remove(SnomedRf2Headers.FIELD_MAP_PRIORITY)) {
            queryBuilder.filter(mapPriority(propsFilter.getCollection(SnomedRf2Headers.FIELD_MAP_PRIORITY, Integer.class)));
        }
        if (propKeys.remove(SnomedRf2Headers.FIELD_MAP_BLOCK)) {
            queryBuilder.filter(mapBlock(propsFilter.getCollection(SnomedRf2Headers.FIELD_MAP_BLOCK, Integer.class)));
        }
        if (propKeys.remove(SnomedRf2Headers.FIELD_VALUE_ID)) {
            addEclFilter(context, queryBuilder, propsFilter.getCollection(SnomedRf2Headers.FIELD_VALUE_ID, String.class), SnomedRefSetMemberIndexEntry.Expressions::valueIds);
        }
        if (propKeys.remove(SnomedRf2Headers.FIELD_TYPE_ID)) {
            addEclFilter(context, queryBuilder, propsFilter.getCollection(SnomedRf2Headers.FIELD_TYPE_ID, String.class), SnomedRefSetMemberIndexEntry.Expressions::typeIds);
        }
        if (propKeys.remove(SnomedRf2Headers.FIELD_MRCM_DOMAIN_ID)) {
            addEclFilter(context, queryBuilder, propsFilter.getCollection(SnomedRf2Headers.FIELD_MRCM_DOMAIN_ID, String.class), SnomedRefSetMemberIndexEntry.Expressions::domainIds);
        }
        if (propKeys.remove(SnomedRf2Headers.FIELD_MRCM_CONTENT_TYPE_ID)) {
            addEclFilter(context, queryBuilder, propsFilter.getCollection(SnomedRf2Headers.FIELD_MRCM_CONTENT_TYPE_ID, String.class), SnomedRefSetMemberIndexEntry.Expressions::contentTypeIds);
        }
        if (propKeys.remove(SnomedRf2Headers.FIELD_MRCM_RULE_STRENGTH_ID)) {
            addEclFilter(context, queryBuilder, propsFilter.getCollection(SnomedRf2Headers.FIELD_MRCM_RULE_STRENGTH_ID, String.class), SnomedRefSetMemberIndexEntry.Expressions::ruleStrengthIds);
        }
        if (propKeys.remove(SnomedRf2Headers.FIELD_MRCM_RULE_REFSET_ID)) {
            addEclFilter(context, queryBuilder, propsFilter.getCollection(SnomedRf2Headers.FIELD_MRCM_RULE_REFSET_ID, String.class), SnomedRefSetMemberIndexEntry.Expressions::ruleRefSetIds);
        }
        if (propKeys.remove(SnomedRf2Headers.FIELD_MRCM_GROUPED)) {
            queryBuilder.filter(grouped(propsFilter.getBoolean(SnomedRf2Headers.FIELD_MRCM_GROUPED)));
        }
        if (propKeys.remove(SnomedRf2Headers.FIELD_MRCM_RANGE_CONSTRAINT)) {
            queryBuilder.filter(rangeConstraint(propsFilter.getString(SnomedRf2Headers.FIELD_MRCM_RANGE_CONSTRAINT)));
        }
        if (propKeys.remove(SnomedRf2Headers.FIELD_OWL_EXPRESSION)) {
            queryBuilder.filter(Expressions.exactMatch(SnomedRf2Headers.FIELD_OWL_EXPRESSION, propsFilter.getString(SnomedRf2Headers.FIELD_OWL_EXPRESSION)));
        }
        if (propKeys.remove(SnomedRefSetMemberSearchRequestBuilder.OWL_EXPRESSION_CONCEPTID)) {
            addEclFilter(context, queryBuilder, propsFilter.getCollection(SnomedRefSetMemberSearchRequestBuilder.OWL_EXPRESSION_CONCEPTID, String.class), SnomedRefSetMemberIndexEntry.Expressions::owlExpressionConcept);
        }
        if (propKeys.remove(SnomedRefSetMemberSearchRequestBuilder.OWL_EXPRESSION_DESTINATIONID)) {
            addEclFilter(context, queryBuilder, propsFilter.getCollection(SnomedRefSetMemberSearchRequestBuilder.OWL_EXPRESSION_DESTINATIONID, String.class), SnomedRefSetMemberIndexEntry.Expressions::owlExpressionDestination);
        }
        if (propKeys.remove(SnomedRefSetMemberSearchRequestBuilder.OWL_EXPRESSION_TYPEID)) {
            addEclFilter(context, queryBuilder, propsFilter.getCollection(SnomedRefSetMemberSearchRequestBuilder.OWL_EXPRESSION_TYPEID, String.class), SnomedRefSetMemberIndexEntry.Expressions::owlExpressionType);
        }
        if (propKeys.remove(SnomedRefSetMemberSearchRequestBuilder.OWL_EXPRESSION_GCI)) {
            queryBuilder.filter(gciAxiom(propsFilter.getBoolean(SnomedRefSetMemberSearchRequestBuilder.OWL_EXPRESSION_GCI)));
        }
        final Collection<DataType> dataTypes = propsFilter.getCollection(SnomedRefSetMemberIndexEntry.Fields.DATA_TYPE, DataType.class);
        if (propKeys.remove(SnomedRefSetMemberIndexEntry.Fields.DATA_TYPE)) {
            queryBuilder.filter(dataTypes(dataTypes));
        }
        if (propKeys.remove(SnomedRf2Headers.FIELD_VALUE)) {
            if (dataTypes.size() != 1) {
                throw new BadRequestException("DataType filter must be specified if filtering by value");
            }
            final DataType dataType = Iterables.getOnlyElement(dataTypes);
            final String operatorKey = SearchResourceRequest.operator(SnomedRf2Headers.FIELD_VALUE);
            SearchResourceRequest.Operator op;
            if (propKeys.remove(operatorKey)) {
                op = propsFilter.get(operatorKey, Operator.class);
            } else {
                op = SearchResourceRequest.Operator.EQUALS;
            }
            final Collection<Object> attributeValues = propsFilter.getCollection(SnomedRf2Headers.FIELD_VALUE, Object.class);
            switch(op) {
                case EQUALS:
                    queryBuilder.filter(values(dataType, attributeValues));
                    break;
                case NOT_EQUALS:
                    queryBuilder.mustNot(values(dataType, attributeValues));
                    break;
                case LESS_THAN:
                    checkRangeValue(attributeValues);
                    queryBuilder.filter(valueRange(dataType, null, Iterables.getOnlyElement(attributeValues), false, false));
                    break;
                case LESS_THAN_EQUALS:
                    checkRangeValue(attributeValues);
                    queryBuilder.filter(valueRange(dataType, null, Iterables.getOnlyElement(attributeValues), false, true));
                    break;
                case GREATER_THAN:
                    checkRangeValue(attributeValues);
                    queryBuilder.filter(valueRange(dataType, Iterables.getOnlyElement(attributeValues), null, false, false));
                    break;
                case GREATER_THAN_EQUALS:
                    checkRangeValue(attributeValues);
                    queryBuilder.filter(valueRange(dataType, Iterables.getOnlyElement(attributeValues), null, true, false));
                    break;
                default:
                    throw new NotImplementedException("Unsupported concrete domain value operator %s", op);
            }
        }
        if (!propKeys.isEmpty()) {
            throw new IllegalQueryParameterException("Unsupported property filter(s), %s", propKeys);
        }
    }
    return queryBuilder.build();
}
Also used : Options(com.b2international.commons.options.Options) NotImplementedException(com.b2international.commons.exceptions.NotImplementedException) ExpressionBuilder(com.b2international.index.query.Expressions.ExpressionBuilder) IllegalQueryParameterException(com.b2international.commons.exceptions.IllegalQueryParameterException) DataType(com.b2international.snowowl.snomed.core.domain.refset.DataType) BadRequestException(com.b2international.commons.exceptions.BadRequestException) SnomedRefSetType(com.b2international.snowowl.snomed.core.domain.refset.SnomedRefSetType) Expressions(com.b2international.snowowl.snomed.datastore.index.entry.SnomedRefSetMemberIndexEntry.Expressions) Expressions(com.b2international.index.query.Expressions) SearchResourceRequest(com.b2international.snowowl.core.request.SearchResourceRequest)

Example 14 with Options

use of com.b2international.commons.options.Options in project snow-owl by b2ihealthcare.

the class ValidationIssueSearchRequest method prepareQuery.

@Override
protected Expression prepareQuery(ServiceProvider context) {
    final ExpressionBuilder queryBuilder = Expressions.builder();
    addIdFilter(queryBuilder, ids -> Expressions.matchAny(ValidationIssue.Fields.ID, ids));
    if (containsKey(OptionKey.RESOURCE_URI)) {
        queryBuilder.filter(Expressions.matchAny(ValidationIssue.Fields.RESOURCE_URI, getCollection(OptionKey.RESOURCE_URI, String.class)));
    }
    Set<String> filterByRuleIds = null;
    if (containsKey(OptionKey.TOOLING_ID)) {
        final Collection<String> toolingIds = getCollection(OptionKey.TOOLING_ID, String.class);
        final Set<String> ruleIds = ValidationRequests.rules().prepareSearch().all().filterByToolings(toolingIds).setFields(ValidationRule.Fields.ID).build().execute(context).stream().map(ValidationRule::getId).collect(Collectors.toSet());
        if (ruleIds.isEmpty()) {
            queryBuilder.filter(Expressions.matchNone());
        } else {
            filterByRuleIds = newHashSet(ruleIds);
        }
    }
    if (containsKey(OptionKey.RULE_ID)) {
        Set<String> ruleFilter = ImmutableSet.copyOf(getCollection(OptionKey.RULE_ID, String.class));
        if (filterByRuleIds != null) {
            SetView<String> diff = Sets.difference(ruleFilter, filterByRuleIds);
            if (!diff.isEmpty()) {
                throw new BadRequestException("Some of the ruleId filter values '%s' belong to a non-specified toolingId.", diff);
            }
            filterByRuleIds = ruleFilter;
        } else {
            filterByRuleIds = newHashSet(ruleFilter);
        }
    }
    if (filterByRuleIds != null) {
        queryBuilder.filter(Expressions.matchAny(ValidationIssue.Fields.RULE_ID, filterByRuleIds));
    }
    if (containsKey(OptionKey.AFFECTED_COMPONENT_ID)) {
        Collection<String> affectedComponentIds = getCollection(OptionKey.AFFECTED_COMPONENT_ID, String.class);
        queryBuilder.filter(Expressions.matchAny(ValidationIssue.Fields.AFFECTED_COMPONENT_ID, affectedComponentIds));
    }
    if (containsKey(OptionKey.AFFECTED_COMPONENT_LABEL)) {
        final String searchTerm = getString(OptionKey.AFFECTED_COMPONENT_LABEL);
        if (containsKey(OptionKey.AFFECTED_COMPONENT_ID)) {
            queryBuilder.must(Expressions.matchTextPhrase(ValidationIssue.Fields.AFFECTED_COMPONENT_LABELS_TEXT, searchTerm));
        } else {
            queryBuilder.must(Expressions.builder().should(Expressions.dismaxWithScoreCategories(Expressions.matchTextPhrase(ValidationIssue.Fields.AFFECTED_COMPONENT_LABELS_TEXT, searchTerm), Expressions.matchTextAll(ValidationIssue.Fields.AFFECTED_COMPONENT_LABELS_PREFIX, searchTerm))).should(Expressions.boost(Expressions.exactMatch(ValidationIssue.Fields.AFFECTED_COMPONENT_ID, searchTerm), 1000f)).build());
        }
    }
    if (containsKey(OptionKey.WHITELISTED)) {
        boolean whitelisted = getBoolean(OptionKey.WHITELISTED);
        queryBuilder.filter(Expressions.match(ValidationIssue.Fields.WHITELISTED, whitelisted));
    }
    if (containsKey(OptionKey.DETAILS)) {
        if (!containsKey(OptionKey.TOOLING_ID)) {
            throw new BadRequestException("At least one toolingId is required to be able to filter issues by details.");
        }
        final Collection<String> toolingIds = getCollection(OptionKey.TOOLING_ID, String.class);
        final Options options = getOptions(OptionKey.DETAILS);
        final ExpressionBuilder toolingQuery = Expressions.builder();
        final Collection<ValidationIssueDetailExtension> extensions = context.service(ValidationIssueDetailExtensionProvider.class).getExtensions();
        for (String toolingId : toolingIds) {
            extensions.stream().filter(ext -> toolingId.equals(ext.getToolingId())).findFirst().ifPresent(extension -> {
                final ExpressionBuilder extensionQuery = Expressions.builder();
                extension.prepareQuery(extensionQuery, options);
                toolingQuery.should(extensionQuery.build());
            });
        }
        // at least one tooling should match
        toolingQuery.setMinimumNumberShouldMatch(1);
        queryBuilder.filter(toolingQuery.build());
    }
    return queryBuilder.build();
}
Also used : Options(com.b2international.commons.options.Options) BadRequestException(com.b2international.commons.exceptions.BadRequestException) ExpressionBuilder(com.b2international.index.query.Expressions.ExpressionBuilder)

Example 15 with Options

use of com.b2international.commons.options.Options in project snow-owl by b2ihealthcare.

the class EclExpression method resolveToGroupedOnly.

private Promise<Multimap<String, Integer>> resolveToGroupedOnly(BranchContext context, Set<String> sourceIds) {
    final Set<String> characteristicTypes = isInferred() ? SnomedEclRefinementEvaluator.INFERRED_CHARACTERISTIC_TYPES : SnomedEclRefinementEvaluator.STATED_CHARACTERISTIC_TYPES;
    List<Promise<Multimap<String, Integer>>> promises = newArrayListWithCapacity(3);
    // search relationships
    promises.add(SnomedRequests.prepareSearchRelationship().all().filterByActive(true).filterByCharacteristicTypes(characteristicTypes).filterBySources(sourceIds).filterByGroup(1, Integer.MAX_VALUE).setEclExpressionForm(expressionForm).setFields(SnomedRelationshipIndexEntry.Fields.ID, SnomedRelationshipIndexEntry.Fields.SOURCE_ID, SnomedRelationshipIndexEntry.Fields.RELATIONSHIP_GROUP).build(context.service(ResourceURI.class)).execute(context.service(IEventBus.class)).then(new Function<SnomedRelationships, Multimap<String, Integer>>() {

        @Override
        public Multimap<String, Integer> apply(SnomedRelationships input) {
            final Multimap<String, SnomedRelationship> relationshipsBySource = Multimaps.index(input, SnomedRelationship::getSourceId);
            final Multimap<String, Integer> groupsByRelationshipId = Multimaps.transformValues(relationshipsBySource, SnomedRelationship::getRelationshipGroup);
            return ImmutableSetMultimap.copyOf(groupsByRelationshipId);
        }
    }));
    // search concrete domain members
    if (context.service(SnomedCoreConfiguration.class).isConcreteDomainSupported()) {
        final Options propFilter = Options.builder().put(SnomedRf2Headers.FIELD_CHARACTERISTIC_TYPE_ID, characteristicTypes).put(SearchResourceRequest.operator(SnomedRf2Headers.FIELD_RELATIONSHIP_GROUP), SearchResourceRequest.Operator.NOT_EQUALS).put(SnomedRf2Headers.FIELD_RELATIONSHIP_GROUP, 0).build();
        promises.add(SnomedRequests.prepareSearchMember().all().filterByActive(true).filterByReferencedComponent(sourceIds).filterByRefSetType(SnomedRefSetType.CONCRETE_DATA_TYPE).filterByProps(propFilter).setEclExpressionForm(expressionForm).build(context.service(ResourceURI.class)).execute(context.service(IEventBus.class)).then(members -> {
            final Multimap<String, SnomedReferenceSetMember> relationshipsBySource = Multimaps.index(members, m -> m.getReferencedComponent().getId());
            return Multimaps.transformValues(relationshipsBySource, m -> (Integer) m.getProperties().get(SnomedRf2Headers.FIELD_RELATIONSHIP_GROUP));
        }));
    } else {
        promises.add(Promise.immediate(ImmutableSetMultimap.of()));
    }
    // search owl axiom members
    if (isStated()) {
        ImmutableSetMultimap.Builder<String, Integer> groupedAxioms = ImmutableSetMultimap.builder();
        SnomedEclRefinementEvaluator.evalAxiomStatements(context, true, sourceIds, null, null).forEach(property -> groupedAxioms.put(property.getObjectId(), property.getGroup()));
        promises.add(Promise.immediate(groupedAxioms.build()));
    } else {
        promises.add(Promise.immediate(ImmutableSetMultimap.of()));
    }
    return Promise.all(promises).then(statements -> {
        Multimap<String, Integer> relationshipStatements = (Multimap<String, Integer>) statements.get(0);
        Multimap<String, Integer> concreteDomainStatements = (Multimap<String, Integer>) statements.get(1);
        Multimap<String, Integer> axiomStatements = (Multimap<String, Integer>) statements.get(2);
        return ImmutableSetMultimap.<String, Integer>builder().putAll(relationshipStatements).putAll(concreteDomainStatements).putAll(axiomStatements).build();
    });
}
Also used : Query(com.b2international.index.query.Query) SnomedRelationshipIndexEntry(com.b2international.snowowl.snomed.datastore.index.entry.SnomedRelationshipIndexEntry) Promise(com.b2international.snowowl.core.events.util.Promise) Multimap(com.google.common.collect.Multimap) Multimaps(com.google.common.collect.Multimaps) SnomedRequests(com.b2international.snowowl.snomed.datastore.request.SnomedRequests) Options(com.b2international.commons.options.Options) NestedExpression(com.b2international.snomed.ecl.ecl.NestedExpression) RevisionSearcher(com.b2international.index.revision.RevisionSearcher) Sets.newHashSet(com.google.common.collect.Sets.newHashSet) SnomedConceptDocument(com.b2international.snowowl.snomed.datastore.index.entry.SnomedConceptDocument) Nullable(javax.annotation.Nullable) ResourceURI(com.b2international.snowowl.core.ResourceURI) ImmutableSetMultimap(com.google.common.collect.ImmutableSetMultimap) Lists.newArrayListWithCapacity(com.google.common.collect.Lists.newArrayListWithCapacity) Function(com.google.common.base.Function) SnowowlRuntimeException(com.b2international.snowowl.core.api.SnowowlRuntimeException) RevisionDocument(com.b2international.snowowl.core.repository.RevisionDocument) SnomedConcepts(com.b2international.snowowl.snomed.core.domain.SnomedConcepts) Set(java.util.Set) IOException(java.io.IOException) IEventBus(com.b2international.snowowl.eventbus.IEventBus) NotNull(javax.validation.constraints.NotNull) PathWithVersion(com.b2international.snowowl.core.uri.ResourceURIPathResolver.PathWithVersion) SnomedRelationships(com.b2international.snowowl.snomed.core.domain.SnomedRelationships) Any(com.b2international.snomed.ecl.ecl.Any) Trees(com.b2international.snowowl.snomed.core.tree.Trees) SearchResourceRequest(com.b2international.snowowl.core.request.SearchResourceRequest) SnomedRelationship(com.b2international.snowowl.snomed.core.domain.SnomedRelationship) List(java.util.List) Expressions(com.b2international.index.query.Expressions) SnomedReferenceSetMember(com.b2international.snowowl.snomed.core.domain.refset.SnomedReferenceSetMember) Expression(com.b2international.index.query.Expression) Preconditions(com.google.common.base.Preconditions) Ecl(com.b2international.snomed.ecl.Ecl) SnomedRf2Headers(com.b2international.snowowl.snomed.common.SnomedRf2Headers) EclConceptReference(com.b2international.snomed.ecl.ecl.EclConceptReference) ExpressionConstraint(com.b2international.snomed.ecl.ecl.ExpressionConstraint) BranchContext(com.b2international.snowowl.core.domain.BranchContext) SnomedRefSetType(com.b2international.snowowl.snomed.core.domain.refset.SnomedRefSetType) SnomedCoreConfiguration(com.b2international.snowowl.snomed.datastore.config.SnomedCoreConfiguration) Options(com.b2international.commons.options.Options) SnomedRelationship(com.b2international.snowowl.snomed.core.domain.SnomedRelationship) ImmutableSetMultimap(com.google.common.collect.ImmutableSetMultimap) SnomedCoreConfiguration(com.b2international.snowowl.snomed.datastore.config.SnomedCoreConfiguration) SnomedRelationships(com.b2international.snowowl.snomed.core.domain.SnomedRelationships) Promise(com.b2international.snowowl.core.events.util.Promise) Function(com.google.common.base.Function) Multimap(com.google.common.collect.Multimap) ImmutableSetMultimap(com.google.common.collect.ImmutableSetMultimap) IEventBus(com.b2international.snowowl.eventbus.IEventBus)

Aggregations

Options (com.b2international.commons.options.Options)57 List (java.util.List)15 Collectors (java.util.stream.Collectors)14 Set (java.util.Set)13 ExtendedLocale (com.b2international.commons.http.ExtendedLocale)11 BranchContext (com.b2international.snowowl.core.domain.BranchContext)11 SnomedConcept (com.b2international.snowowl.snomed.core.domain.SnomedConcept)11 SnomedConceptRequestCache (com.b2international.snowowl.snomed.datastore.request.SnomedConceptRequestCache)11 Test (org.junit.Test)9 SnomedReferenceSetMember (com.b2international.snowowl.snomed.core.domain.refset.SnomedReferenceSetMember)8 Map (java.util.Map)8 Concepts (com.b2international.snowowl.snomed.common.SnomedConstants.Concepts)7 SnomedConcepts (com.b2international.snowowl.snomed.core.domain.SnomedConcepts)7 BadRequestException (com.b2international.commons.exceptions.BadRequestException)6 ResourceURI (com.b2international.snowowl.core.ResourceURI)6 RepositoryContext (com.b2international.snowowl.core.domain.RepositoryContext)6 SnomedRelationship (com.b2international.snowowl.snomed.core.domain.SnomedRelationship)6 SnomedRequests (com.b2international.snowowl.snomed.datastore.request.SnomedRequests)6 Multimaps (com.google.common.collect.Multimaps)6 Collection (java.util.Collection)6