Search in sources :

Example 1 with Validated

use of org.hl7.gravity.refimpl.sdohexchange.dto.Validated in project beneficiary-fhir-data by CMSgov.

the class R4ExplanationOfBenefitResourceProviderIT method assertEobEquals.

/**
 * Compares two ExplanationOfBenefit objects in detail while working around serialization issues
 * like comparing "0" and "0.0" or creation differences like using "Quantity" vs "SimpleQuantity"
 *
 * @param expected the expected
 * @param actual the actual
 */
private static void assertEobEquals(ExplanationOfBenefit expected, ExplanationOfBenefit actual) {
    // ID in the bundle will have `ExplanationOfBenefit/` in front, so make sure the last bit
    // matches up
    assertTrue(actual.getId().endsWith(expected.getId()));
    // Clean them out so we can do a deep compare later
    actual.setId("");
    expected.setId("");
    // If there are any contained resources, they might have lastupdate times in them too
    assertEquals(expected.getContained().size(), actual.getContained().size());
    for (int i = 0; i < expected.getContained().size(); i++) {
        Resource expectedContained = expected.getContained().get(i);
        Resource actualContained = actual.getContained().get(i);
        expectedContained.getMeta().setLastUpdated(null);
        actualContained.getMeta().setLastUpdated(null);
        // TODO: HAPI seems to be inserting the `#` in the ID of the contained element.
        // This is incorrect according to the FHIR spec:
        // https://build.fhir.org/references.html#contained
        // This works around that problem
        assertEquals("#" + expectedContained.getId(), actualContained.getId());
        expectedContained.setId("");
        actualContained.setId("");
    }
    // Dates are not easy to compare so just make sure they are there
    assertNotNull(actual.getMeta().getLastUpdated());
    // We compared all of meta that we care about so get it out of the way
    expected.getMeta().setLastUpdated(null);
    actual.getMeta().setLastUpdated(null);
    // Created is required, but can't be compared
    assertNotNull(actual.getCreated());
    expected.setCreated(null);
    actual.setCreated(null);
    // Extensions may have `valueMoney` elements
    assertEquals(expected.getExtension().size(), actual.getExtension().size());
    for (int i = 0; i < expected.getExtension().size(); i++) {
        Extension expectedEx = expected.getExtension().get(i);
        Extension actualEx = actual.getExtension().get(i);
        // We have to deal with Money objects separately
        if (expectedEx.hasValue() && expectedEx.getValue() instanceof Money) {
            assertTrue(actualEx.getValue() instanceof Money);
            assertCurrencyEquals((Money) expectedEx.getValue(), (Money) actualEx.getValue());
            // Now remove since we validated so we can compare the rest directly
            expectedEx.setValue(null);
            actualEx.setValue(null);
        }
    }
    // SupportingInfo can have `valueQuantity` that has the 0 vs 0.0 issue
    assertEquals(expected.getSupportingInfo().size(), actual.getSupportingInfo().size());
    for (int i = 0; i < expected.getSupportingInfo().size(); i++) {
        SupportingInformationComponent expectedSup = expected.getSupportingInfo().get(i);
        SupportingInformationComponent actualSup = actual.getSupportingInfo().get(i);
        // We have to deal with Money objects separately
        if (expectedSup.hasValueQuantity()) {
            assertTrue(actualSup.hasValueQuantity());
            assertEquals(expectedSup.getValueQuantity().getValue().floatValue(), actualSup.getValueQuantity().getValue().floatValue(), 0.0);
            // Now remove since we validated so we can compare the rest directly
            expectedSup.setValue(null);
            actualSup.setValue(null);
        }
    }
    // line items
    assertEquals(expected.getItem().size(), actual.getItem().size());
    for (int i = 0; i < expected.getItem().size(); i++) {
        ItemComponent expectedItem = expected.getItem().get(i);
        ItemComponent actualItem = actual.getItem().get(i);
        // Compare value directly because SimpleQuantity vs Quantity can't be compared
        assertEquals(expectedItem.getQuantity().getValue().floatValue(), actualItem.getQuantity().getValue().floatValue(), 0.0);
        expectedItem.setQuantity(null);
        actualItem.setQuantity(null);
        assertEquals(expectedItem.getAdjudication().size(), actualItem.getAdjudication().size());
        for (int j = 0; j < expectedItem.getAdjudication().size(); j++) {
            AdjudicationComponent expectedAdj = expectedItem.getAdjudication().get(j);
            AdjudicationComponent actualAdj = actualItem.getAdjudication().get(j);
            // Here is where we start getting into trouble with "0" vs "0.0", so we do this manually
            if (expectedAdj.hasAmount()) {
                assertNotNull(actualAdj.getAmount());
                assertCurrencyEquals(expectedAdj.getAmount(), actualAdj.getAmount());
            } else {
                // If expected doesn't have an amount, actual shouldn't
                assertFalse(actualAdj.hasAmount());
            }
            // We just checked manually, so null them out and check the rest of the fields
            expectedAdj.setAmount(null);
            actualAdj.setAmount(null);
        }
    }
    // Total has the same problem with values
    assertEquals(expected.getTotal().size(), actual.getTotal().size());
    for (int i = 0; i < expected.getTotal().size(); i++) {
        TotalComponent expectedTot = expected.getTotal().get(i);
        TotalComponent actualTot = actual.getTotal().get(i);
        if (expectedTot.hasAmount()) {
            assertNotNull(actualTot.getAmount());
            assertCurrencyEquals(expectedTot.getAmount(), actualTot.getAmount());
        } else {
            // If expected doesn't have an amount, actual shouldn't
            assertFalse(actualTot.hasAmount());
        }
        expectedTot.setAmount(null);
        actualTot.setAmount(null);
    }
    // Benefit Balance Financial components
    assertEquals(expected.getBenefitBalance().size(), actual.getBenefitBalance().size());
    for (int i = 0; i < expected.getBenefitBalance().size(); i++) {
        BenefitBalanceComponent expectedBen = expected.getBenefitBalance().get(i);
        BenefitBalanceComponent actualBen = actual.getBenefitBalance().get(i);
        assertEquals(expectedBen.getFinancial().size(), actualBen.getFinancial().size());
        for (int j = 0; j < expectedBen.getFinancial().size(); j++) {
            BenefitComponent expectedFinancial = expectedBen.getFinancial().get(j);
            BenefitComponent actualFinancial = actualBen.getFinancial().get(j);
            // Are we dealing with Money?
            if (expectedFinancial.hasUsedMoney()) {
                assertNotNull(actualFinancial.getUsedMoney());
                assertCurrencyEquals(expectedFinancial.getUsedMoney(), actualFinancial.getUsedMoney());
                // Clean up
                expectedFinancial.setUsed(null);
                actualFinancial.setUsed(null);
            }
        }
    }
    // As does payment
    if (expected.hasPayment()) {
        assertTrue(actual.hasPayment());
        assertCurrencyEquals(expected.getPayment().getAmount(), actual.getPayment().getAmount());
    } else {
        // If expected doesn't have an amount, actual shouldn't
        assertFalse(actual.hasPayment());
    }
    expected.getPayment().setAmount(null);
    actual.getPayment().setAmount(null);
    // Now for the grand finale, we can do an `equalsDeep` on the rest
    assertTrue(expected.equalsDeep(actual));
}
Also used : Extension(org.hl7.fhir.r4.model.Extension) TotalComponent(org.hl7.fhir.r4.model.ExplanationOfBenefit.TotalComponent) Money(org.hl7.fhir.r4.model.Money) SupportingInformationComponent(org.hl7.fhir.r4.model.ExplanationOfBenefit.SupportingInformationComponent) ItemComponent(org.hl7.fhir.r4.model.ExplanationOfBenefit.ItemComponent) AdjudicationComponent(org.hl7.fhir.r4.model.ExplanationOfBenefit.AdjudicationComponent) IBaseResource(org.hl7.fhir.instance.model.api.IBaseResource) Resource(org.hl7.fhir.r4.model.Resource) BenefitBalanceComponent(org.hl7.fhir.r4.model.ExplanationOfBenefit.BenefitBalanceComponent) BenefitComponent(org.hl7.fhir.r4.model.ExplanationOfBenefit.BenefitComponent)

