Search in sources :

Example 6 with Value

use of org.hl7.fhir.utilities.graphql.Value in project beneficiary-fhir-data by CMSgov.

the class TransformerUtils method addExtensionValueQuantity.

/**
 * Adds an {@link Extension} to the specified {@link DomainResource}. {@link Extension#getValue()}
 * will be set to a {@link Quantity} with the specified system and value.
 *
 * @param fhirElement the FHIR element to add the {@link Extension} to
 * @param extensionUrl the {@link Extension#getUrl()} to use
 * @param quantitySystem the {@link Quantity#getSystem()} to use
 * @param quantityValue the {@link Quantity#getValue()} to use
 */
static void addExtensionValueQuantity(IBaseHasExtensions fhirElement, String extensionUrl, String quantitySystem, BigDecimal quantityValue) {
    IBaseExtension<?, ?> extension = fhirElement.addExtension();
    extension.setUrl(extensionUrl);
    extension.setValue(new Quantity().setSystem(extensionUrl).setValue(quantityValue));
// CodeableConcept codeableConcept = new CodeableConcept();
// extension.setValue(codeableConcept);
// 
// Coding coding = codeableConcept.addCoding();
// coding.setSystem(codingSystem).setCode(codingCode);
}
Also used : SimpleQuantity(org.hl7.fhir.dstu3.model.SimpleQuantity) Quantity(org.hl7.fhir.dstu3.model.Quantity)

Example 7 with Value

use of org.hl7.fhir.utilities.graphql.Value in project beneficiary-fhir-data by CMSgov.

the class TransformerUtilsV2 method createExtensionQuantity.

/**
 * @param ccwVariable the {@link CcwCodebookInterface} being mapped
 * @param quantityValue the value to use for {@link Coding#getCode()} for the resulting {@link
 *     Coding}
 * @return the output {@link Extension}, with {@link Extension#getValue()} set to represent the
 *     specified input values
 */
static Extension createExtensionQuantity(CcwCodebookInterface ccwVariable, Optional<? extends Number> quantityValue) {
    if (!quantityValue.isPresent()) {
        throw new IllegalArgumentException();
    }
    Quantity quantity;
    if (quantityValue.get() instanceof BigDecimal) {
        quantity = new Quantity().setValue((BigDecimal) quantityValue.get());
    } else {
        throw new BadCodeMonkeyException();
    }
    String extensionUrl = CCWUtils.calculateVariableReferenceUrl(ccwVariable);
    Extension extension = new Extension(extensionUrl, quantity);
    return extension;
}
Also used : Extension(org.hl7.fhir.r4.model.Extension) BadCodeMonkeyException(gov.cms.bfd.sharedutils.exceptions.BadCodeMonkeyException) SimpleQuantity(org.hl7.fhir.r4.model.SimpleQuantity) Quantity(org.hl7.fhir.r4.model.Quantity) BigDecimal(java.math.BigDecimal)

Example 8 with Value

use of org.hl7.fhir.utilities.graphql.Value in project beneficiary-fhir-data by CMSgov.

the class PatientResourceProvider method queryDatabaseByHash.

/**
 * @param hash the {@link Beneficiary} hash value to match
 * @param hashType a string to represent the hash type (used for logging purposes)
 * @param requestHeader the {@link #RequestHeaders} where resource request headers are
 *     encapsulated
 * @param beneficiaryHashField the JPA location of the beneficiary hash field
 * @param beneficiaryHistoryHashField the JPA location of the beneficiary history hash field
 * @return a FHIR {@link Patient} for the CCW {@link Beneficiary} that matches the specified
 *     {@link Beneficiary} hash value
 * @throws NoResultException A {@link NoResultException} will be thrown if no matching {@link
 *     Beneficiary} can be found
 */
