Search in sources :

Example 21 with FHIRVersion

use of org.hl7.fhir.r5.model.Enumerations.FHIRVersion 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)

Example 22 with FHIRVersion

use of org.hl7.fhir.r5.model.Enumerations.FHIRVersion in project pathling by aehrc.

the class ConformanceProvider method getServerConformance.

@Override
@Metadata(cacheMillis = 0)
public CapabilityStatement getServerConformance(@Nullable final HttpServletRequest httpServletRequest, @Nullable final RequestDetails requestDetails) {
    log.debug("Received request for server capabilities");
    final CapabilityStatement capabilityStatement = new CapabilityStatement();
    capabilityStatement.setUrl(getCapabilityUri());
    capabilityStatement.setVersion(version.getBuildVersion().orElse(UNKNOWN_VERSION));
    capabilityStatement.setTitle("Pathling FHIR API");
    capabilityStatement.setName("pathling-fhir-api");
    capabilityStatement.setStatus(PublicationStatus.ACTIVE);
    capabilityStatement.setExperimental(true);
    capabilityStatement.setPublisher("Australian e-Health Research Centre, CSIRO");
    capabilityStatement.setCopyright("Dedicated to the public domain via CC0: https://creativecommons.org/publicdomain/zero/1.0/");
    capabilityStatement.setKind(CapabilityStatementKind.INSTANCE);
    final CapabilityStatementSoftwareComponent software = new CapabilityStatementSoftwareComponent(new StringType("Pathling"));
    software.setVersion(version.getDescriptiveVersion().orElse(UNKNOWN_VERSION));
    capabilityStatement.setSoftware(software);
    final CapabilityStatementImplementationComponent implementation = new CapabilityStatementImplementationComponent(new StringType(configuration.getImplementationDescription()));
    final Optional<String> serverBase = getServerBase(Optional.ofNullable(httpServletRequest));
    serverBase.ifPresent(implementation::setUrl);
    capabilityStatement.setImplementation(implementation);
    capabilityStatement.setFhirVersion(FHIRVersion._4_0_1);
    capabilityStatement.setFormat(Arrays.asList(new CodeType("json"), new CodeType("xml")));
    capabilityStatement.setRest(buildRestComponent());
    return capabilityStatement;
}
Also used : StringType(org.hl7.fhir.r4.model.StringType) CapabilityStatementImplementationComponent(org.hl7.fhir.r4.model.CapabilityStatement.CapabilityStatementImplementationComponent) CapabilityStatement(org.hl7.fhir.r4.model.CapabilityStatement) CapabilityStatementSoftwareComponent(org.hl7.fhir.r4.model.CapabilityStatement.CapabilityStatementSoftwareComponent) CodeType(org.hl7.fhir.r4.model.CodeType) Metadata(ca.uhn.fhir.rest.annotation.Metadata)

Example 23 with FHIRVersion

use of org.hl7.fhir.r5.model.Enumerations.FHIRVersion in project eCRNow by drajer-health.

the class LaunchController method setStartAndEndDates.

public void setStartAndEndDates(ClientDetails clientDetails, LaunchDetails launchDetails, IBaseResource encounter) {
    String fhirVersion = launchDetails.getFhirVersion();
    // This is explicitly set to null so that when we don't have the encounter
    // period present, we can default it to launch immediately.
    launchDetails.setStartDate(null);
    launchDetails.setEndDate(null);
    if (fhirVersion.equalsIgnoreCase(FhirVersionEnum.R4.toString())) {
        org.hl7.fhir.r4.model.Encounter r4Encounter = (org.hl7.fhir.r4.model.Encounter) encounter;
        if (r4Encounter != null) {
            Period r4Period = r4Encounter.getPeriod();
            if (r4Period != null) {
                if (r4Period.getStart() != null) {
                    launchDetails.setStartDate(r4Period.getStart());
                } else {
                    launchDetails.setStartDate(getDate(clientDetails.getEncounterStartThreshold()));
                }
                if (r4Period.getEnd() != null) {
                    launchDetails.setEndDate(r4Period.getEnd());
                } else {
                    launchDetails.setEndDate(getDate(clientDetails.getEncounterEndThreshold()));
                }
            }
        }
        return;
    }
    if (fhirVersion.equalsIgnoreCase(FhirVersionEnum.DSTU2.toString())) {
        Encounter dstu2Encounter = (Encounter) encounter;
        if (dstu2Encounter != null) {
            PeriodDt dstu2Period = dstu2Encounter.getPeriod();
            if (dstu2Period != null) {
                if (dstu2Period.getStart() != null) {
                    launchDetails.setStartDate(dstu2Period.getStart());
                } else {
                    launchDetails.setStartDate(getDate(clientDetails.getEncounterStartThreshold()));
                }
                if (dstu2Period.getEnd() != null) {
                    launchDetails.setEndDate(dstu2Period.getEnd());
                } else {
                    launchDetails.setEndDate(getDate(clientDetails.getEncounterEndThreshold()));
                }
            }
        }
    }
}
Also used : PeriodDt(ca.uhn.fhir.model.dstu2.composite.PeriodDt) Encounter(ca.uhn.fhir.model.dstu2.resource.Encounter) Period(org.hl7.fhir.r4.model.Period)