Example 2 with Validated

use of org.hl7.gravity.refimpl.sdohexchange.dto.Validated in project kindling by HL7.

the class ProfileGenerator method produceOpParam.

private void produceOpParam(String path, List<OperationDefinitionParameterComponent> opd, OperationParameter p, OperationParameterUse defUse) throws Exception {
    OperationDefinitionParameterComponent pp = new OperationDefinitionParameterComponent();
    pp.setName(p.getName());
    if (path.contains("."))
        pp.setUse(defUse);
    else if (p.getUse().equals("in"))
        pp.setUse(OperationParameterUse.IN);
    else if (p.getUse().equals("out"))
        pp.setUse(OperationParameterUse.OUT);
    else
        // but this is validated elsewhere
        throw new Exception("Unable to determine parameter use: " + p.getUse() + " at " + path + "." + p.getName());
    pp.setDocumentation(preProcessMarkdown(p.getDoc(), "Operation Parameter Doco"));
    pp.setMin(p.getMin());
    pp.setMax(p.getMax());
    if (p.getBs() != null) {
        if (p.getBs().hasMax())
            throw new Error("Max binding not handled yet");
        pp.setBinding(new OperationDefinitionParameterBindingComponent().setStrength(p.getBs().getStrength()).setValueSet(buildValueSetReference(p.getBs())));
        if (!Utilities.noString(p.getBinding().getName())) {
            pp.getBinding().addExtension("http://hl7.org/fhir/StructureDefinition/elementdefinition-bindingName", new StringType(p.getBinding().getName()));
        }
    }
    if (!Utilities.noString(p.getProfile())) {
        pp.addTargetProfile(p.getProfile());
    }
    opd.add(pp);
    if (p.getFhirType().equals("Tuple")) {
        for (OperationParameter part : p.getParts()) {
            produceOpParam(path + "." + p.getName(), pp.getPart(), part, pp.getUse());
        }
    } else {
        List<TypeRef> trs = new TypeParser(version.toCode()).parse(p.getFhirType(), false, null, null, false);
        if (trs.size() > 1) {
            if (p.getSearchType() != null)
                pp.setSearchType(SearchParamType.fromCode(p.getSearchType()));
            pp.setType(Enumerations.FHIRAllTypes.fromCode("Element"));
            for (TypeRef tr : trs) {
                pp.addExtension(ToolingExtensions.EXT_ALLOWED_TYPE, new UriType(tr.getName()));
                if (tr.getParams().size() > 0)
                    throw new Error("Multiple types for an operation parameter, where one is a reference, is not supported by the build tools");
            }
        } else {
            TypeRef tr = trs.get(0);
            if (definitions.getConstraints().containsKey(tr.getName())) {
                ProfiledType pt = definitions.getConstraints().get(tr.getName());
                pp.setType(Enumerations.FHIRAllTypes.fromCode(pt.getBaseType().equals("*") ? "Type" : pt.getBaseType()));
                pp.addTargetProfile("http://hl7.org/fhir/StructureDefinition/" + pt.getName());
            } else {
                if (p.getSearchType() != null)
                    pp.setSearchType(SearchParamType.fromCode(p.getSearchType()));
                pp.setType(Enumerations.FHIRAllTypes.fromCode(tr.getName().equals("*") ? "Type" : tr.getName()));
                if (tr.getParams().size() == 1 && !tr.getParams().get(0).equals("Any"))
                    pp.addTargetProfile("http://hl7.org/fhir/StructureDefinition/" + tr.getParams().get(0));
            }
        }
    }
}
Also used : TypeParser(org.hl7.fhir.definitions.parsers.TypeParser) ProfiledType(org.hl7.fhir.definitions.model.ProfiledType) StringType(org.hl7.fhir.r5.model.StringType) TypeRef(org.hl7.fhir.definitions.model.TypeRef) OperationDefinitionParameterBindingComponent(org.hl7.fhir.r5.model.OperationDefinition.OperationDefinitionParameterBindingComponent) OperationParameter(org.hl7.fhir.definitions.model.OperationParameter) FHIRFormatError(org.hl7.fhir.exceptions.FHIRFormatError) FHIRException(org.hl7.fhir.exceptions.FHIRException) URISyntaxException(java.net.URISyntaxException) OperationDefinitionParameterComponent(org.hl7.fhir.r5.model.OperationDefinition.OperationDefinitionParameterComponent) UriType(org.hl7.fhir.r5.model.UriType)