@Trace
private Patient queryDatabaseByHash(String hash, String hashType, SingularAttribute<Beneficiary, String> beneficiaryHashField, SingularAttribute<BeneficiaryHistory, String> beneficiaryHistoryHashField, RequestHeaders requestHeader) {
    if (hash == null || hash.trim().isEmpty())
        throw new IllegalArgumentException();
    /*
     * Beneficiaries' HICN/MBIs can change over time and those past HICN/MBIs may land in
     * BeneficiaryHistory records. Accordingly, we need to search for matching HICN/MBIs in both the
     * Beneficiary and the BeneficiaryHistory records.
     *
     * There's no sane way to do this in a single query with JPA 2.1, it appears: JPA doesn't
     * support UNIONs and it doesn't support subqueries in FROM clauses. That said, the ideal query
     * would look like this:
     *
     * SELECT * FROM ( SELECT DISTINCT "beneficiaryId" FROM "Beneficiaries" WHERE "hicn" =
     * :'hicn_hash' UNION SELECT DISTINCT "beneficiaryId" FROM "BeneficiariesHistory" WHERE "hicn" =
     * :'hicn_hash') AS matching_benes INNER JOIN "Beneficiaries" ON matching_benes."beneficiaryId"
     * = "Beneficiaries"."beneficiaryId" LEFT JOIN "BeneficiariesHistory" ON
     * "Beneficiaries"."beneficiaryId" = "BeneficiariesHistory"."beneficiaryId" LEFT JOIN
     * "MedicareBeneficiaryIdHistory" ON "Beneficiaries"."beneficiaryId" =
     * "MedicareBeneficiaryIdHistory"."beneficiaryId";
     *
     * ... with the returned columns and JOINs being dynamic, depending on IncludeIdentifiers.
     *
     * In lieu of that, we run two queries: one to find HICN/MBI matches in BeneficiariesHistory,
     * and a second to find BENE_ID or HICN/MBI matches in Beneficiaries (with all of their data, so
     * we're ready to return the result). This is bad and dumb but I can't find a better working
     * alternative.
     *
     * (I'll just note that I did also try JPA/Hibernate native SQL queries but couldn't get the
     * joins or fetch groups to work with them.)
     *
     * If we want to fix this, we need to move identifiers out entirely to separate tables:
     * BeneficiaryHicns and BeneficiaryMbis. We could then safely query these tables and join them
     * back to Beneficiaries (and hopefully the optimizer will play nice, too).
     */
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    // First, find all matching hashes from BeneficiariesHistory.
    CriteriaQuery<String> beneHistoryMatches = builder.createQuery(String.class);
    Root<BeneficiaryHistory> beneHistoryMatchesRoot = beneHistoryMatches.from(BeneficiaryHistory.class);
    beneHistoryMatches.select(beneHistoryMatchesRoot.get(BeneficiaryHistory_.beneficiaryId));
    beneHistoryMatches.where(builder.equal(beneHistoryMatchesRoot.get(beneficiaryHistoryHashField), hash));
    List<String> matchingIdsFromBeneHistory = null;
    Long hicnsFromHistoryQueryNanoSeconds = null;
    Timer.Context beneHistoryMatchesTimer = metricRegistry.timer(MetricRegistry.name(getClass().getSimpleName(), "query", "bene_by_" + hashType, hashType + "s_from_beneficiarieshistory")).time();
    try {
        matchingIdsFromBeneHistory = entityManager.createQuery(beneHistoryMatches).getResultList();
    } finally {
        hicnsFromHistoryQueryNanoSeconds = beneHistoryMatchesTimer.stop();
        TransformerUtils.recordQueryInMdc("bene_by_" + hashType + "." + hashType + "s_from_beneficiarieshistory", hicnsFromHistoryQueryNanoSeconds, matchingIdsFromBeneHistory == null ? 0 : matchingIdsFromBeneHistory.size());
    }
    // Then, find all Beneficiary records that match the hash or those BENE_IDs.
    CriteriaQuery<Beneficiary> beneMatches = builder.createQuery(Beneficiary.class);
    Root<Beneficiary> beneMatchesRoot = beneMatches.from(Beneficiary.class);
    beneMatchesRoot.fetch(Beneficiary_.skippedRifRecords, JoinType.LEFT);
    if (requestHeader.isHICNinIncludeIdentifiers())
        beneMatchesRoot.fetch(Beneficiary_.beneficiaryHistories, JoinType.LEFT);
    if (requestHeader.isMBIinIncludeIdentifiers())
        beneMatchesRoot.fetch(Beneficiary_.medicareBeneficiaryIdHistories, JoinType.LEFT);
    beneMatches.select(beneMatchesRoot);
    Predicate beneHashMatches = builder.equal(beneMatchesRoot.get(beneficiaryHashField), hash);
    if (matchingIdsFromBeneHistory != null && !matchingIdsFromBeneHistory.isEmpty()) {
        Predicate beneHistoryHashMatches = beneMatchesRoot.get(Beneficiary_.beneficiaryId).in(matchingIdsFromBeneHistory);
        beneMatches.where(builder.or(beneHashMatches, beneHistoryHashMatches));
    } else {
        beneMatches.where(beneHashMatches);
    }
    List<Beneficiary> matchingBenes = Collections.emptyList();
    Long benesByHashOrIdQueryNanoSeconds = null;
    Timer.Context timerHicnQuery = metricRegistry.timer(MetricRegistry.name(getClass().getSimpleName(), "query", "bene_by_" + hashType, "bene_by_" + hashType + "_or_id")).time();
    try {
        matchingBenes = entityManager.createQuery(beneMatches).getResultList();
    } finally {
        benesByHashOrIdQueryNanoSeconds = timerHicnQuery.stop();
        TransformerUtils.recordQueryInMdc(String.format("bene_by_" + hashType + ".bene_by_" + hashType + "_or_id.include_%s", String.join("_", (List<String>) requestHeader.getValue(HEADER_NAME_INCLUDE_IDENTIFIERS))), benesByHashOrIdQueryNanoSeconds, matchingBenes.size());
    }
    // Then, if we found more than one distinct BENE_ID, or none, throw an error.
    long distinctBeneIds = matchingBenes.stream().map(Beneficiary::getBeneficiaryId).filter(Objects::nonNull).distinct().count();
    Beneficiary beneficiary = null;
    if (distinctBeneIds <= 0) {
        throw new NoResultException();
    } else if (distinctBeneIds > 1) {
        MDC.put("database_query.by_hash.collision.distinct_bene_ids", Long.toString(distinctBeneIds));
        throw new ResourceNotFoundException("By hash query found more than one distinct BENE_ID: " + Long.toString(distinctBeneIds));
    } else if (distinctBeneIds == 1) {
        beneficiary = matchingBenes.get(0);
    }
    // Null out the unhashed HICNs if we're not supposed to be returning them
    if (!requestHeader.isHICNinIncludeIdentifiers()) {
        beneficiary.setHicnUnhashed(Optional.empty());
    }
    // Null out the unhashed MBIs if we're not supposed to be returning
    if (!requestHeader.isMBIinIncludeIdentifiers()) {
        beneficiary.setMedicareBeneficiaryId(Optional.empty());
    }
    Patient patient = BeneficiaryTransformer.transform(metricRegistry, beneficiary, requestHeader);
    return patient;
}
Also used : CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) BeneficiaryHistory(gov.cms.bfd.model.rif.BeneficiaryHistory) Patient(org.hl7.fhir.dstu3.model.Patient) NoResultException(javax.persistence.NoResultException) Predicate(javax.persistence.criteria.Predicate) Timer(com.codahale.metrics.Timer) Objects(java.util.Objects) ResourceNotFoundException(ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException) Beneficiary(gov.cms.bfd.model.rif.Beneficiary) Trace(com.newrelic.api.agent.Trace)

