Search in sources :

Example 76 with Endpoint

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;
}
Also used : IdParam(ca.uhn.fhir.rest.annotation.IdParam) Arrays(java.util.Arrays) PatientLinkBuilder(gov.cms.bfd.server.war.commons.PatientLinkBuilder) Description(ca.uhn.fhir.model.api.annotation.Description) Identifier(org.hl7.fhir.r4.model.Identifier) NoResultException(javax.persistence.NoResultException) StringUtils(org.apache.commons.lang3.StringUtils) BigDecimal(java.math.BigDecimal) DateRangeParam(ca.uhn.fhir.rest.param.DateRangeParam) Predicate(javax.persistence.criteria.Predicate) IResourceProvider(ca.uhn.fhir.rest.server.IResourceProvider) IBaseResource(org.hl7.fhir.instance.model.api.IBaseResource) Map(java.util.Map) CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) JoinType(javax.persistence.criteria.JoinType) BeneficiaryHistory(gov.cms.bfd.model.rif.BeneficiaryHistory) LoadedFilterManager(gov.cms.bfd.server.war.commons.LoadedFilterManager) Patient(org.hl7.fhir.r4.model.Patient) SingularAttribute(javax.persistence.metamodel.SingularAttribute) CriteriaQuery(javax.persistence.criteria.CriteriaQuery) IdDt(ca.uhn.fhir.model.primitive.IdDt) InvalidRequestException(ca.uhn.fhir.rest.server.exceptions.InvalidRequestException) BeneficiaryMonthly_(gov.cms.bfd.model.rif.BeneficiaryMonthly_) QueryHints(org.hibernate.jpa.QueryHints) Collectors(java.util.stream.Collectors) BeneficiaryMonthly(gov.cms.bfd.model.rif.BeneficiaryMonthly) Objects(java.util.Objects) Beneficiary(gov.cms.bfd.model.rif.Beneficiary) List(java.util.List) BeneficiaryHistory_(gov.cms.bfd.model.rif.BeneficiaryHistory_) TransformerConstants(gov.cms.bfd.server.war.commons.TransformerConstants) Year(java.time.Year) LocalDate(java.time.LocalDate) Timer(com.codahale.metrics.Timer) Optional(java.util.Optional) OptionalParam(ca.uhn.fhir.rest.annotation.OptionalParam) QueryUtils(gov.cms.bfd.server.war.commons.QueryUtils) Trace(com.newrelic.api.agent.Trace) HashMap(java.util.HashMap) RequestHeaders(gov.cms.bfd.server.war.commons.RequestHeaders) TypedQuery(javax.persistence.TypedQuery) Beneficiary_(gov.cms.bfd.model.rif.Beneficiary_) ArrayList(java.util.ArrayList) RequiredParam(ca.uhn.fhir.rest.annotation.RequiredParam) Inject(javax.inject.Inject) Strings(com.google.common.base.Strings) RequestDetails(ca.uhn.fhir.rest.api.server.RequestDetails) Search(ca.uhn.fhir.rest.annotation.Search) CcwCodebookVariable(gov.cms.bfd.model.codebook.data.CcwCodebookVariable) ResourceNotFoundException(ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException) CommonHeaders(gov.cms.bfd.server.war.commons.CommonHeaders) LinkedList(java.util.LinkedList) Root(javax.persistence.criteria.Root) Read(ca.uhn.fhir.rest.annotation.Read) OffsetLinkBuilder(gov.cms.bfd.server.war.commons.OffsetLinkBuilder) MetricRegistry(com.codahale.metrics.MetricRegistry) Operation(gov.cms.bfd.server.war.Operation) EntityManager(javax.persistence.EntityManager) PersistenceContext(javax.persistence.PersistenceContext) IdType(org.hl7.fhir.r4.model.IdType) TokenParam(ca.uhn.fhir.rest.param.TokenParam) Component(org.springframework.stereotype.Component) MDC(org.slf4j.MDC) YearMonth(java.time.YearMonth) Bundle(org.hl7.fhir.r4.model.Bundle) Collections(java.util.Collections) PatientLinkBuilder(gov.cms.bfd.server.war.commons.PatientLinkBuilder) Bundle(org.hl7.fhir.r4.model.Bundle) InvalidRequestException(ca.uhn.fhir.rest.server.exceptions.InvalidRequestException) Operation(gov.cms.bfd.server.war.Operation) RequestHeaders(gov.cms.bfd.server.war.commons.RequestHeaders) IBaseResource(org.hl7.fhir.instance.model.api.IBaseResource) Beneficiary(gov.cms.bfd.model.rif.Beneficiary) Trace(com.newrelic.api.agent.Trace)

Example 77 with Endpoint

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;
}
Also used : TaskInfoHolder(org.hl7.gravity.refimpl.sdohexchange.fhir.extract.TaskInfoBundleExtractor.TaskInfoHolder) Task(org.hl7.fhir.r4.model.Task) Bundle(org.hl7.fhir.r4.model.Bundle)

Example 78 with Endpoint

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())))));
}
Also used : Organization(org.hl7.fhir.r4.model.Organization) EndpointConnectionType(org.hl7.fhir.r4.model.codesystems.EndpointConnectionType)

Example 79 with Endpoint

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);
}
Also used : TaskInfoHolder(org.hl7.gravity.refimpl.sdohexchange.fhir.extract.TaskInfoBundleExtractor.TaskInfoHolder) Task(org.hl7.fhir.r4.model.Task) Bundle(org.hl7.fhir.r4.model.Bundle) ServiceRequest(org.hl7.fhir.r4.model.ServiceRequest)

Example 80 with 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);
    }
}
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

Test (org.junit.jupiter.api.Test)36 Endpoint (org.hl7.fhir.dstu3.model.Endpoint)21 RequestDetails (ca.uhn.fhir.rest.api.server.RequestDetails)18 StringAndListParam (ca.uhn.fhir.rest.param.StringAndListParam)16 RestIntegrationTest (org.opencds.cqf.ruler.test.RestIntegrationTest)16 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)16 IGenericClient (ca.uhn.fhir.rest.client.api.IGenericClient)15 Endpoint (org.hl7.fhir.r4.model.Endpoint)15 Complex (org.hl7.fhir.dstu3.utils.formats.Turtle.Complex)14 Complex (org.hl7.fhir.r4.utils.formats.Turtle.Complex)14 Bundle (org.hl7.fhir.r4.model.Bundle)12 Organization (org.hl7.fhir.dstu3.model.Organization)11 Resource (org.hl7.fhir.r4.model.Resource)10 Resource (org.hl7.fhir.dstu3.model.Resource)9 Operation (ca.uhn.fhir.rest.annotation.Operation)7 List (java.util.List)7 Bundle (org.hl7.fhir.dstu3.model.Bundle)7 Description (ca.uhn.fhir.model.api.annotation.Description)6 MethodOutcome (ca.uhn.fhir.rest.api.MethodOutcome)6 ArrayList (java.util.ArrayList)6