Example 3 with Validated

use of org.hl7.gravity.refimpl.sdohexchange.dto.Validated in project Gravity-SDOH-Exchange-RI by FHIR.

the class PersonalCharacteristicsService method createSexGenderBundleFactory.

private PersonalCharacteristicBundleFactory createSexGenderBundleFactory(NewPersonalCharacteristicDto dto) {
    RecordedSexGenderBundleFactory genderIdentityBundleFactory = new RecordedSexGenderBundleFactory(dto.getType(), dto.getMethod(), SexGenderCode.fromCode(dto.getValue()));
    genderIdentityBundleFactory.setValueDetail(dto.getValueDetail());
    // The derived from file must be set but this is validated right in the bundle factory.
    if (dto.getDerivedFrom() != null) {
        genderIdentityBundleFactory.setDerivedFromFileName(dto.getDerivedFrom().getName());
        genderIdentityBundleFactory.setDerivedFromFile(Base64.getDecoder().decode(dto.getDerivedFrom().getBase64Content()));
    }
    return genderIdentityBundleFactory;
}
Also used : RecordedSexGenderBundleFactory(org.hl7.gravity.refimpl.sdohexchange.fhir.factory.characteristic.RecordedSexGenderBundleFactory)

Example 4 with Validated

use of org.hl7.gravity.refimpl.sdohexchange.dto.Validated in project org.hl7.fhir.core by hapifhir.

