Search in sources :

Example 46 with ParametersParameterComponent

use of org.hl7.fhir.r4.model.Parameters.ParametersParameterComponent in project summary-care-record-api by NHSDigital.

the class AcsService method getPermission.

private static AcsPermission getPermission(ParametersParameterComponent parameter) {
    Coding coding = (Coding) parameter.getPart().stream().filter(p -> PERMISSION_CODE_PART_NAME.equals(p.getName())).filter(p -> PERMISSION_CODE_SYSTEM.equals(((Coding) p.getValue()).getSystem())).findFirst().get().getValue();
    String permissionValue = coding.getCode();
    return AcsPermission.fromValue(permissionValue);
}
Also used : SpineClientContract(uk.nhs.adaptors.scr.clients.spine.SpineClientContract) IdentityServiceContract(uk.nhs.adaptors.scr.clients.identity.IdentityServiceContract) Mustache(com.github.mustachejava.Mustache) RequiredArgsConstructor(lombok.RequiredArgsConstructor) Response(uk.nhs.adaptors.scr.clients.spine.SpineHttpClient.Response) Autowired(org.springframework.beans.factory.annotation.Autowired) RequestData(uk.nhs.adaptors.scr.models.RequestData) OffsetDateTime.now(java.time.OffsetDateTime.now) FhirParser(uk.nhs.adaptors.scr.components.FhirParser) AcsParams(uk.nhs.adaptors.scr.models.AcsParams) AcsPermission(uk.nhs.adaptors.scr.models.AcsPermission) BadRequestException(uk.nhs.adaptors.scr.exceptions.BadRequestException) UserInfo(uk.nhs.adaptors.scr.clients.identity.UserInfo) Document(org.w3c.dom.Document) SpineConfiguration(uk.nhs.adaptors.scr.config.SpineConfiguration) TemplateUtils.loadTemplate(uk.nhs.adaptors.scr.utils.TemplateUtils.loadTemplate) ParametersParameterComponent(org.hl7.fhir.r4.model.Parameters.ParametersParameterComponent) TemplateUtils.fillTemplate(uk.nhs.adaptors.scr.utils.TemplateUtils.fillTemplate) ScrConfiguration(uk.nhs.adaptors.scr.config.ScrConfiguration) CORRELATION_ID_MDC_KEY(uk.nhs.adaptors.scr.config.ConversationIdFilter.CORRELATION_ID_MDC_KEY) Slf4j(lombok.extern.slf4j.Slf4j) Component(org.springframework.stereotype.Component) Coding(org.hl7.fhir.r4.model.Coding) MDC(org.slf4j.MDC) DateTimeFormatter(java.time.format.DateTimeFormatter) UTC(java.time.ZoneOffset.UTC) Parameters(org.hl7.fhir.r4.model.Parameters) Coding(org.hl7.fhir.r4.model.Coding)

Example 47 with ParametersParameterComponent

use of org.hl7.fhir.r4.model.Parameters.ParametersParameterComponent in project pathling by aehrc.

the class ImportExecutor method readStringsFromUrl.

