Merged the rel_5_3_0 branch into this Branch to pick up the MDM changes.

This commit is contained in:
Kevin Dougan
2021-01-07 09:12:52 -05:00
parent a83927aa0c
commit 3954f6a3f4
18 changed files with 338 additions and 262 deletions

View File

@@ -26,11 +26,13 @@ import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import pl.allegro.tech.embeddedelasticsearch.EmbeddedElastic;
import pl.allegro.tech.embeddedelasticsearch.PopularProperties;
import org.testcontainers.elasticsearch.ElasticsearchContainer;
import org.testcontainers.junit.jupiter.Container;
import javax.annotation.PreDestroy;
import java.io.IOException;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.UUID;
@@ -49,7 +51,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
// Because the port is set randomly, we will set the rest_url using the Initializer.
// "elasticsearch.rest_url='http://localhost:9200'",
"elasticsearch.username=SomeUsername",
"elasticsearch.password=SomePassword"
"elasticsearch.password=SomePassword",
"elasticsearch.protocol=http"
})
@ContextConfiguration(initializers = ElasticsearchLastNR4IT.Initializer.class)
public class ElasticsearchLastNR4IT {
@@ -57,30 +60,20 @@ public class ElasticsearchLastNR4IT {
private IGenericClient ourClient;
private FhirContext ourCtx;
private static final String ELASTIC_VERSION = "6.5.4";
private static EmbeddedElastic embeddedElastic;
private static final String ELASTIC_VERSION = "7.10.0";
private static final String ELASTIC_IMAGE = "docker.elastic.co/elasticsearch/elasticsearch:" + ELASTIC_VERSION;
private static ElasticsearchContainer embeddedElastic;
@Autowired
private ElasticsearchSvcImpl myElasticsearchSvc;
@BeforeAll
public static void beforeClass() {
embeddedElastic = null;
try {
embeddedElastic = EmbeddedElastic.builder()
.withElasticVersion(ELASTIC_VERSION)
.withSetting(PopularProperties.TRANSPORT_TCP_PORT, 0)
.withSetting(PopularProperties.HTTP_PORT, 0)
.withSetting(PopularProperties.CLUSTER_NAME, UUID.randomUUID())
.withStartTimeout(60, TimeUnit.SECONDS)
.build()
.start();
} catch (IOException | InterruptedException e) {
throw new ConfigurationException(e);
}
embeddedElastic = new ElasticsearchContainer(ELASTIC_IMAGE).withStartupTimeout(Duration.of(300, ChronoUnit.SECONDS));
embeddedElastic.start();
}
@PreDestroy
public void stop() {
embeddedElastic.stop();
@@ -136,7 +129,7 @@ public class ElasticsearchLastNR4IT {
public void initialize(
ConfigurableApplicationContext configurableApplicationContext) {
// Since the port is dynamically generated, replace the URL with one that has the correct port
TestPropertyValues.of("elasticsearch.rest_url=http://localhost:" + embeddedElastic.getHttpPort())
TestPropertyValues.of("elasticsearch.rest_url=" + embeddedElastic.getHost() +":" + embeddedElastic.getMappedPort(9200))
.applyTo(configurableApplicationContext.getEnvironment());
}

View File

@@ -14,10 +14,12 @@ import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
import org.eclipse.jetty.websocket.client.WebSocketClient;
import org.hl7.fhir.instance.model.api.IIdType;
import org.hl7.fhir.r4.model.*;
import org.junit.Assert;
import org.junit.jupiter.api.AfterEach;
import org.hl7.fhir.r4.model.Bundle;
import org.hl7.fhir.r4.model.Observation;
import org.hl7.fhir.r4.model.Patient;
import org.hl7.fhir.r4.model.Subscription;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
@@ -27,246 +29,145 @@ import org.springframework.test.context.junit.jupiter.SpringExtension;
import java.io.IOException;
import java.net.URI;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static ca.uhn.fhir.util.TestUtil.waitForSize;
import static java.util.Comparator.comparing;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = Application.class, properties =
{
"spring.batch.job.enabled=false",
"spring.datasource.url=jdbc:h2:mem:dbr4",
"hapi.fhir.fhir_version=R4",
"hapi.fhir.cql_enabled=true",
"hapi.fhir.subscription.websocket_enabled=true",
//Override is currently required when using Empi as the construction of the Empi beans are ambiguous as they are constructed multiple places. This is evident when running in a spring boot environment
"spring.main.allow-bean-definition-overriding=true"
})
public class ExampleServerR4IT implements IServerSupport {
{
"spring.batch.job.enabled=false",
"spring.datasource.url=jdbc:h2:mem:dbr4",
"hapi.fhir.enable_repository_validating_interceptor=true",
"hapi.fhir.fhir_version=r4",
"hapi.fhir.subscription.websocket_enabled=true",
"hapi.fhir.mdm_enabled=true",
//Override is currently required when using MDM as the construction of the MDM beans are ambiguous as they are constructed multiple places. This is evident when running in a spring boot environment
"spring.main.allow-bean-definition-overriding=true"
})
public class ExampleServerR4IT {
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(ExampleServerDstu2IT.class);
private IGenericClient ourClient;
private FhirContext ourCtx;
private String ourServerBaseURL;
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(ExampleServerDstu2IT.class);
private IGenericClient ourClient;
private FhirContext ourCtx;
@Autowired
DaoRegistry myDaoRegistry;
@LocalServerPort
private int port;
@LocalServerPort
private int port;
@BeforeEach
void beforeEach() {
ourCtx = FhirContext.forR4();
ourCtx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.NEVER);
ourCtx.getRestfulClientFactory().setSocketTimeout(1200 * 1000);
ourServerBaseURL = "http://localhost:" + port + "/fhir/";
ourClient = ourCtx.newRestfulGenericClient(ourServerBaseURL);
ourClient.registerInterceptor(new LoggingInterceptor(true));
}
@Test
@Order(0)
void testCreateAndRead() {
@AfterEach
void afterEach() {
ourLog.info("Finished running a test...");
}
String methodName = "testCreateResourceConditional";
@Test
public void testCQLEXM104EvaluateMeasure() throws IOException {
String measureId = "measure-EXM104-8.2.000";
Patient pt = new Patient();
pt.setActive(true);
pt.getBirthDateElement().setValueAsString("2020-01-01");
pt.addIdentifier().setSystem("http://foo").setValue("12345");
pt.addName().setFamily(methodName);
IIdType id = ourClient.create().resource(pt).execute().getId();
loadBundle("r4/EXM104/EXM104-8.2.000-bundle.json", ourCtx, ourClient);
Patient pt2 = ourClient.read().resource(Patient.class).withId(id).execute();
assertEquals(methodName, pt2.getName().get(0).getFamily());
// http://localhost:8080/fhir/Measure/measure-EXM104-8.2.000/$evaluate-measure?periodStart=2019-01-01&periodEnd=2019-12-31
Parameters inParams = new Parameters();
inParams.addParameter().setName("periodStart").setValue(new StringType("2019-01-01"));
inParams.addParameter().setName("periodEnd").setValue(new StringType("2019-12-31"));
// Test MDM
Parameters outParams = ourClient
.operation()
.onInstance(new IdDt("Measure", measureId))
.named("$evaluate-measure")
.withParameters(inParams)
.cacheControl(new CacheControlDirective().setNoCache(true))
.withAdditionalHeader("Content-Type", "application/json")
.useHttpGet()
.execute();
// Wait until the MDM message has been processed
await().until(() -> getPatients().size(), equalTo(2));
List<Patient> persons = getPatients();
Patient goldenRecord = persons.get(0);
List<Parameters.ParametersParameterComponent> response = outParams.getParameter();
Assert.assertTrue(!response.isEmpty());
Parameters.ParametersParameterComponent component = response.get(0);
Assert.assertTrue(component.getResource() instanceof MeasureReport);
MeasureReport report = (MeasureReport) component.getResource();
Assert.assertEquals("Measure/"+measureId, report.getMeasure());
}
// Verify that a golden record Patient was created
assertNotNull(goldenRecord.getMeta().getTag("http://hapifhir.io/fhir/NamingSystem/mdm-record-status", "GOLDEN_RECORD"));
}
private Bundle loadBundle(String theLocation, FhirContext theCtx, IGenericClient theClient) throws IOException {
String json = stringFromResource(theLocation);
Bundle bundle = (Bundle) theCtx.newJsonParser().parseResource(json);
Bundle result = (Bundle) theClient.transaction().withBundle(bundle).execute();
return result;
}
private List<Patient> getPatients() {
Bundle bundle = ourClient.search().forResource(Patient.class).cacheControl(new CacheControlDirective().setNoCache(true)).returnBundle(Bundle.class).execute();
List<Patient> retVal = BundleUtil.toListOfResourcesOfType(ourCtx, bundle, Patient.class);
retVal.sort(comparing(o -> ((Patient) o).getMeta().getLastUpdated()).reversed());
return retVal;
}
@Test
public void testCQLEXM130EvaluateMeasure() throws IOException {
String measureId = "measure-EXM130-7.3.000";
@Test
@Order(1)
public void testWebsocketSubscription() throws Exception {
/*
* Create subscription
*/
Subscription subscription = new Subscription();
subscription.setReason("Monitor new neonatal function (note, age will be determined by the monitor)");
subscription.setStatus(Subscription.SubscriptionStatus.REQUESTED);
subscription.setCriteria("Observation?status=final");
loadBundle("r4/EXM130/EXM130-7.3.000-bundle.json", ourCtx, ourClient);
Subscription.SubscriptionChannelComponent channel = new Subscription.SubscriptionChannelComponent();
channel.setType(Subscription.SubscriptionChannelType.WEBSOCKET);
channel.setPayload("application/json");
subscription.setChannel(channel);
// http://localhost:8080/fhir/Measure/measure-EXM130-FHIR4-7.2.000/$evaluate-measure?periodStart=2019-01-01&periodEnd=2019-12-31
Parameters inParams = new Parameters();
// inParams.addParameter().setName("measure").setValue(new StringType("Measure/measure-EXM104-8.2.000"));
// inParams.addParameter().setName("patient").setValue(new StringType("Patient/numer-EXM104-FHIR3"));
inParams.addParameter().setName("periodStart").setValue(new StringType("2019-01-01"));
inParams.addParameter().setName("periodEnd").setValue(new StringType("2019-12-31"));
MethodOutcome methodOutcome = ourClient.create().resource(subscription).execute();
IIdType mySubscriptionId = methodOutcome.getId();
Parameters outParams = ourClient
.operation()
.onInstance(new IdDt("Measure", measureId))
.named("$evaluate-measure")
.withParameters(inParams)
.cacheControl(new CacheControlDirective().setNoCache(true))
.withAdditionalHeader("Content-Type", "application/json")
.useHttpGet()
.execute();
// Wait for the subscription to be activated
await().until(() -> activeSubscriptionCount() == 3);
List<Parameters.ParametersParameterComponent> response = outParams.getParameter();
Assert.assertTrue(!response.isEmpty());
Parameters.ParametersParameterComponent component = response.get(0);
Assert.assertTrue(component.getResource() instanceof MeasureReport);
MeasureReport report = (MeasureReport) component.getResource();
Assert.assertEquals("Measure/"+measureId, report.getMeasure());
}
/*
* Attach websocket
*/
@Test
public void testCQLEXM349EvaluateMeasure() throws IOException {
String measureId = "measure-EXM349-2.10.000";
WebSocketClient myWebSocketClient = new WebSocketClient();
SocketImplementation mySocketImplementation = new SocketImplementation(mySubscriptionId.getIdPart(), EncodingEnum.JSON);
loadBundle("r4/EXM349/EXM349-2.10.000-bundle.json.manuallyeditedtoremovesupplementaldata", ourCtx, ourClient);
myWebSocketClient.start();
URI echoUri = new URI("ws://localhost:" + port + "/websocket");
ClientUpgradeRequest request = new ClientUpgradeRequest();
ourLog.info("Connecting to : {}", echoUri);
Future<Session> connection = myWebSocketClient.connect(mySocketImplementation, echoUri, request);
Session session = connection.get(2, TimeUnit.SECONDS);
// http://localhost:8080/fhir/Measure/measure-EXM349-2.10.000/$evaluate-measure?periodStart=2019-01-01&periodEnd=2019-12-31
Parameters inParams = new Parameters();
inParams.addParameter().setName("periodStart").setValue(new StringType("2019-01-01"));
inParams.addParameter().setName("periodEnd").setValue(new StringType("2019-12-31"));
ourLog.info("Connected to WS: {}", session.isOpen());
Parameters outParams = ourClient
.operation()
.onInstance(new IdDt("Measure", measureId))
.named("$evaluate-measure")
.withParameters(inParams)
.cacheControl(new CacheControlDirective().setNoCache(true))
.withAdditionalHeader("Content-Type", "application/json")
.useHttpGet()
.execute();
/*
* Create a matching resource
*/
Observation obs = new Observation();
obs.setStatus(Observation.ObservationStatus.FINAL);
ourClient.create().resource(obs).execute();
List<Parameters.ParametersParameterComponent> response = outParams.getParameter();
Assert.assertTrue(!response.isEmpty());
Parameters.ParametersParameterComponent component = response.get(0);
Assert.assertTrue(component.getResource() instanceof MeasureReport);
MeasureReport report = (MeasureReport) component.getResource();
Assert.assertEquals("Measure/"+measureId, report.getMeasure());
}
// Give some time for the subscription to deliver
Thread.sleep(2000);
//@Test
void testCreateAndRead() {
/*
* Ensure that we receive a ping on the websocket
*/
waitForSize(1, () -> mySocketImplementation.myPingCount);
String methodName = "testCreateResourceConditional";
/*
* Clean up
*/
ourClient.delete().resourceById(mySubscriptionId).execute();
}
Patient pt = new Patient();
pt.setActive(true);
pt.getBirthDateElement().setValueAsString("2020-01-01");
pt.addIdentifier().setSystem("http://foo").setValue("12345");
pt.addName().setFamily(methodName);
IIdType id = ourClient.create().resource(pt).execute().getId();
private int activeSubscriptionCount() {
return ourClient.search().forResource(Subscription.class).where(Subscription.STATUS.exactly().code("active")).cacheControl(new CacheControlDirective().setNoCache(true)).returnBundle(Bundle.class).execute().getEntry().size();
}
Patient pt2 = ourClient.read().resource(Patient.class).withId(id).execute();
assertEquals(methodName, pt2.getName().get(0).getFamily());
// Wait until the message has been processed
await().until(() -> getPeople().size() > 0);
List<Person> persons = getPeople();
@BeforeEach
void beforeEach() {
// Verify a Person was created that links to our Patient
Optional<String> personLinkToCreatedPatient = persons.stream()
.map(Person::getLink)
.flatMap(Collection::stream)
.map(Person.PersonLinkComponent::getTarget)
.map(Reference::getReference)
.filter(pid -> id.toUnqualifiedVersionless().getValue().equals(pid))
.findAny();
assertTrue(personLinkToCreatedPatient.isPresent());
}
private List<Person> getPeople() {
Bundle bundle = ourClient.search().forResource(Person.class).cacheControl(new CacheControlDirective().setNoCache(true)).returnBundle(Bundle.class).execute();
return BundleUtil.toListOfResourcesOfType(ourCtx, bundle, Person.class);
}
//@Test
public void testWebsocketSubscription() throws Exception {
/*
* Create subscription
*/
Subscription subscription = new Subscription();
subscription.setReason("Monitor new neonatal function (note, age will be determined by the monitor)");
subscription.setStatus(Subscription.SubscriptionStatus.REQUESTED);
subscription.setCriteria("Observation?status=final");
Subscription.SubscriptionChannelComponent channel = new Subscription.SubscriptionChannelComponent();
channel.setType(Subscription.SubscriptionChannelType.WEBSOCKET);
channel.setPayload("application/json");
subscription.setChannel(channel);
MethodOutcome methodOutcome = ourClient.create().resource(subscription).execute();
IIdType mySubscriptionId = methodOutcome.getId();
// Wait for the subscription to be activated
await().until(() -> activeSubscriptionCount() == 3);
/*
* Attach websocket
*/
WebSocketClient myWebSocketClient = new WebSocketClient();
SocketImplementation mySocketImplementation = new SocketImplementation(mySubscriptionId.getIdPart(), EncodingEnum.JSON);
myWebSocketClient.start();
URI echoUri = new URI("ws://localhost:" + port + "/websocket");
ClientUpgradeRequest request = new ClientUpgradeRequest();
ourLog.info("Connecting to : {}", echoUri);
Future<Session> connection = myWebSocketClient.connect(mySocketImplementation, echoUri, request);
Session session = connection.get(2, TimeUnit.SECONDS);
ourLog.info("Connected to WS: {}", session.isOpen());
/*
* Create a matching resource
*/
Observation obs = new Observation();
obs.setStatus(Observation.ObservationStatus.FINAL);
ourClient.create().resource(obs).execute();
// Give some time for the subscription to deliver
Thread.sleep(2000);
/*
* Ensure that we receive a ping on the websocket
*/
waitForSize(1, () -> mySocketImplementation.myPingCount);
/*
* Clean up
*/
ourClient.delete().resourceById(mySubscriptionId).execute();
}
private int activeSubscriptionCount() {
return ourClient.search().forResource(Subscription.class).where(Subscription.STATUS.exactly().code("active")).cacheControl(new CacheControlDirective().setNoCache(true)).returnBundle(Bundle.class).execute().getEntry().size();
}
ourCtx = FhirContext.forR4();
ourCtx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.NEVER);
ourCtx.getRestfulClientFactory().setSocketTimeout(1200 * 1000);
String ourServerBase = "http://localhost:" + port + "/fhir/";
ourClient = ourCtx.newRestfulGenericClient(ourServerBase);
ourClient.registerInterceptor(new LoggingInterceptor(true));
}
}

View File

@@ -37,7 +37,8 @@ import org.springframework.test.context.junit.jupiter.SpringExtension;
"spring.batch.job.enabled=false",
"spring.datasource.url=jdbc:h2:mem:dbr5",
"hapi.fhir.fhir_version=r5",
"hapi.fhir.subscription.websocket_enabled=true"
"hapi.fhir.subscription.websocket_enabled=true",
"hapi.fhir.subscription.websocket_enabled=true"
})
public class ExampleServerR5IT {