use of org.hl7.fhir.r4b.model.CapabilityStatement 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);
}
}
use of org.hl7.fhir.r4b.model.CapabilityStatement in project pathling by aehrc.
the class DockerImageTest method getCapabilityStatement.
CapabilityStatement getCapabilityStatement() throws IOException {
final HttpUriRequest capabilitiesRequest = new HttpGet("http://localhost:8091/fhir/metadata");
capabilitiesRequest.addHeader("Accept", "application/fhir+json");
log.info("Sending capabilities request");
final CapabilityStatement capabilities;
try (final CloseableHttpResponse response = (CloseableHttpResponse) httpClient.execute(capabilitiesRequest)) {
final InputStream capabilitiesStream = response.getEntity().getContent();
capabilities = (CapabilityStatement) jsonParser.parseResource(capabilitiesStream);
assertThat(response.getStatusLine().getStatusCode()).withFailMessage("Capabilities operation did not succeed").isEqualTo(200);
}
return capabilities;
}
use of org.hl7.fhir.r4b.model.CapabilityStatement in project quality-measure-and-cohort-service by Alvearie.
the class CohortEngineRestStatusHandlerTest method testEnhancedHealthCheckFailNoTermServer.
@PrepareForTest({ Response.class, TenantManager.class, ServiceBaseUtility.class, DefaultFhirClientBuilder.class })
@Test
public /**
* Test a failure connecting to data server and no terminology server provided
*/
void testEnhancedHealthCheckFailNoTermServer() throws Exception {
prepMocks(false);
PowerMockito.mockStatic(ServiceBaseUtility.class);
PowerMockito.when(ServiceBaseUtility.apiSetup(VERSION, logger, CohortEngineRestStatusHandler.GET_HEALTH_CHECK_ENCHANCED)).thenReturn(null);
CapabilityStatement metadata = getCapabilityStatement();
mockFhirResourceRetrieval("/metadata?_format=json", metadata);
mockFhirResourceRetrieval("/Patient?_format=json", null);
Response response = cerSH.getHealthCheckEnhanced(VERSION, getEnhancedHealthCheckInputConfigFileBody(false));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
assertEquals(((EnhancedHealthCheckResults) response.getEntity()).getDataServerConnectionResults().getConnectionResults(), FhirConnectionStatus.failure);
assertEquals(((EnhancedHealthCheckResults) response.getEntity()).getTerminologyServerConnectionResults().getConnectionResults(), FhirConnectionStatus.notAttempted);
}
use of org.hl7.fhir.r4b.model.CapabilityStatement in project quality-measure-and-cohort-service by Alvearie.
the class CohortEngineRestStatusHandlerTest method testEnhancedHealthCheckOK.
@PrepareForTest({ Response.class, TenantManager.class, ServiceBaseUtility.class, DefaultFhirClientBuilder.class })
@Test
public /**
* Test the setting of service status to OK.
*/
void testEnhancedHealthCheckOK() throws Exception {
prepMocks(false);
PowerMockito.mockStatic(ServiceBaseUtility.class);
PowerMockito.when(ServiceBaseUtility.apiSetup(VERSION, logger, CohortEngineRestStatusHandler.GET_HEALTH_CHECK_ENCHANCED)).thenReturn(null);
CapabilityStatement metadata = getCapabilityStatement();
mockFhirResourceRetrieval("/metadata?_format=json", metadata);
Patient patient = getPatient("123", AdministrativeGender.MALE, "1970-10-10");
mockFhirResourceRetrieval("/Patient?_format=json", patient);
// don't need to return a valueset since we only care that the call returns something
mockFhirResourceRetrieval("/ValueSet?_format=json", patient);
Response response = cerSH.getHealthCheckEnhanced(VERSION, getEnhancedHealthCheckInputConfigFileBody(true));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
assertEquals(((EnhancedHealthCheckResults) response.getEntity()).getDataServerConnectionResults().getConnectionResults(), FhirConnectionStatus.success);
assertEquals(((EnhancedHealthCheckResults) response.getEntity()).getTerminologyServerConnectionResults().getConnectionResults(), FhirConnectionStatus.success);
}
use of org.hl7.fhir.r4b.model.CapabilityStatement in project quality-measure-and-cohort-service by Alvearie.
the class CohortEngineRestStatusHandlerTest method testEnhancedHealthCheckOKNoTermServer.
@PrepareForTest({ Response.class, TenantManager.class, ServiceBaseUtility.class, DefaultFhirClientBuilder.class })
@Test
public void testEnhancedHealthCheckOKNoTermServer() throws Exception {
prepMocks(false);
PowerMockito.mockStatic(ServiceBaseUtility.class);
PowerMockito.when(ServiceBaseUtility.apiSetup(VERSION, logger, CohortEngineRestStatusHandler.GET_HEALTH_CHECK_ENCHANCED)).thenReturn(null);
CapabilityStatement metadata = getCapabilityStatement();
mockFhirResourceRetrieval("/metadata?_format=json", metadata);
Patient patient = getPatient("123", AdministrativeGender.MALE, "1970-10-10");
mockFhirResourceRetrieval("/Patient?_format=json", patient);
Response response = cerSH.getHealthCheckEnhanced(VERSION, getEnhancedHealthCheckInputConfigFileBody(false));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
assertEquals(((EnhancedHealthCheckResults) response.getEntity()).getDataServerConnectionResults().getConnectionResults(), FhirConnectionStatus.success);
assertEquals(((EnhancedHealthCheckResults) response.getEntity()).getTerminologyServerConnectionResults().getConnectionResults(), FhirConnectionStatus.notAttempted);
}
Aggregations