the class RdfParser method composeTestScriptTestScriptMetadataCapabilityComponent.

protected void composeTestScriptTestScriptMetadataCapabilityComponent(Complex parent, String parentType, String name, TestScript.TestScriptMetadataCapabilityComponent element, int index) {
    if (element == null)
        return;
    Complex t;
    if (Utilities.noString(parentType))
        t = parent;
    else {
        t = parent.predicate("fhir:" + parentType + '.' + name);
    }
    composeBackboneElement(t, "capability", name, element, index);
    if (element.hasRequiredElement())
        composeBoolean(t, "TestScript", "required", element.getRequiredElement(), -1);
    if (element.hasValidatedElement())
        composeBoolean(t, "TestScript", "validated", element.getValidatedElement(), -1);
    if (element.hasDescriptionElement())
        composeString(t, "TestScript", "description", element.getDescriptionElement(), -1);
    for (int i = 0; i < element.getOrigin().size(); i++) composeInteger(t, "TestScript", "origin", element.getOrigin().get(i), i);
    if (element.hasDestinationElement())
        composeInteger(t, "TestScript", "destination", element.getDestinationElement(), -1);
    for (int i = 0; i < element.getLink().size(); i++) composeUri(t, "TestScript", "link", element.getLink().get(i), i);
    if (element.hasCapabilitiesElement())
        composeCanonical(t, "TestScript", "capabilities", element.getCapabilitiesElement(), -1);
}
Also used : Complex(org.hl7.fhir.r4.utils.formats.Turtle.Complex)

Example 5 with Validated

use of org.hl7.gravity.refimpl.sdohexchange.dto.Validated in project org.hl7.fhir.core by hapifhir.

the class SHCParser method parse.