Example 9 with Value

use of org.hl7.fhir.utilities.graphql.Value in project beneficiary-fhir-data by CMSgov.

the class PatientResourceProvider method searchByIdentifier.

/**
 * Adds support for the FHIR "search" operation for {@link Patient}s, allowing users to search by
 * {@link Patient#getIdentifier()}. Specifically, the following criteria are supported:
 *
 * <ul>
 *   <li>Matching a {@link Beneficiary#getHicn()} hash value: when {@link TokenParam#getSystem()}
 *       matches one of the {@link #SUPPORTED_HASH_IDENTIFIER_SYSTEMS} entries.
 * </ul>
 *
 * <p>Searches that don't match one of the above forms are not supported.
 *
 * <p>The {@link Search} annotation indicates that this method supports the search operation.
 * There may be many different methods annotated with this {@link Search} annotation, to support
 * many different search criteria.
 *
 * @param identifier an {@link Identifier} {@link TokenParam} for the {@link
 *     Patient#getIdentifier()} to try and find a matching {@link Patient} for
 * @param startIndex an {@link OptionalParam} for the startIndex (or offset) used to determine
 *     pagination
 * @param lastUpdated an {@link OptionalParam} to filter the results based on the passed date
 *     range
 * @param requestDetails a {@link RequestDetails} containing the details of the request URL, used
 *     to parse out pagination values
 * @return Returns a {@link List} of {@link Patient}s, which may contain multiple matching
 *     resources, or may also be empty.
 */