@Nonnull
private Dataset<String> readStringsFromUrl(@Nonnull final ParametersParameterComponent urlParam) {
    final String url = ((UrlType) urlParam.getValue()).getValueAsString();
    final String decodedUrl = URLDecoder.decode(url, StandardCharsets.UTF_8);
    final String convertedUrl = PersistenceScheme.convertS3ToS3aUrl(decodedUrl);
    final Dataset<String> jsonStrings;
    try {
        // Check that the user is authorized to execute the operation.
        accessRules.ifPresent(ar -> ar.checkCanImportFrom(convertedUrl));
        final FilterFunction<String> nonBlanks = s -> !s.isBlank();
        jsonStrings = spark.read().textFile(convertedUrl).filter(nonBlanks);
    } catch (final SecurityError e) {
        throw new InvalidUserInputError("Not allowed to import from URL: " + convertedUrl, e);
    } catch (final Exception e) {
        throw new InvalidUserInputError("Error reading from URL: " + convertedUrl, e);
    }
    return jsonStrings;
}
Also used : UrlType(org.hl7.fhir.r4.model.UrlType) URLDecoder(java.net.URLDecoder) Getter(lombok.Getter) Dataset(org.apache.spark.sql.Dataset) ResourceType(org.hl7.fhir.r4.model.Enumerations.ResourceType) UnsupportedResourceError(au.csiro.pathling.encoders.UnsupportedResourceError) FhirEncoders(au.csiro.pathling.encoders.FhirEncoders) AccessRules(au.csiro.pathling.io.AccessRules) IBaseResource(org.hl7.fhir.instance.model.api.IBaseResource) InvalidUserInputError(au.csiro.pathling.errors.InvalidUserInputError) SecurityError(au.csiro.pathling.errors.SecurityError) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) MapFunction(org.apache.spark.api.java.function.MapFunction) SparkSession(org.apache.spark.sql.SparkSession) ParametersParameterComponent(org.hl7.fhir.r4.model.Parameters.ParametersParameterComponent) IssueSeverity(org.hl7.fhir.r4.model.OperationOutcome.IssueSeverity) PersistenceScheme(au.csiro.pathling.io.PersistenceScheme) Collectors(java.util.stream.Collectors) Profile(org.springframework.context.annotation.Profile) FhirContextFactory(au.csiro.pathling.fhir.FhirContextFactory) StandardCharsets(java.nio.charset.StandardCharsets) OperationOutcomeIssueComponent(org.hl7.fhir.r4.model.OperationOutcome.OperationOutcomeIssueComponent) ExpressionEncoder(org.apache.spark.sql.catalyst.encoders.ExpressionEncoder) OperationOutcome(org.hl7.fhir.r4.model.OperationOutcome) ResourceParam(ca.uhn.fhir.rest.annotation.ResourceParam) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) Component(org.springframework.stereotype.Component) Database(au.csiro.pathling.io.Database) IssueType(org.hl7.fhir.r4.model.OperationOutcome.IssueType) Optional(java.util.Optional) Parameters(org.hl7.fhir.r4.model.Parameters) CodeType(org.hl7.fhir.r4.model.CodeType) Preconditions.checkUserInput(au.csiro.pathling.utilities.Preconditions.checkUserInput) FilterFunction(org.apache.spark.api.java.function.FilterFunction) InvalidUserInputError(au.csiro.pathling.errors.InvalidUserInputError) UrlType(org.hl7.fhir.r4.model.UrlType) SecurityError(au.csiro.pathling.errors.SecurityError) Nonnull(javax.annotation.Nonnull)

Example 48 with ParametersParameterComponent

use of org.hl7.fhir.r4.model.Parameters.ParametersParameterComponent in project pathling by aehrc.

the class ImportTest method buildImportParameters.

@SuppressWarnings("SameParameterValue")
@Nonnull
Parameters buildImportParameters(@Nonnull final URL jsonURL, @Nonnull final ResourceType resourceType, @Nonnull final ImportMode mode) {
    final Parameters parameters = buildImportParameters(jsonURL, resourceType);
    final ParametersParameterComponent sourceParam = parameters.getParameter().stream().filter(p -> p.getName().equals("source")).findFirst().orElseThrow();
    sourceParam.addPart().setName("mode").setValue(new CodeType(mode.getCode()));
    return parameters;
}
Also used : Parameters(org.hl7.fhir.r4.model.Parameters) CodeType(org.hl7.fhir.r4.model.CodeType) ParametersParameterComponent(org.hl7.fhir.r4.model.Parameters.ParametersParameterComponent) Nonnull(javax.annotation.Nonnull)

Example 49 with ParametersParameterComponent

use of org.hl7.fhir.r4.model.Parameters.ParametersParameterComponent in project pathling by aehrc.

the class ImportTest method buildImportParameters.

