-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
ResourceProviderDstu3Test.java
4837 lines (4023 loc) · 184 KB
/
ResourceProviderDstu3Test.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package ca.uhn.fhir.jpa.provider.dstu3;
import ca.uhn.fhir.i18n.Msg;
import ca.uhn.fhir.jpa.api.config.DaoConfig;
import ca.uhn.fhir.jpa.dao.data.ISearchDao;
import ca.uhn.fhir.jpa.entity.Search;
import ca.uhn.fhir.jpa.search.SearchCoordinatorSvcImpl;
import ca.uhn.fhir.jpa.util.QueryParameterUtils;
import ca.uhn.fhir.model.api.TemporalPrecisionEnum;
import ca.uhn.fhir.model.primitive.InstantDt;
import ca.uhn.fhir.model.primitive.UriDt;
import ca.uhn.fhir.parser.IParser;
import ca.uhn.fhir.parser.StrictErrorHandler;
import ca.uhn.fhir.rest.api.CacheControlDirective;
import ca.uhn.fhir.rest.api.Constants;
import ca.uhn.fhir.rest.api.MethodOutcome;
import ca.uhn.fhir.rest.api.SearchTotalModeEnum;
import ca.uhn.fhir.rest.api.SummaryEnum;
import ca.uhn.fhir.rest.client.api.IClientInterceptor;
import ca.uhn.fhir.rest.client.api.IGenericClient;
import ca.uhn.fhir.rest.client.api.IHttpRequest;
import ca.uhn.fhir.rest.client.api.IHttpResponse;
import ca.uhn.fhir.rest.client.interceptor.LoggingInterceptor;
import ca.uhn.fhir.rest.gclient.StringClientParam;
import ca.uhn.fhir.rest.param.DateRangeParam;
import ca.uhn.fhir.rest.param.NumberParam;
import ca.uhn.fhir.rest.param.ParamPrefixEnum;
import ca.uhn.fhir.rest.param.StringAndListParam;
import ca.uhn.fhir.rest.param.StringOrListParam;
import ca.uhn.fhir.rest.param.StringParam;
import ca.uhn.fhir.rest.server.exceptions.InternalErrorException;
import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;
import ca.uhn.fhir.rest.server.exceptions.PreconditionFailedException;
import ca.uhn.fhir.rest.server.exceptions.ResourceGoneException;
import ca.uhn.fhir.rest.server.exceptions.UnprocessableEntityException;
import ca.uhn.fhir.rest.server.interceptor.BaseValidatingInterceptor;
import ca.uhn.fhir.rest.server.interceptor.RequestValidatingInterceptor;
import ca.uhn.fhir.util.ClasspathUtil;
import ca.uhn.fhir.util.HapiExtensions;
import ca.uhn.fhir.util.UrlUtil;
import ca.uhn.fhir.validation.IValidatorModule;
import ca.uhn.fhir.validation.ResultSeverityEnum;
import com.google.common.base.Charsets;
import com.google.common.collect.Lists;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import org.hl7.fhir.common.hapi.validation.validator.FhirInstanceValidator;
import org.hl7.fhir.dstu3.model.Attachment;
import org.hl7.fhir.dstu3.model.AuditEvent;
import org.hl7.fhir.dstu3.model.BaseResource;
import org.hl7.fhir.dstu3.model.Basic;
import org.hl7.fhir.dstu3.model.Binary;
import org.hl7.fhir.dstu3.model.Bundle;
import org.hl7.fhir.dstu3.model.Bundle.BundleEntryComponent;
import org.hl7.fhir.dstu3.model.Bundle.BundleLinkComponent;
import org.hl7.fhir.dstu3.model.Bundle.BundleType;
import org.hl7.fhir.dstu3.model.Bundle.HTTPVerb;
import org.hl7.fhir.dstu3.model.Bundle.SearchEntryMode;
import org.hl7.fhir.dstu3.model.CodeSystem;
import org.hl7.fhir.dstu3.model.CodeType;
import org.hl7.fhir.dstu3.model.CodeableConcept;
import org.hl7.fhir.dstu3.model.Coding;
import org.hl7.fhir.dstu3.model.Condition;
import org.hl7.fhir.dstu3.model.DateTimeType;
import org.hl7.fhir.dstu3.model.DateType;
import org.hl7.fhir.dstu3.model.Device;
import org.hl7.fhir.dstu3.model.DocumentManifest;
import org.hl7.fhir.dstu3.model.DocumentReference;
import org.hl7.fhir.dstu3.model.Encounter;
import org.hl7.fhir.dstu3.model.Encounter.EncounterLocationComponent;
import org.hl7.fhir.dstu3.model.Encounter.EncounterStatus;
import org.hl7.fhir.dstu3.model.Enumerations;
import org.hl7.fhir.dstu3.model.Enumerations.AdministrativeGender;
import org.hl7.fhir.dstu3.model.EpisodeOfCare;
import org.hl7.fhir.dstu3.model.Extension;
import org.hl7.fhir.dstu3.model.IdType;
import org.hl7.fhir.dstu3.model.Identifier;
import org.hl7.fhir.dstu3.model.ImagingStudy;
import org.hl7.fhir.dstu3.model.InstantType;
import org.hl7.fhir.dstu3.model.IntegerType;
import org.hl7.fhir.dstu3.model.Location;
import org.hl7.fhir.dstu3.model.Media;
import org.hl7.fhir.dstu3.model.Medication;
import org.hl7.fhir.dstu3.model.MedicationAdministration;
import org.hl7.fhir.dstu3.model.MedicationRequest;
import org.hl7.fhir.dstu3.model.Meta;
import org.hl7.fhir.dstu3.model.Narrative.NarrativeStatus;
import org.hl7.fhir.dstu3.model.Observation;
import org.hl7.fhir.dstu3.model.Observation.ObservationStatus;
import org.hl7.fhir.dstu3.model.OperationOutcome;
import org.hl7.fhir.dstu3.model.Organization;
import org.hl7.fhir.dstu3.model.Parameters;
import org.hl7.fhir.dstu3.model.Patient;
import org.hl7.fhir.dstu3.model.Period;
import org.hl7.fhir.dstu3.model.PlanDefinition;
import org.hl7.fhir.dstu3.model.Practitioner;
import org.hl7.fhir.dstu3.model.ProcedureRequest;
import org.hl7.fhir.dstu3.model.Quantity;
import org.hl7.fhir.dstu3.model.Questionnaire;
import org.hl7.fhir.dstu3.model.Questionnaire.QuestionnaireItemType;
import org.hl7.fhir.dstu3.model.QuestionnaireResponse;
import org.hl7.fhir.dstu3.model.Reference;
import org.hl7.fhir.dstu3.model.RelatedArtifact;
import org.hl7.fhir.dstu3.model.SearchParameter;
import org.hl7.fhir.dstu3.model.StringType;
import org.hl7.fhir.dstu3.model.StructureDefinition;
import org.hl7.fhir.dstu3.model.Subscription;
import org.hl7.fhir.dstu3.model.Subscription.SubscriptionChannelType;
import org.hl7.fhir.dstu3.model.Subscription.SubscriptionStatus;
import org.hl7.fhir.dstu3.model.Task;
import org.hl7.fhir.dstu3.model.UnsignedIntType;
import org.hl7.fhir.dstu3.model.ValueSet;
import org.hl7.fhir.dstu3.model.codesystems.DeviceStatus;
import org.hl7.fhir.instance.model.api.IBaseResource;
import org.hl7.fhir.instance.model.api.IIdType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.util.AopTestUtils;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;
import java.util.stream.Collectors;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.containsInRelativeOrder;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.emptyString;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
import static org.hamcrest.Matchers.matchesPattern;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.startsWith;
import static org.hamcrest.Matchers.stringContainsInOrder;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
public class ResourceProviderDstu3Test extends BaseResourceProviderDstu3Test {
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(ResourceProviderDstu3Test.class);
private SearchCoordinatorSvcImpl mySearchCoordinatorSvcRaw;
@Autowired
private ISearchDao mySearchEntityDao;
@Override
@AfterEach
public void after() throws Exception {
super.after();
myDaoConfig.setAllowMultipleDelete(new DaoConfig().isAllowMultipleDelete());
myDaoConfig.setAllowExternalReferences(new DaoConfig().isAllowExternalReferences());
myDaoConfig.setReuseCachedSearchResultsForMillis(new DaoConfig().getReuseCachedSearchResultsForMillis());
mySearchCoordinatorSvcRaw.setLoadingThrottleForUnitTests(null);
mySearchCoordinatorSvcRaw.setSyncSizeForUnitTests(QueryParameterUtils.DEFAULT_SYNC_SIZE);
mySearchCoordinatorSvcRaw.setNeverUseLocalSearchForUnitTests(false);
}
@Test
public void testSearchBySourceTransactionId() {
Patient p1 = new Patient();
p1.setActive(true);
ourClient
.create()
.resource(p1)
.withAdditionalHeader(Constants.HEADER_REQUEST_ID, "11111")
.execute();
Patient p2 = new Patient();
p2.setActive(true);
ourClient
.create()
.resource(p2)
.withAdditionalHeader(Constants.HEADER_REQUEST_ID, "22222")
.execute();
Bundle results = ourClient
.search()
.byUrl(ourServerBase + "/Patient?_source=%2311111")
.returnBundle(Bundle.class)
.execute();
assertEquals(1, results.getEntry().size());
}
@Test
public void testSearchByExternalReference() {
myDaoConfig.setAllowExternalReferences(true);
Patient patient = new Patient();
patient.addName().setFamily("FooName");
IIdType patientId = ourClient.create().resource(patient).execute().getId();
//Reference patientReference = new Reference("Patient/" + patientId.getIdPart()); <--- this works
Reference patientReference = new Reference(patientId); // <--- this is seen as an external reference
Media media = new Media();
Attachment attachment = new Attachment();
attachment.setLanguage("ENG");
media.setContent(attachment);
media.setSubject(patientReference);
media.setType(Media.DigitalMediaType.AUDIO);
IIdType mediaId = ourClient.create().resource(media).execute().getId();
// Act
Bundle returnedBundle = ourClient.search()
.forResource(Observation.class)
.where(Observation.CONTEXT.hasId(patientReference.getReference()))
.returnBundle(Bundle.class)
.execute();
// Assert
assertEquals(0, returnedBundle.getEntry().size());
}
@Test
public void createResourceSearchParameter_withExpressionMetaSecurity_succeeds(){
String spCallingName = "securitySP";
String secCode = "secCode";
SearchParameter searchParameter = new SearchParameter();
searchParameter.setStatus(Enumerations.PublicationStatus.ACTIVE);
searchParameter.setCode(spCallingName);
searchParameter.addBase("Patient").addBase("Account");
searchParameter.setType(Enumerations.SearchParamType.TOKEN);
searchParameter.setExpression("meta.security");
ourClient.create().resource(searchParameter).execute();
mySearchParamRegistry.forceRefresh();
IIdType expectedPatientId = createPatientWithMeta(new Meta().addSecurity(new Coding().setCode(secCode)));
IIdType dontCare = createPatientWithMeta(new Meta().addSecurity(new Coding().setCode("L")));
Bundle searchResultBundle = ourClient.search().forResource(Patient.class).where(new StringClientParam(spCallingName).matches().value(secCode)).returnBundle(Bundle.class).execute();
List<String> foundPatients = toUnqualifiedVersionlessIdValues(searchResultBundle);
assertEquals(1, foundPatients.size());
assertEquals(foundPatients.get(0), expectedPatientId.getValue());
}
@Test
public void createSearchParameter_with2Expressions_succeeds(){
SearchParameter searchParameter = new SearchParameter();
searchParameter.setStatus(Enumerations.PublicationStatus.ACTIVE);
searchParameter.setCode("myGender");
searchParameter.addBase("Patient").addBase("Person");
searchParameter.setType(Enumerations.SearchParamType.TOKEN);
searchParameter.setExpression("Patient.gender|Person.gender");
MethodOutcome result= ourClient.create().resource(searchParameter).execute();
assertEquals(true, result.getCreated());
}
@Test
public void testSuppressNoExtensibleWarnings() {
RequestValidatingInterceptor interceptor = new RequestValidatingInterceptor();
interceptor.setFailOnSeverity(ResultSeverityEnum.INFORMATION);
FhirInstanceValidator val = new FhirInstanceValidator(myValidationSupport);
val.setNoExtensibleWarnings(true);
interceptor.addValidatorModule(val);
ourRestServer.registerInterceptor(interceptor);
try {
CodeableConcept codeableConcept = new CodeableConcept();
Coding codingCode = codeableConcept.addCoding();
codingCode.setCode(DeviceStatus.ACTIVE.toCode());
codingCode.setSystem(DeviceStatus.ACTIVE.getSystem());
Device device = new Device();
Identifier identifier = device.addIdentifier();
identifier.setType(codeableConcept); // Not valid against valueset with 'Extensible' binding strength
ourClient.create().resource(device).execute().getId();
} finally {
ourRestServer.unregisterInterceptor(interceptor);
}
}
@Test
public void testSuppressNoBindingMessage() {
RequestValidatingInterceptor interceptor = new RequestValidatingInterceptor();
interceptor.setFailOnSeverity(ResultSeverityEnum.INFORMATION);
FhirInstanceValidator val = new FhirInstanceValidator(myValidationSupport);
val.setNoBindingMsgSuppressed(true);
interceptor.addValidatorModule(val);
ourRestServer.registerInterceptor(interceptor);
try {
CodeableConcept codeableConcept = new CodeableConcept();
Coding codingCode = codeableConcept.addCoding();
codingCode.setSystem(DeviceStatus.ACTIVE.toCode());
codingCode.setSystem(DeviceStatus.ACTIVE.getSystem());
Task task = new Task();
task.setStatus(Task.TaskStatus.DRAFT);
task.setIntent(Task.TaskIntent.FILLERORDER);
task.setCode(codeableConcept); // Task.code has no source/binding
ourClient.create().resource(task).execute().getId();
} finally {
ourRestServer.unregisterInterceptor(interceptor);
}
}
/**
* See #872
*/
@Test
public void testExtensionUrlWithHl7UrlPost() throws IOException {
ValueSet vs = myValidationSupport.fetchResource(ValueSet.class, "http:https://hl7.org/fhir/ValueSet/v3-ActInvoiceGroupCode");
myValueSetDao.create(vs);
RequestValidatingInterceptor interceptor = new RequestValidatingInterceptor();
FhirInstanceValidator val = new FhirInstanceValidator(myValidationSupport);
interceptor.addValidatorModule(val);
ourRestServer.registerInterceptor(interceptor);
try {
String input = IOUtils.toString(ResourceProviderDstu3Test.class.getResourceAsStream("/bug872-ext-with-hl7-url.json"), Charsets.UTF_8);
HttpPost post = new HttpPost(ourServerBase + "/Patient/aaa");
post.setEntity(new StringEntity(input, ContentType.APPLICATION_JSON));
CloseableHttpResponse resp = ourHttpClient.execute(post);
try {
String respString = IOUtils.toString(resp.getEntity().getContent(), Charsets.UTF_8);
ourLog.info(respString);
assertEquals(400, resp.getStatusLine().getStatusCode());
} finally {
IOUtils.closeQuietly(resp);
}
} finally {
ourRestServer.unregisterInterceptor(interceptor);
}
}
@BeforeEach
@Override
public void before() throws Exception {
super.before();
myFhirContext.setParserErrorHandler(new StrictErrorHandler());
myDaoConfig.setAllowMultipleDelete(true);
myDaoConfig.setReuseCachedSearchResultsForMillis(null);
mySearchCoordinatorSvcRaw = AopTestUtils.getTargetObject(ourSearchCoordinatorSvc);
}
private void checkParamMissing(String paramName) throws IOException {
HttpGet get = new HttpGet(ourServerBase + "/Observation?" + paramName + ":missing=false");
CloseableHttpResponse resp = ourHttpClient.execute(get);
IOUtils.closeQuietly(resp.getEntity().getContent());
assertEquals(200, resp.getStatusLine().getStatusCode());
}
private ArrayList<IBaseResource> genResourcesOfType(Bundle theRes, Class<? extends IBaseResource> theClass) {
ArrayList<IBaseResource> retVal = new ArrayList<IBaseResource>();
for (BundleEntryComponent next : theRes.getEntry()) {
if (next.getResource() != null) {
if (theClass.isAssignableFrom(next.getResource().getClass())) {
retVal.add(next.getResource());
}
}
}
return retVal;
}
/**
* See #484
*/
@Test
public void saveAndRetrieveBasicResource() throws IOException {
String input = IOUtils.toString(getClass().getResourceAsStream("/basic-stu3.xml"), StandardCharsets.UTF_8);
String respString = ourClient.transaction().withBundle(input).prettyPrint().execute();
ourLog.info(respString);
Bundle bundle = myFhirContext.newXmlParser().parseResource(Bundle.class, respString);
IdType id = new IdType(bundle.getEntry().get(0).getResponse().getLocation());
Basic basic = ourClient.read().resource(Basic.class).withId(id).execute();
List<Extension> exts = basic.getExtensionsByUrl("http:https://localhost:1080/hapi-fhir-jpaserver-example/baseDstu2/StructureDefinition/DateID");
assertEquals(1, exts.size());
}
private List<String> searchAndReturnUnqualifiedIdValues(String uri) throws IOException {
List<String> ids;
HttpGet get = new HttpGet(uri);
CloseableHttpResponse response = ourHttpClient.execute(get);
try {
String resp = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
ourLog.info(resp);
Bundle bundle = myFhirContext.newXmlParser().parseResource(Bundle.class, resp);
ids = toUnqualifiedIdValues(bundle);
} finally {
IOUtils.closeQuietly(response);
}
return ids;
}
private List<String> searchAndReturnUnqualifiedVersionlessIdValues(String uri) throws IOException {
List<String> ids;
HttpGet get = new HttpGet(uri);
CloseableHttpResponse response = ourHttpClient.execute(get);
try {
String resp = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
ourLog.info(resp);
Bundle bundle = myFhirContext.newXmlParser().parseResource(Bundle.class, resp);
ids = toUnqualifiedVersionlessIdValues(bundle);
} finally {
IOUtils.closeQuietly(response);
}
return ids;
}
// Y
@Test
public void testBundleCreate() throws Exception {
IGenericClient client = ourClient;
String resBody = IOUtils.toString(ResourceProviderDstu3Test.class.getResource("/document-father-dstu3.json"), StandardCharsets.UTF_8);
IIdType id = client.create().resource(resBody).execute().getId();
ourLog.info("Created: {}", id);
Bundle bundle = client.read().resource(Bundle.class).withId(id).execute();
ourLog.info(myFhirContext.newJsonParser().setPrettyPrint(true).encodeResourceToString(bundle));
}
@Test
public void testSearchWithIncludeAllWithNotResolvableReference() {
// Arrange
myDaoConfig.setAllowExternalReferences(true);
Patient patient = new Patient();
patient.addName().setFamily(UUID.randomUUID().toString());
IIdType createdPatientId = ourClient.create().resource(patient).execute().getId();
RelatedArtifact relatedArtifactInternalReference = new RelatedArtifact();
relatedArtifactInternalReference.setDisplay(UUID.randomUUID().toString());
relatedArtifactInternalReference.setType(RelatedArtifact.RelatedArtifactType.PREDECESSOR);
relatedArtifactInternalReference.setResource(new Reference(createdPatientId.toUnqualifiedVersionless()));
RelatedArtifact relatedArtifactExternalReference = new RelatedArtifact();
relatedArtifactExternalReference.setDisplay(UUID.randomUUID().toString());
relatedArtifactExternalReference.setType(RelatedArtifact.RelatedArtifactType.PREDECESSOR);
relatedArtifactExternalReference.setResource(new Reference("http:https://not-local-host.dk/hapi-fhir-jpaserver/fhir/Patient/2"));
PlanDefinition planDefinition = new PlanDefinition();
planDefinition.setStatus(Enumerations.PublicationStatus.ACTIVE);
planDefinition.setName(UUID.randomUUID().toString());
planDefinition.setRelatedArtifact(Arrays.asList(relatedArtifactInternalReference, relatedArtifactExternalReference));
IIdType createdPlanDefinitionId = ourClient.create().resource(planDefinition).execute().getId();
// Act
Bundle returnedBundle = ourClient.search()
.forResource(PlanDefinition.class)
.include(PlanDefinition.INCLUDE_ALL)
.where(PlanDefinition.NAME.matches().value(planDefinition.getName()))
.returnBundle(Bundle.class)
.execute();
// Assert
assertEquals(returnedBundle.getEntry().size(), 2);
assertEquals(createdPlanDefinitionId, genResourcesOfType(returnedBundle, PlanDefinition.class).get(0).getIdElement());
assertEquals(createdPatientId, genResourcesOfType(returnedBundle, Patient.class).get(0).getIdElement());
}
@Test
public void testBundleCreateWithTypeTransaction() throws Exception {
IGenericClient client = ourClient;
String resBody = IOUtils.toString(ResourceProviderDstu3Test.class.getResource("/document-father-dstu3.json"), StandardCharsets.UTF_8);
resBody = resBody.replace("\"type\": \"document\"", "\"type\": \"transaction\"");
try {
client.create().resource(resBody).execute().getId();
fail();
} catch (UnprocessableEntityException e) {
assertThat(e.getMessage(), containsString("Unable to store a Bundle resource on this server with a Bundle.type value of: transaction. Note that if you are trying to perform a FHIR transaction or batch operation you should POST the Bundle resource to the Base URL of the server, not to the /Bundle endpoint."));
}
}
@Test
public void testSearchChainedReference() {
Patient p = new Patient();
p.addName().setFamily("SMITH");
IIdType pid = ourClient.create().resource(p).execute().getId().toUnqualifiedVersionless();
QuestionnaireResponse qr = new QuestionnaireResponse();
qr.getSubject().setReference(pid.getValue());
ourClient.create().resource(qr).execute();
Subscription subs = new Subscription();
subs.setStatus(SubscriptionStatus.ACTIVE);
subs.getChannel().setType(SubscriptionChannelType.WEBSOCKET);
subs.setCriteria("Observation?");
IIdType id = ourClient.create().resource(subs).execute().getId().toUnqualifiedVersionless();
// Unqualified (doesn't work because QuestionnaireRespone.subject is a Refercence(Any))
try {
ourClient
.search()
.forResource(QuestionnaireResponse.class)
.where(QuestionnaireResponse.SUBJECT.hasChainedProperty(Patient.FAMILY.matches().value("SMITH")))
.returnBundle(Bundle.class)
.execute();
fail();
} catch (InvalidRequestException e) {
assertEquals("HTTP 400 Bad Request: " + Msg.code(1245) + "Unable to perform search for unqualified chain 'subject' as this SearchParameter does not declare any target types. Add a qualifier of the form 'subject:[ResourceType]' to perform this search.", e.getMessage());
}
// Qualified
Bundle resp = ourClient
.search()
.forResource(QuestionnaireResponse.class)
.where(QuestionnaireResponse.SUBJECT.hasChainedProperty("Patient", Patient.FAMILY.matches().value("SMITH")))
.returnBundle(Bundle.class)
.execute();
assertEquals(1, resp.getEntry().size());
// Qualified With an invalid name
try {
ourClient
.search()
.forResource(QuestionnaireResponse.class)
.where(QuestionnaireResponse.SUBJECT.hasChainedProperty("FOO", Patient.FAMILY.matches().value("SMITH")))
.returnBundle(Bundle.class)
.execute();
} catch (InvalidRequestException e) {
assertEquals("HTTP 400 Bad Request: " + Msg.code(1250) + "Invalid/unsupported resource type: \"FOO\"", e.getMessage());
}
}
@Test
public void testCodeSearch() {
Subscription subs = new Subscription();
subs.setStatus(SubscriptionStatus.ACTIVE);
subs.getChannel().setType(SubscriptionChannelType.WEBSOCKET);
subs.setCriteria("Observation?");
IIdType id = ourClient.create().resource(subs).execute().getId().toUnqualifiedVersionless();
//@formatter:off
Bundle resp = ourClient
.search()
.forResource(Subscription.class)
.where(Subscription.TYPE.exactly().code(SubscriptionChannelType.WEBSOCKET.toCode()))
.and(Subscription.STATUS.exactly().code(SubscriptionStatus.ACTIVE.toCode()))
.returnBundle(Bundle.class)
.execute();
//@formatter:off
assertThat(toUnqualifiedVersionlessIds(resp), contains(id));
//@formatter:off
resp = ourClient
.search()
.forResource(Subscription.class)
.where(Subscription.TYPE.exactly().systemAndCode(SubscriptionChannelType.WEBSOCKET.getSystem(), SubscriptionChannelType.WEBSOCKET.toCode()))
.and(Subscription.STATUS.exactly().systemAndCode(SubscriptionStatus.ACTIVE.getSystem(), SubscriptionStatus.ACTIVE.toCode()))
.returnBundle(Bundle.class)
.execute();
//@formatter:off
assertThat(toUnqualifiedVersionlessIds(resp), contains(id));
//@formatter:off
resp = ourClient
.search()
.forResource(Subscription.class)
.where(Subscription.TYPE.exactly().systemAndCode(SubscriptionChannelType.WEBSOCKET.getSystem(), SubscriptionChannelType.WEBSOCKET.toCode()))
.and(Subscription.STATUS.exactly().systemAndCode("foo", SubscriptionStatus.ACTIVE.toCode()))
.returnBundle(Bundle.class)
.execute();
//@formatter:off
assertThat(toUnqualifiedVersionlessIds(resp), empty());
}
@Test
public void testCountParam() {
List<IBaseResource> resources = new ArrayList<IBaseResource>();
for (int i = 0; i < 100; i++) {
Organization org = new Organization();
org.setName("rpdstu2_testCountParam_01");
resources.add(org);
}
ourClient.transaction().withResources(resources).prettyPrint().encodedXml().execute();
Bundle found = ourClient.search().forResource(Organization.class)
.where(Organization.NAME.matches().value("rpdstu2_testCountParam_01"))
.totalMode(SearchTotalModeEnum.ACCURATE)
.count(10).returnBundle(Bundle.class).execute();
assertEquals(100, found.getTotal());
assertEquals(10, found.getEntry().size());
found = ourClient.search().forResource(Organization.class).where(Organization.NAME.matches().value("rpdstu2_testCountParam_01")).count(50).returnBundle(Bundle.class).execute();
assertEquals(50, found.getEntry().size());
}
/**
* See #438
*/
@Test
public void testCreateAndUpdateBinary() throws Exception {
byte[] arr = {1, 21, 74, 123, -44};
Binary binary = new Binary();
binary.setContent(arr);
binary.setContentType("dansk");
IIdType resource = ourClient.create().resource(binary).execute().getId();
Binary fromDB = ourClient.read().resource(Binary.class).withId(resource.toVersionless()).execute();
assertEquals("1", fromDB.getIdElement().getVersionIdPart());
arr[0] = 2;
HttpPut putRequest = new HttpPut(ourServerBase + "/Binary/" + resource.getIdPart());
putRequest.setEntity(new ByteArrayEntity(arr, ContentType.parse("dansk")));
CloseableHttpResponse resp = ourHttpClient.execute(putRequest);
try {
assertEquals(200, resp.getStatusLine().getStatusCode());
assertEquals(resource.withVersion("2").getValue(), resp.getFirstHeader("Content-Location").getValue());
} finally {
IOUtils.closeQuietly(resp);
}
fromDB = ourClient.read().resource(Binary.class).withId(resource.toVersionless()).execute();
assertEquals("2", fromDB.getIdElement().getVersionIdPart());
arr[0] = 3;
fromDB.setContent(arr);
String encoded = myFhirContext.newJsonParser().encodeResourceToString(fromDB);
putRequest = new HttpPut(ourServerBase + "/Binary/" + resource.getIdPart());
putRequest.setEntity(new StringEntity(encoded, ContentType.parse("application/json+fhir")));
resp = ourHttpClient.execute(putRequest);
try {
assertEquals(200, resp.getStatusLine().getStatusCode());
assertEquals(resource.withVersion("3").getValue(), resp.getFirstHeader(Constants.HEADER_CONTENT_LOCATION).getValue());
} finally {
IOUtils.closeQuietly(resp);
}
fromDB = ourClient.read().resource(Binary.class).withId(resource.toVersionless()).execute();
assertEquals("3", fromDB.getIdElement().getVersionIdPart());
// Now an update with the wrong ID in the body
arr[0] = 4;
binary.setId("");
encoded = myFhirContext.newJsonParser().encodeResourceToString(binary);
putRequest = new HttpPut(ourServerBase + "/Binary/" + resource.getIdPart());
putRequest.setEntity(new StringEntity(encoded, ContentType.parse("application/json+fhir")));
resp = ourHttpClient.execute(putRequest);
try {
assertEquals(400, resp.getStatusLine().getStatusCode());
} finally {
IOUtils.closeQuietly(resp);
}
fromDB = ourClient.read().resource(Binary.class).withId(resource.toVersionless()).execute();
assertEquals("3", fromDB.getIdElement().getVersionIdPart());
}
/**
* Issue submitted by Bryn
*/
@Test
public void testCreateBundle() throws IOException {
String input = IOUtils.toString(getClass().getResourceAsStream("/bryn-bundle.json"), StandardCharsets.UTF_8);
Validate.notNull(input);
ourClient.create().resource(input).execute().getResource();
}
@Test
public void testUrlSearchWithNoStoreHeader() throws IOException {
submitBundle("/dstu3/no-store-header/patient-bundle.json");
submitBundle("/dstu3/no-store-header/practitioner-bundle.json");
submitBundle("/dstu3/no-store-header/episodeofcare-bundle.json");
Bundle responseBundle;
responseBundle = ourClient
.search()
.forResource(EpisodeOfCare.class)
.where(new StringClientParam("_id").matches().value("ECC19005O3"))
.where(new StringClientParam("_include").matches().value("*"))
.where(new StringClientParam("_revinclude").matches().value("*"))
.where(new StringClientParam("_count").matches().value("300"))
.returnBundle(Bundle.class)
.encodedJson()
.execute();
String bundleContents = "\n * " + responseBundle.getEntry().stream().map(t->t.getResource().getIdElement().toUnqualifiedVersionless().getValue()).collect(Collectors.joining("\n * "));
assertEquals(3, responseBundle.getEntry().size(), bundleContents);
runInTransaction(()->{
ourLog.info("Resources:\n * {}", myResourceTableDao
.findAll()
.stream()
.sorted(((o1, o2) -> (int) (o1.getId() - o2.getId())))
.map(t->t.getId() + " - " + t.getIdDt().toUnqualifiedVersionless().getValue())
.collect(Collectors.joining("\n * ")));
});
// Now try the exact same search again but using the Cache-Control no-store Header
responseBundle = ourClient
.search()
.forResource(EpisodeOfCare.class)
.where(new StringClientParam("_id").matches().value("ECC19005O3"))
.where(new StringClientParam("_include").matches().value("*"))
.where(new StringClientParam("_revinclude").matches().value("*"))
.where(new StringClientParam("_count").matches().value("300"))
.cacheControl(new CacheControlDirective().setNoStore(true))
.returnBundle(Bundle.class)
.encodedJson()
.execute();
bundleContents = "\n * " + responseBundle.getEntry().stream().map(t->t.getResource().getIdElement().toUnqualifiedVersionless().getValue()).collect(Collectors.joining("\n * "));
assertEquals(3, responseBundle.getEntry().size(), bundleContents);
}
private void submitBundle(String bundleName) throws IOException {
String input = IOUtils.toString(getClass().getResourceAsStream(bundleName), StandardCharsets.UTF_8);
Validate.notNull(input);
ourClient.transaction().withBundle(input).execute();
}
@Test
public void testCreateConditional() {
Patient patient = new Patient();
patient.addIdentifier().setSystem("http:https://uhn.ca/mrns").setValue("100");
patient.addName().setFamily("Tester").addGiven("Raghad");
MethodOutcome output1 = ourClient.update().resource(patient).conditionalByUrl("Patient?identifier=http:https://uhn.ca/mrns|100").execute();
patient = new Patient();
patient.addIdentifier().setSystem("http:https://uhn.ca/mrns").setValue("100");
patient.addName().setFamily("Tester").addGiven("Raghad");
MethodOutcome output2 = ourClient.update().resource(patient).conditionalByUrl("Patient?identifier=http:https://uhn.ca/mrns|100").execute();
assertEquals(output1.getId().getIdPart(), output2.getId().getIdPart());
}
@Test
public void testCreateIncludesRequestValidatorInterceptorOutcome() {
RequestValidatingInterceptor interceptor = new RequestValidatingInterceptor();
assertTrue(interceptor.isAddValidationResultsToResponseOperationOutcome());
interceptor.setFailOnSeverity(null);
ourRestServer.registerInterceptor(interceptor);
ourClient.registerInterceptor(new IClientInterceptor() {
@Override
public void interceptRequest(IHttpRequest theRequest) {
theRequest.addHeader(Constants.HEADER_PREFER, Constants.HEADER_PREFER_RETURN + "=" + Constants.HEADER_PREFER_RETURN_OPERATION_OUTCOME);
}
@Override
public void interceptResponse(IHttpResponse theResponse) { // TODO Auto-generated method stu
}
});
try {
// Missing status, which is mandatory
Observation obs = new Observation();
obs.addIdentifier().setSystem("urn:foo").setValue("bar");
IBaseResource outcome = ourClient.create().resource(obs).execute().getOperationOutcome();
String encodedOo = myFhirContext.newJsonParser().setPrettyPrint(true).encodeResourceToString(outcome);
ourLog.info(encodedOo);
assertThat(encodedOo, containsString("cvc-complex-type.2.4.b"));
assertThat(encodedOo, containsString("Successfully created resource \\\"Observation/"));
interceptor.setAddValidationResultsToResponseOperationOutcome(false);
outcome = ourClient.create().resource(obs).execute().getOperationOutcome();
encodedOo = myFhirContext.newJsonParser().setPrettyPrint(true).encodeResourceToString(outcome);
ourLog.info(encodedOo);
assertThat(encodedOo, not(containsString("cvc-complex-type.2.4.b")));
assertThat(encodedOo, containsString("Successfully created resource \\\"Observation/"));
} finally {
ourRestServer.unregisterInterceptor(interceptor);
}
}
@Test
@Disabled
public void testCreateQuestionnaireResponseWithValidation() {
CodeSystem cs = new CodeSystem();
cs.setUrl("http:https://urn/system");
cs.addConcept().setCode("code0");
ourClient.create().resource(cs).execute();
ValueSet options = new ValueSet();
options.getCompose().addInclude().setSystem("http:https://urn/system");
IIdType optId = ourClient.create().resource(options).execute().getId();
Questionnaire q = new Questionnaire();
q.addItem().setLinkId("link0").setRequired(false).setType(QuestionnaireItemType.CHOICE).setOptions(new Reference(optId));
IIdType qId = ourClient.create().resource(q).execute().getId();
QuestionnaireResponse qa;
// Good code
qa = new QuestionnaireResponse();
qa.getQuestionnaire().setReference(qId.toUnqualifiedVersionless().getValue());
qa.addItem().setLinkId("link0").addAnswer().setValue(new Coding().setSystem("urn:system").setCode("code0"));
ourClient.create().resource(qa).execute();
// Bad code
qa = new QuestionnaireResponse();
qa.getQuestionnaire().setReference(qId.toUnqualifiedVersionless().getValue());
qa.addItem().setLinkId("link0").addAnswer().setValue(new Coding().setSystem("urn:system").setCode("code1"));
try {
ourClient.create().resource(qa).execute();
fail();
} catch (UnprocessableEntityException e) {
assertThat(e.getMessage(), containsString("Question with linkId[link0]"));
}
}
@Test
public void testCreateResourceConditional() throws IOException {
String methodName = "testCreateResourceConditional";
Patient pt = new Patient();
pt.addName().setFamily(methodName);
String resource = myFhirContext.newXmlParser().encodeResourceToString(pt);
HttpPost post = new HttpPost(ourServerBase + "/Patient");
post.addHeader(Constants.HEADER_IF_NONE_EXIST, "Patient?name=" + methodName);
post.setEntity(new StringEntity(resource, ContentType.create(Constants.CT_FHIR_XML, "UTF-8")));
CloseableHttpResponse response = ourHttpClient.execute(post);
IdType id;
try {
assertEquals(201, response.getStatusLine().getStatusCode());
String newIdString = response.getFirstHeader(Constants.HEADER_LOCATION_LC).getValue();
assertThat(newIdString, startsWith(ourServerBase + "/Patient/"));
id = new IdType(newIdString);
} finally {
response.close();
}
post = new HttpPost(ourServerBase + "/Patient");
post.setEntity(new StringEntity(resource, ContentType.create(Constants.CT_FHIR_XML, "UTF-8")));
post.addHeader(Constants.HEADER_IF_NONE_EXIST, "Patient?name=" + methodName);
response = ourHttpClient.execute(post);
try {
assertEquals(200, response.getStatusLine().getStatusCode());
String newIdString = response.getFirstHeader(Constants.HEADER_LOCATION_LC).getValue();
assertEquals(id.getValue(), newIdString); // version should match for conditional create
} finally {
response.close();
}
}
@Test
public void testCreateResourceConditionalComplex() throws IOException {
Patient pt = new Patient();
pt.addIdentifier().setSystem("http:https://general-hospital.co.uk/Identifiers").setValue("09832345234543876876");
String resource = myFhirContext.newXmlParser().encodeResourceToString(pt);
HttpPost post = new HttpPost(ourServerBase + "/Patient");
post.addHeader(Constants.HEADER_IF_NONE_EXIST, "Patient?identifier=http:https://general-hospital.co.uk/Identifiers|09832345234543876876");
post.setEntity(new StringEntity(resource, ContentType.create(Constants.CT_FHIR_XML, "UTF-8")));
IdType id;
CloseableHttpResponse response = ourHttpClient.execute(post);
try {
assertEquals(201, response.getStatusLine().getStatusCode());
String newIdString = response.getFirstHeader(Constants.HEADER_LOCATION_LC).getValue();
assertThat(newIdString, startsWith(ourServerBase + "/Patient/"));
id = new IdType(newIdString);
} finally {
response.close();
}
IdType id2;
response = ourHttpClient.execute(post);
try {
assertEquals(200, response.getStatusLine().getStatusCode());
String newIdString = response.getFirstHeader(Constants.HEADER_LOCATION_LC).getValue();
assertThat(newIdString, startsWith(ourServerBase + "/Patient/"));
id2 = new IdType(newIdString);
} finally {
response.close();
}
// //@formatter:off
// IIdType id3 = ourClient
// .update()
// .resource(pt)
// .conditionalByUrl("Patient?identifier=http:https://general-hospital.co.uk/Identifiers|09832345234543876876")
// .execute().getId();
// //@formatter:on
assertEquals(id.getValue(), id2.getValue());
}
@Test
public void testCreateResourceReturnsRepresentationByDefault() throws IOException {
String resource = "<Patient xmlns=\"http:https://hl7.org/fhir\"></Patient>";
HttpPost post = new HttpPost(ourServerBase + "/Patient");
post.setEntity(new StringEntity(resource, ContentType.create(Constants.CT_FHIR_XML, "UTF-8")));
CloseableHttpResponse response = ourHttpClient.execute(post);
try {
assertEquals(201, response.getStatusLine().getStatusCode());
String respString = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
ourLog.info(response.toString());
ourLog.info(respString);
assertThat(respString, startsWith("<Patient xmlns=\"http:https://hl7.org/fhir\">"));
assertThat(respString, endsWith("</Patient>"));
} finally {
response.getEntity().getContent().close();
response.close();
}
}
@Test
public void testCreateResourceReturnsOperationOutcome() throws IOException {
String resource = "<Patient xmlns=\"http:https://hl7.org/fhir\"></Patient>";
HttpPost post = new HttpPost(ourServerBase + "/Patient");
post.setEntity(new StringEntity(resource, ContentType.create(Constants.CT_FHIR_XML, "UTF-8")));
post.addHeader(Constants.HEADER_PREFER, Constants.HEADER_PREFER_RETURN + "=" + Constants.HEADER_PREFER_RETURN_OPERATION_OUTCOME);
CloseableHttpResponse response = ourHttpClient.execute(post);
try {
assertEquals(201, response.getStatusLine().getStatusCode());
String respString = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
ourLog.info(response.toString());
ourLog.info(respString);
assertThat(respString, containsString("<OperationOutcome xmlns=\"http:https://hl7.org/fhir\">"));
} finally {
response.getEntity().getContent().close();
response.close();