Example 24 with FHIRVersion

use of org.hl7.fhir.r5.model.Enumerations.FHIRVersion in project eCRNow by drajer-health.

the class LaunchController method invokeSystemLaunch.

@CrossOrigin
@PostMapping(value = "/api/systemLaunch")
public String invokeSystemLaunch(@RequestBody SystemLaunch systemLaunch, HttpServletRequest request, HttpServletResponse response) throws IOException {
    logger.info("System launch request received for patientId: {} and encounterId: {}", systemLaunch.getPatientId(), systemLaunch.getEncounterId());
    ClientDetails clientDetails = clientDetailsService.getClientDetailsByUrl(systemLaunch.getFhirServerURL());
    String requestIdHeadervalue = request.getHeader("X-Request-ID");
    if (clientDetails != null) {
        String fhirVersion = "";
        String tokenEndpoint = "";
        JSONObject object = authorization.getMetadata(systemLaunch.getFhirServerURL() + "/metadata");
        if (object != null) {
            logger.info("Reading Metadata information");
            JSONObject security = (JSONObject) object.getJSONArray("rest").get(0);
            JSONObject sec = security.getJSONObject("security");
            JSONObject extension = (JSONObject) sec.getJSONArray(EXTENSION).get(0);
            JSONArray innerExtension = extension.getJSONArray(EXTENSION);
            if (object.getString(FHIR_VERSION).equals("1.(.*).(.*)")) {
                fhirVersion = FhirVersionEnum.DSTU2.toString();
            }
            if (object.getString(FHIR_VERSION).matches("4.(.*).(.*)")) {
                fhirVersion = FhirVersionEnum.R4.toString();
            }
            for (int i = 0; i < innerExtension.length(); i++) {
                JSONObject urlExtension = innerExtension.getJSONObject(i);
                if (urlExtension.getString("url").equals("token")) {
                    logger.info("Token URL::::: {}", urlExtension.getString(VALUE_URI));
                    tokenEndpoint = urlExtension.getString(VALUE_URI);
                    clientDetails.setTokenURL(tokenEndpoint);
                }
            }
        }
        JSONObject tokenResponse = tokenScheduler.getSystemAccessToken(clientDetails);
        if (tokenResponse != null) {
            if (systemLaunch.getPatientId() != null) {
                if (!checkWithExistingPatientAndEncounter(systemLaunch.getPatientId(), systemLaunch.getEncounterId(), systemLaunch.getFhirServerURL())) {
                    LaunchDetails launchDetails = new LaunchDetails();
                    launchDetails.setAccessToken(tokenResponse.getString(ACCESS_TOKEN));
                    launchDetails.setAssigningAuthorityId(clientDetails.getAssigningAuthorityId());
                    launchDetails.setClientId(clientDetails.getClientId());
                    launchDetails.setClientSecret(clientDetails.getClientSecret());
                    launchDetails.setScope(clientDetails.getScopes());
                    launchDetails.setDirectHost(clientDetails.getDirectHost());
                    launchDetails.setDirectPwd(clientDetails.getDirectPwd());
                    launchDetails.setSmtpPort(clientDetails.getSmtpPort());
                    launchDetails.setImapPort(clientDetails.getImapPort());
                    launchDetails.setDirectRecipient(clientDetails.getDirectRecipientAddress());
                    launchDetails.setDirectUser(clientDetails.getDirectUser());
                    launchDetails.setEhrServerURL(clientDetails.getFhirServerBaseURL());
                    launchDetails.setEncounterId(systemLaunch.getEncounterId());
                    launchDetails.setExpiry(tokenResponse.getInt(EXPIRES_IN));
                    launchDetails.setFhirVersion(fhirVersion);
                    launchDetails.setIsCovid(clientDetails.getIsCovid());
                    launchDetails.setLaunchPatientId(systemLaunch.getPatientId());
                    launchDetails.setTokenUrl(clientDetails.getTokenURL());
                    launchDetails.setSetId(systemLaunch.getPatientId() + "|" + systemLaunch.getEncounterId());
                    launchDetails.setVersionNumber(1);
                    launchDetails.setIsSystem(clientDetails.getIsSystem());
                    launchDetails.setDebugFhirQueryAndEicr(clientDetails.getDebugFhirQueryAndEicr());
                    launchDetails.setRequireAud(clientDetails.getRequireAud());
                    launchDetails.setRestAPIURL(clientDetails.getRestAPIURL());
                    launchDetails.setxRequestId(requestIdHeadervalue);
                    launchDetails.setProcessingState(LaunchDetails.getString(ProcessingStatus.In_Progress));
                    if (systemLaunch.getValidationMode() != null) {
                        launchDetails.setValidationMode(systemLaunch.getValidationMode());
                    }
                    if (tokenResponse.get(EXPIRES_IN) != null) {
                        Integer expiresInSec = (Integer) tokenResponse.get(EXPIRES_IN);
                        Instant expireInstantTime = new Date().toInstant().plusSeconds(new Long(expiresInSec));
                        launchDetails.setTokenExpiryDateTime(new Date().from(expireInstantTime));
                    }
                    launchDetails.setLaunchType("SystemLaunch");
                    IBaseResource encounter = getEncounterById(launchDetails);
                    setStartAndEndDates(clientDetails, launchDetails, encounter);
                    clientDetailsService.saveOrUpdate(clientDetails);
                    saveLaunchDetails(launchDetails);
                    response.setStatus(HttpServletResponse.SC_ACCEPTED);
                    logger.info("System launch was successful for patientId: {} and encounterId: {} with launchId: {}", launchDetails.getLaunchPatientId(), launchDetails.getEncounterId(), launchDetails.getId());
                } else {
                    throw new ResponseStatusException(HttpStatus.CONFLICT, "Launch Context is already present for Patient:::::" + systemLaunch.getPatientId());
                }
            } else {
                logger.error("Please provide Patient Id and Encounter Id");
                throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Please provide Patient Id and Encounter Id");
            }
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Error in Launching the App");
        }
    } else {
        throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Unrecognized client");
    }
    return "App is launched successfully";
}
Also used : ClientDetails(com.drajer.sof.model.ClientDetails) LaunchDetails(com.drajer.sof.model.LaunchDetails) JSONObject(org.json.JSONObject) Instant(java.time.Instant) JSONArray(org.json.JSONArray) IBaseResource(org.hl7.fhir.instance.model.api.IBaseResource) ResponseStatusException(org.springframework.web.server.ResponseStatusException) Date(java.util.Date)