@SuppressWarnings("SameParameterValue")
@Nonnull
Parameters buildImportParameters(@Nonnull final URL jsonURL, @Nonnull final ResourceType resourceType) {
    final Parameters parameters = new Parameters();
    final ParametersParameterComponent sourceParam = parameters.addParameter().setName("source");
    sourceParam.addPart().setName("resourceType").setValue(new CodeType(resourceType.toCode()));
    sourceParam.addPart().setName("url").setValue(new UrlType(jsonURL.toExternalForm()));
    return parameters;
}
Also used : Parameters(org.hl7.fhir.r4.model.Parameters) CodeType(org.hl7.fhir.r4.model.CodeType) UrlType(org.hl7.fhir.r4.model.UrlType) ParametersParameterComponent(org.hl7.fhir.r4.model.Parameters.ParametersParameterComponent) Nonnull(javax.annotation.Nonnull)

Example 50 with ParametersParameterComponent

use of org.hl7.fhir.r4.model.Parameters.ParametersParameterComponent in project pathling by aehrc.

the class DockerImageTest method importDataAndQuery.

@Test
void importDataAndQuery() throws JSONException {
    try {
        // Get the token endpoint from the CapabilityStatement.
        final CapabilityStatement capabilities = getCapabilityStatement();
        final String tokenUrl = capabilities.getRest().stream().findFirst().map(rest -> ((UriType) rest.getSecurity().getExtensionByUrl("http://fhir-registry.smarthealthit.org/StructureDefinition/oauth-uris").getExtensionByUrl("token").getValue()).asStringValue()).orElseThrow();
        // Get an access token from the token endpoint.
        final HttpPost clientCredentialsGrant = new HttpPost(tokenUrl);
        final List<? extends NameValuePair> nameValuePairs = Arrays.asList(new BasicNameValuePair("grant_type", "client_credentials"), new BasicNameValuePair("client_id", CLIENT_ID), new BasicNameValuePair("client_secret", CLIENT_SECRET), new BasicNameValuePair("scope", REQUESTED_SCOPE));
        clientCredentialsGrant.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        log.info("Requesting client credentials grant");
        final String accessToken;
        try (final CloseableHttpResponse response = (CloseableHttpResponse) httpClient.execute(clientCredentialsGrant)) {
            assertThat(response.getStatusLine().getStatusCode()).withFailMessage("Client credentials grant did not succeed").isEqualTo(200);
            final InputStream clientCredentialsStream = response.getEntity().getContent();
            final Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
            final ClientCredentialsResponse ccResponse = gson.fromJson(new InputStreamReader(clientCredentialsStream), ClientCredentialsResponse.class);
            accessToken = ccResponse.getAccessToken();
        }
        // Create a request to the $import operation, referencing the NDJSON files we have loaded into
        // the staging area.
        final InputStream requestStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("import/SystemTest/request.Parameters.json");
        assertThat(requestStream).isNotNull();
        final HttpPost importRequest = new HttpPost("http://localhost:8091/fhir/$import");
        importRequest.setEntity(new InputStreamEntity(requestStream));
        importRequest.addHeader("Content-Type", "application/json");
        importRequest.addHeader("Accept", "application/fhir+json");
        importRequest.addHeader("Authorization", "Bearer " + accessToken);
        log.info("Sending import request");
        final OperationOutcome importOutcome;
        try (final CloseableHttpResponse response = (CloseableHttpResponse) httpClient.execute(importRequest)) {
            final InputStream importResponseStream = response.getEntity().getContent();
            importOutcome = (OperationOutcome) jsonParser.parseResource(importResponseStream);
            assertThat(response.getStatusLine().getStatusCode()).withFailMessage(importOutcome.getIssueFirstRep().getDiagnostics()).isEqualTo(200);
        }
        assertThat(importOutcome.getIssueFirstRep().getDiagnostics()).isEqualTo("Data import completed successfully");
        log.info("Import completed successfully");
        final Parameters inParams = new Parameters();
        // Set subject resource parameter.
        final ParametersParameterComponent subjectResourceParam = new ParametersParameterComponent();
        subjectResourceParam.setName("subjectResource");
        subjectResourceParam.setValue(new CodeType("Patient"));
        // Add aggregation, number of patients.
        final ParametersParameterComponent aggregationParam = new ParametersParameterComponent();
        aggregationParam.setName("aggregation");
        aggregationParam.setValue(new StringType("count()"));
        // Add grouping, has the patient been diagnosed with a chronic disease?
        final ParametersParameterComponent groupingParam = new ParametersParameterComponent();
        groupingParam.setName("grouping");
        groupingParam.setValue(new StringType("reverseResolve(Condition.subject)" + ".code" + ".memberOf('http://snomed.info/sct?fhir_vs=ecl/" + "^ 32570581000036105 : " + "<< 263502005 = << 90734009')"));
        // Add filter, females only.
        final ParametersParameterComponent filterParam = new ParametersParameterComponent();
        filterParam.setName("filter");
        filterParam.setValue(new StringType("gender = 'female'"));
        inParams.getParameter().add(subjectResourceParam);
        inParams.getParameter().add(aggregationParam);
        inParams.getParameter().add(groupingParam);
        inParams.getParameter().add(filterParam);
        // Send a request to the `$aggregate` operation on the FHIR server.
        final String requestString = jsonParser.encodeResourceToString(inParams);
        final HttpPost queryRequest = new HttpPost("http://localhost:8091/fhir/Patient/$aggregate");
        queryRequest.setEntity(new StringEntity(requestString));
        queryRequest.addHeader("Content-Type", "application/fhir+json");
        queryRequest.addHeader("Accept", "application/fhir+json");
        queryRequest.addHeader("Authorization", "Bearer " + accessToken);
        log.info("Sending query request");
        try (final CloseableHttpResponse response = (CloseableHttpResponse) httpClient.execute(queryRequest)) {
            final int statusCode = response.getStatusLine().getStatusCode();
            final InputStream queryResponseStream = response.getEntity().getContent();
            if (statusCode == 200) {
                final StringWriter writer = new StringWriter();
                IOUtils.copy(queryResponseStream, writer, StandardCharsets.UTF_8);
                assertJson("responses/DockerImageTest/importDataAndQuery.Parameters.json", writer.toString());
            } else {
                captureLogs();
                final OperationOutcome opOutcome = (OperationOutcome) jsonParser.parseResource(queryResponseStream);
                assertEquals(200, statusCode, opOutcome.getIssueFirstRep().getDiagnostics());
            }
        }
    } catch (final Exception e) {
        captureLogs();
    } finally {
        stopContainer(dockerClient, fhirServerContainerId);
        fhirServerContainerId = null;
        getRuntime().removeShutdownHook(shutdownHook);
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) BeforeEach(org.junit.jupiter.api.BeforeEach) CreateContainerResponse(com.github.dockerjava.api.command.CreateContainerResponse) Arrays(java.util.Arrays) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) URL(java.net.URL) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) GsonBuilder(com.google.gson.GsonBuilder) DockerClient(com.github.dockerjava.api.DockerClient) FhirContext(ca.uhn.fhir.context.FhirContext) JSONException(org.json.JSONException) CapabilityStatement(org.hl7.fhir.r4.model.CapabilityStatement) Gson(com.google.gson.Gson) StringType(org.hl7.fhir.r4.model.StringType) ExposedPort(com.github.dockerjava.api.model.ExposedPort) PortBinding(com.github.dockerjava.api.model.PortBinding) Binding(com.github.dockerjava.api.model.Ports.Binding) Tag(org.junit.jupiter.api.Tag) Awaitility.await(org.awaitility.Awaitility.await) StringEntity(org.apache.http.entity.StringEntity) StandardCharsets(java.nio.charset.StandardCharsets) Test(org.junit.jupiter.api.Test) IOUtils(org.apache.commons.io.IOUtils) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) HttpGet(org.apache.http.client.methods.HttpGet) ResultCallback(com.github.dockerjava.api.async.ResultCallback) UriType(org.hl7.fhir.r4.model.UriType) NameValuePair(org.apache.http.NameValuePair) HttpClients(org.apache.http.impl.client.HttpClients) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) DockerClientBuilder(com.github.dockerjava.core.DockerClientBuilder) Getter(lombok.Getter) HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) FieldNamingPolicy(com.google.gson.FieldNamingPolicy) DockerClientConfig(com.github.dockerjava.core.DockerClientConfig) HostConfig(com.github.dockerjava.api.model.HostConfig) HttpClient(org.apache.http.client.HttpClient) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) Frame(com.github.dockerjava.api.model.Frame) Assertions.assertJson(au.csiro.pathling.test.assertions.Assertions.assertJson) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) DefaultDockerClientConfig(com.github.dockerjava.core.DefaultDockerClientConfig) Nonnull(javax.annotation.Nonnull) IParser(ca.uhn.fhir.parser.IParser) Nullable(javax.annotation.Nullable) ParametersParameterComponent(org.hl7.fhir.r4.model.Parameters.ParametersParameterComponent) StringWriter(java.io.StringWriter) IOException(java.io.IOException) InputStreamReader(java.io.InputStreamReader) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) OperationOutcome(org.hl7.fhir.r4.model.OperationOutcome) AfterEach(org.junit.jupiter.api.AfterEach) Closeable(java.io.Closeable) Data(lombok.Data) Parameters(org.hl7.fhir.r4.model.Parameters) InputStreamEntity(org.apache.http.entity.InputStreamEntity) CodeType(org.hl7.fhir.r4.model.CodeType) Runtime.getRuntime(java.lang.Runtime.getRuntime) Builder(com.github.dockerjava.okhttp.OkDockerHttpClient.Builder) OkDockerHttpClient(com.github.dockerjava.okhttp.OkDockerHttpClient) InputStream(java.io.InputStream) HttpPost(org.apache.http.client.methods.HttpPost) Parameters(org.hl7.fhir.r4.model.Parameters) InputStreamReader(java.io.InputStreamReader) GsonBuilder(com.google.gson.GsonBuilder) StringType(org.hl7.fhir.r4.model.StringType) InputStream(java.io.InputStream) Gson(com.google.gson.Gson) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) JSONException(org.json.JSONException) IOException(java.io.IOException) UriType(org.hl7.fhir.r4.model.UriType) InputStreamEntity(org.apache.http.entity.InputStreamEntity) StringEntity(org.apache.http.entity.StringEntity) StringWriter(java.io.StringWriter) OperationOutcome(org.hl7.fhir.r4.model.OperationOutcome) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) CapabilityStatement(org.hl7.fhir.r4.model.CapabilityStatement) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) CodeType(org.hl7.fhir.r4.model.CodeType) ParametersParameterComponent(org.hl7.fhir.r4.model.Parameters.ParametersParameterComponent) Test(org.junit.jupiter.api.Test)

