use of org.hl7.fhir.r4.model.Endpoint in project beneficiary-fhir-data by CMSgov.
the class R4PatientResourceProvider method searchByCoverageContractAndYearMonth.
@Trace
private Bundle searchByCoverageContractAndYearMonth(// of relational search is more common.
TokenParam coverageId, LocalDate yearMonth, RequestDetails requestDetails) {
checkCoverageId(coverageId);
RequestHeaders requestHeader = RequestHeaders.getHeaderWrapper(requestDetails);
// requested.
if (!requestHeader.isMBIinIncludeIdentifiers() || requestHeader.isHICNinIncludeIdentifiers()) {
throw new InvalidRequestException(String.format("This endpoint requires the '%s: mbi' header.", CommonHeaders.HEADER_NAME_INCLUDE_IDENTIFIERS));
}
PatientLinkBuilder paging = new PatientLinkBuilder(requestDetails.getCompleteUrl());
Operation operation = new Operation(Operation.Endpoint.V2_PATIENT);
operation.setOption("by", "coverageContractForYearMonth");
requestHeader.getNVPairs().forEach((n, v) -> operation.setOption(n, v.toString()));
operation.publishOperationName();
List<Beneficiary> matchingBeneficiaries = fetchBeneficiariesByContractAndYearMonth(coverageId, yearMonth, paging);
boolean hasAnotherPage = matchingBeneficiaries.size() > paging.getPageSize();
if (hasAnotherPage) {
matchingBeneficiaries = matchingBeneficiaries.subList(0, paging.getPageSize());
paging = new PatientLinkBuilder(paging, hasAnotherPage);
}
List<IBaseResource> patients = matchingBeneficiaries.stream().map(b -> BeneficiaryTransformerV2.transform(metricRegistry, b, requestHeader)).collect(Collectors.toList());
Bundle bundle = TransformerUtilsV2.createBundle(patients, paging, loadedFilterManager.getTransactionTime());
TransformerUtilsV2.workAroundHAPIIssue1585(requestDetails);
return bundle;
}
use of org.hl7.fhir.r4.model.Endpoint in project Gravity-SDOH-Exchange-RI by FHIR.
the class TaskPollingService method getUpdateBundle.
protected Bundle getUpdateBundle(Task task, ServiceRequest serviceRequest, Endpoint endpoint) throws CpClientException {
Bundle resultBundle = new Bundle();
resultBundle.setType(Bundle.BundleType.TRANSACTION);
// Do a copy not to modify an input Task. Possibly this method will fail during execution, and we don't want to
// end up with a modified Task.
Task resultTask = task.copy();
TaskInfoHolder cpTaskInfo = cpService.read(task.getIdElement().getIdPart(), endpoint);
Task cpTask = cpTaskInfo.getTask();
// If status is the same and comments size are the same OR CP task in REQUESTED state - do nothing.
if ((cpTask.getStatus().equals(task.getStatus()) && cpTask.getNote().size() == task.getNote().size()) || Task.TaskStatus.REQUESTED.equals(cpTask.getStatus())) {
return resultBundle;
}
log.info("Task status/field change detected for id '{}'. '{}' -> '{}'. Updating...", task.getIdElement().getIdPart(), task.getStatus(), cpTask.getStatus());
// Copy required Task fields
copyTaskFields(resultTask, cpTask, endpoint);
resultBundle.addEntry(FhirUtil.createPutEntry(resultTask));
if (FINISHED_TASK_STATUSES.contains(cpTask.getStatus())) {
// It is critical to pass a resultTask, not a task, since it will be modified inside.
handleFinishedTask(resultBundle, resultTask, serviceRequest, cpTask, endpoint);
}
return resultBundle;
}
use of org.hl7.fhir.r4.model.Endpoint in project Gravity-SDOH-Exchange-RI by FHIR.
the class TaskPrepareBundleFactory method getPerformerWithEndpointEntry.
/**
* Create GET entry to retrieve a performing Organization by id and additionally check whether it has supported type,
* also include all related Endpoint resources with specific connection type.
*
* @return organization and endpoint entry
*/
protected BundleEntryComponent getPerformerWithEndpointEntry() {
Assert.notNull(performer, "Performer Organization can't be null.");
EndpointConnectionType connectionType = EndpointConnectionType.HL7FHIRREST;
return FhirUtil.createGetEntry(addParams(Organization.class.getSimpleName(), combineParams(eq(Organization.SP_RES_ID, performer), eq(Organization.SP_TYPE, hasSystemWithAnyCode(OrganizationTypeCode.SYSTEM)), eq(Constants.PARAM_INCLUDE, include(Organization.class.getSimpleName(), Organization.SP_ENDPOINT)), eq(resourceField(Organization.SP_ENDPOINT, Endpoint.SP_CONNECTION_TYPE), hasSystemAndCode(connectionType.getSystem(), connectionType.toCode())))));
}
use of org.hl7.fhir.r4.model.Endpoint in project Gravity-SDOH-Exchange-RI by FHIR.
the class CpService method sync.
public void sync(final Task ehrTask, final ServiceRequest ehrServiceRequest, final Endpoint endpoint) throws CpClientException {
Bundle cpUpdateBundle = new Bundle();
cpUpdateBundle.setType(BundleType.TRANSACTION);
TaskInfoHolder cpTaskInfo = read(ehrTask.getIdElement().getIdPart(), endpoint);
Task cpTask = cpTaskInfo.getTask();
cpTask.setStatus(ehrTask.getStatus());
cpTask.setStatusReason(ehrTask.getStatusReason());
cpTask.setLastModifiedElement(ehrTask.getLastModifiedElement());
cpTask.setNote(ehrTask.getNote());
cpUpdateBundle.addEntry(FhirUtil.createPutEntry(cpTask));
ServiceRequest cpServiceRequest = cpTaskInfo.getServiceRequest();
if (!ehrServiceRequest.getStatus().equals(cpServiceRequest.getStatus())) {
cpServiceRequest.setStatus(ehrServiceRequest.getStatus());
cpUpdateBundle.addEntry(FhirUtil.createPutEntry(cpServiceRequest));
}
transaction(cpUpdateBundle, endpoint);
}
use of org.hl7.fhir.r4.model.Endpoint 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);
}
}
Aggregations