@Search
@Trace
public Bundle searchByIdentifier(@RequiredParam(name = Patient.SP_IDENTIFIER) @Description(shortDefinition = "The patient identifier to search for") TokenParam identifier, @OptionalParam(name = "startIndex") @Description(shortDefinition = "The offset used for result pagination") String startIndex, @OptionalParam(name = "_lastUpdated") @Description(shortDefinition = "Include resources last updated in the given range") DateRangeParam lastUpdated, RequestDetails requestDetails) {
    if (identifier.getQueryParameterQualifier() != null)
        throw new InvalidRequestException("Unsupported query parameter qualifier: " + identifier.getQueryParameterQualifier());
    if (!SUPPORTED_HASH_IDENTIFIER_SYSTEMS.contains(identifier.getSystem()))
        throw new InvalidRequestException("Unsupported identifier system: " + identifier.getSystem());
    RequestHeaders requestHeader = RequestHeaders.getHeaderWrapper(requestDetails);
    Operation operation = new Operation(Operation.Endpoint.V1_PATIENT);
    operation.setOption("by", "identifier");
    requestHeader.getNVPairs().forEach((n, v) -> operation.setOption(n, v.toString()));
    operation.setOption("_lastUpdated", Boolean.toString(lastUpdated != null && !lastUpdated.isEmpty()));
    operation.publishOperationName();
    List<IBaseResource> patients;
    try {
        Patient patient;
        switch(identifier.getSystem()) {
            case TransformerConstants.CODING_BBAPI_BENE_HICN_HASH:
            case TransformerConstants.CODING_BBAPI_BENE_HICN_HASH_OLD:
                patient = queryDatabaseByHicnHash(identifier.getValue(), requestHeader);
                break;
            case TransformerConstants.CODING_BBAPI_BENE_MBI_HASH:
                patient = queryDatabaseByMbiHash(identifier.getValue(), requestHeader);
                break;
            default:
                throw new InvalidRequestException("Unsupported identifier system: " + identifier.getSystem());
        }
        patients = QueryUtils.isInRange(patient.getMeta().getLastUpdated().toInstant(), lastUpdated) ? Collections.singletonList(patient) : Collections.emptyList();
    } catch (NoResultException e) {
        patients = new LinkedList<>();
    }
    OffsetLinkBuilder paging = new OffsetLinkBuilder(requestDetails, "/Patient?");
    Bundle bundle = TransformerUtils.createBundle(paging, patients, loadedFilterManager.getTransactionTime());
    return bundle;
}
Also used : OffsetLinkBuilder(gov.cms.bfd.server.war.commons.OffsetLinkBuilder) Bundle(org.hl7.fhir.dstu3.model.Bundle) Patient(org.hl7.fhir.dstu3.model.Patient) InvalidRequestException(ca.uhn.fhir.rest.server.exceptions.InvalidRequestException) Operation(gov.cms.bfd.server.war.Operation) NoResultException(javax.persistence.NoResultException) RequestHeaders(gov.cms.bfd.server.war.commons.RequestHeaders) IBaseResource(org.hl7.fhir.instance.model.api.IBaseResource) LinkedList(java.util.LinkedList) Trace(com.newrelic.api.agent.Trace) Search(ca.uhn.fhir.rest.annotation.Search)

Example 10 with Value

use of org.hl7.fhir.utilities.graphql.Value in project beneficiary-fhir-data by CMSgov.

the class TransformerUtils method createCodeableConcept.

/**
 * @param rootResource the root FHIR {@link IAnyResource} that the resultant {@link
 *     CodeableConcept} will be contained in
 * @param ccwVariable the {@link CcwCodebookInterface} being coded
 * @param code the value to use for {@link Coding#getCode()} for the resulting (single) {@link
 *     Coding}, wrapped within the resulting {@link CodeableConcept}
 * @return the output {@link CodeableConcept} for the specified input values
 */
static CodeableConcept createCodeableConcept(IAnyResource rootResource, CcwCodebookInterface ccwVariable, Optional<?> code) {
    if (!code.isPresent())
        throw new IllegalArgumentException();
    Coding coding = createCoding(rootResource, ccwVariable, code.get());
    CodeableConcept concept = new CodeableConcept();
    concept.addCoding(coding);
    return concept;
}
Also used : Coding(org.hl7.fhir.dstu3.model.Coding) CodeableConcept(org.hl7.fhir.dstu3.model.CodeableConcept)

Aggregations

Test (org.junit.jupiter.api.Test)222 ArrayList (java.util.ArrayList)183 FHIRException (org.hl7.fhir.exceptions.FHIRException)107 List (java.util.List)97 DisplayName (org.junit.jupiter.api.DisplayName)96 XhtmlNode (org.hl7.fhir.utilities.xhtml.XhtmlNode)89 CodeableConcept (org.hl7.fhir.r4.model.CodeableConcept)85 Complex (org.hl7.fhir.r4.utils.formats.Turtle.Complex)70 Identifier (org.hl7.fhir.r4.model.Identifier)69 Test (org.junit.Test)66 Complex (org.hl7.fhir.dstu2016may.formats.RdfGenerator.Complex)64 Complex (org.hl7.fhir.dstu3.utils.formats.Turtle.Complex)54 IOException (java.io.IOException)52 Bundle (org.hl7.fhir.r4.model.Bundle)49 Coding (org.hl7.fhir.r4.model.Coding)49 ValueSet (org.hl7.fhir.r5.model.ValueSet)48 PathEngineException (org.hl7.fhir.exceptions.PathEngineException)46 Resource (org.hl7.fhir.r4.model.Resource)46 BigDecimal (java.math.BigDecimal)45 BundleEntryComponent (org.hl7.fhir.r4.model.Bundle.BundleEntryComponent)44