Aggregations

ParametersParameterComponent (org.hl7.fhir.r4.model.Parameters.ParametersParameterComponent)26 Parameters (org.hl7.fhir.r4.model.Parameters)21 HashMap (java.util.HashMap)18 JsonObject (javax.json.JsonObject)15 GET (javax.ws.rs.GET)15 Path (javax.ws.rs.Path)15 Produces (javax.ws.rs.Produces)15 ExtraParameters (org.apache.camel.component.fhir.api.ExtraParameters)15 IBaseBundle (org.hl7.fhir.instance.model.api.IBaseBundle)15 FHIRException (org.hl7.fhir.exceptions.FHIRException)12 IOException (java.io.IOException)7 CodeType (org.hl7.fhir.r4.model.CodeType)7 URISyntaxException (java.net.URISyntaxException)6 Nonnull (javax.annotation.Nonnull)6 Parameters (org.hl7.fhir.dstu3.model.Parameters)6 ParametersParameterComponent (org.hl7.fhir.dstu3.model.Parameters.ParametersParameterComponent)6 Bundle (org.hl7.fhir.r4.model.Bundle)6 Slf4j (lombok.extern.slf4j.Slf4j)5 Parameters (org.hl7.fhir.dstu2.model.Parameters)5 Parameters (org.hl7.fhir.dstu2016may.model.Parameters)5