Example 25 with FHIRVersion

use of org.hl7.fhir.r5.model.Enumerations.FHIRVersion in project CRD by HL7-DaVinci.

the class DataController method getFile.

/**
 * Retrieve a file from the File Store.
 * @param topic (case sensitive)
 * @param fhirVersion (converted to uppercase)
 * @param fileName (case sensitive)
 * @param noconvert
 * @return
 * @throws IOException
 */
@GetMapping(path = "/files/{topic}/{fhirVersion}/{fileName}")
public ResponseEntity<Resource> getFile(@PathVariable String topic, @PathVariable String fhirVersion, @PathVariable String fileName, @RequestParam(required = false) boolean noconvert) throws IOException {
    fhirVersion = fhirVersion.toUpperCase();
    logger.info("GET /files/" + topic + "/" + fhirVersion + "/" + fileName);
    FileResource fileResource = fileStore.getFile(topic, fileName, fhirVersion, !noconvert);
    return processFileResource(fileResource);
}
Also used : FileResource(org.hl7.davinci.endpoint.files.FileResource)

Aggregations

ArrayList (java.util.ArrayList)10 IBaseResource (org.hl7.fhir.instance.model.api.IBaseResource)9 JsonObject (com.google.gson.JsonObject)8 Date (java.util.Date)8 IOException (java.io.IOException)7 FhirContext (ca.uhn.fhir.context.FhirContext)6 JsonArray (com.google.gson.JsonArray)6 HashMap (java.util.HashMap)5 FhirVersionEnum (ca.uhn.fhir.context.FhirVersionEnum)4 IParser (ca.uhn.fhir.parser.IParser)4 Complex (org.hl7.fhir.r4.utils.formats.Turtle.Complex)4 CommaSeparatedStringBuilder (org.hl7.fhir.utilities.CommaSeparatedStringBuilder)4 JsonPrimitive (com.google.gson.JsonPrimitive)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)3 Complex (org.hl7.fhir.dstu2016may.formats.RdfGenerator.Complex)3 DefinitionException (org.hl7.fhir.exceptions.DefinitionException)3 FHIRException (org.hl7.fhir.exceptions.FHIRException)3 Bundle (org.hl7.fhir.r4.model.Bundle)3 StructureDefinition (org.hl7.fhir.r5.model.StructureDefinition)3 CascadingDeleteInterceptor (ca.uhn.fhir.jpa.interceptor.CascadingDeleteInterceptor)2