public List<NamedElement> parse(InputStream stream) throws IOException, FHIRFormatError, DefinitionException, FHIRException {
    List<NamedElement> res = new ArrayList<>();
    String src = TextFile.streamToString(stream).trim();
    List<String> list = new ArrayList<>();
    String pfx = null;
    if (src.startsWith("{")) {
        JsonObject json = JsonTrackingParser.parseJson(src);
        if (checkProperty(json, "$", "verifiableCredential", true, "Array")) {
            pfx = "verifiableCredential";
            JsonArray arr = json.getAsJsonArray("verifiableCredential");
            int i = 0;
            for (JsonElement e : arr) {
                if (!(e instanceof JsonPrimitive)) {
                    logError(line(e), col(e), "$.verifiableCredential[" + i + "]", IssueType.STRUCTURE, "Wrong Property verifiableCredential in JSON Payload. Expected : String but found " + JSONUtil.type(e), IssueSeverity.ERROR);
                } else {
                    list.add(e.getAsString());
                }
                i++;
            }
        } else {
            return res;
        }
    } else {
        list.add(src);
    }
    int c = 0;
    for (String ssrc : list) {
        String prefix = pfx == null ? "" : pfx + "[" + Integer.toString(c) + "].";
        c++;
        JWT jwt = null;
        try {
            jwt = decodeJWT(ssrc);
        } catch (Exception e) {
            logError(1, 1, prefix + "JWT", IssueType.INVALID, "Unable to decode JWT token", IssueSeverity.ERROR);
            return res;
        }
        map = jwt.map;
        checkNamedProperties(jwt.getPayload(), prefix + "payload", "iss", "nbf", "vc");
        checkProperty(jwt.getPayload(), prefix + "payload", "iss", true, "String");
        logError(1, 1, prefix + "JWT", IssueType.INFORMATIONAL, "The FHIR Validator does not check the JWT signature " + "(see https://demo-portals.smarthealth.cards/VerifierPortal.html or https://github.com/smart-on-fhir/health-cards-dev-tools) (Issuer = '" + jwt.getPayload().get("iss").getAsString() + "')", IssueSeverity.INFORMATION);
        checkProperty(jwt.getPayload(), prefix + "payload", "nbf", true, "Number");
        JsonObject vc = jwt.getPayload().getAsJsonObject("vc");
        if (vc == null) {
            logError(1, 1, "JWT", IssueType.STRUCTURE, "Unable to find property 'vc' in the payload", IssueSeverity.ERROR);
            return res;
        }
        String path = prefix + "payload.vc";
        checkNamedProperties(vc, path, "type", "credentialSubject");
        if (!checkProperty(vc, path, "type", true, "Array")) {
            return res;
        }
        JsonArray type = vc.getAsJsonArray("type");
        int i = 0;
        for (JsonElement e : type) {
            if (!(e instanceof JsonPrimitive)) {
                logError(line(e), col(e), path + ".type[" + i + "]", IssueType.STRUCTURE, "Wrong Property Type in JSON Payload. Expected : String but found " + JSONUtil.type(e), IssueSeverity.ERROR);
            } else {
                types.add(e.getAsString());
            }
            i++;
        }
        if (!types.contains("https://smarthealth.cards#health-card")) {
            logError(line(vc), col(vc), path, IssueType.STRUCTURE, "Card does not claim to be of type https://smarthealth.cards#health-card, cannot validate", IssueSeverity.ERROR);
            return res;
        }
        if (!checkProperty(vc, path, "credentialSubject", true, "Object")) {
            return res;
        }
        JsonObject cs = vc.getAsJsonObject("credentialSubject");
        path = path + ".credentialSubject";
        if (!checkProperty(cs, path, "fhirVersion", true, "String")) {
            return res;
        }
        JsonElement fv = cs.get("fhirVersion");
        if (!VersionUtilities.versionsCompatible(context.getVersion(), fv.getAsString())) {
            logError(line(fv), col(fv), path + ".fhirVersion", IssueType.STRUCTURE, "Card claims to be of version " + fv.getAsString() + ", cannot be validated against version " + context.getVersion(), IssueSeverity.ERROR);
            return res;
        }
        if (!checkProperty(cs, path, "fhirBundle", true, "Object")) {
            return res;
        }
        // ok. all checks passed, we can now validate the bundle
        Element e = jsonParser.parse(cs.getAsJsonObject("fhirBundle"), map);
        if (e != null) {
            res.add(new NamedElement(path, e));
        }
    }
    return res;
}
Also used : JsonPrimitive(com.google.gson.JsonPrimitive) JsonElement(com.google.gson.JsonElement) ArrayList(java.util.ArrayList) JsonObject(com.google.gson.JsonObject) DefinitionException(org.hl7.fhir.exceptions.DefinitionException) DataFormatException(java.util.zip.DataFormatException) IOException(java.io.IOException) FHIRException(org.hl7.fhir.exceptions.FHIRException) JsonArray(com.google.gson.JsonArray) JsonElement(com.google.gson.JsonElement)

Aggregations

ArrayList (java.util.ArrayList)7 FHIRException (org.hl7.fhir.exceptions.FHIRException)4 Resource (org.hl7.fhir.r4.model.Resource)4 IOException (java.io.IOException)3 List (java.util.List)3 ResourceNotFoundException (ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException)2 JsonArray (com.google.gson.JsonArray)2 JsonElement (com.google.gson.JsonElement)2 JsonObject (com.google.gson.JsonObject)2 JsonPrimitive (com.google.gson.JsonPrimitive)2 DataFormatException (java.util.zip.DataFormatException)2 DefinitionException (org.hl7.fhir.exceptions.DefinitionException)2 Bundle (org.hl7.fhir.r4.model.Bundle)2 Consent (org.hl7.fhir.r4.model.Consent)2 IdType (org.hl7.fhir.r4.model.IdType)2 Organization (org.hl7.fhir.r4.model.Organization)2 Patient (org.hl7.fhir.r4.model.Patient)2 ServiceRequest (org.hl7.fhir.r4.model.ServiceRequest)2 Task (org.hl7.fhir.r4.model.Task)2 UriType (org.hl7.fhir.r5.model.UriType)2