/
GenericClient.java
2187 lines (1844 loc) 路 71.5 KB
/
GenericClient.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.rest.client.impl;
/*
* #%L
* HAPI FHIR - Client Framework
* %%
* Copyright (C) 2014 - 2017 University Health Network
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import java.io.IOException;
import java.io.Reader;
import java.util.*;
import java.util.Map.Entry;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.hl7.fhir.instance.model.api.*;
import ca.uhn.fhir.context.*;
import ca.uhn.fhir.model.api.IQueryParameterType;
import ca.uhn.fhir.model.api.Include;
import ca.uhn.fhir.model.base.resource.BaseOperationOutcome;
import ca.uhn.fhir.model.primitive.*;
import ca.uhn.fhir.parser.DataFormatException;
import ca.uhn.fhir.parser.IParser;
import ca.uhn.fhir.rest.api.*;
import ca.uhn.fhir.rest.client.api.*;
import ca.uhn.fhir.rest.client.exceptions.NonFhirResponseException;
import ca.uhn.fhir.rest.client.interceptor.LoggingInterceptor;
import ca.uhn.fhir.rest.client.method.*;
import ca.uhn.fhir.rest.gclient.*;
import ca.uhn.fhir.rest.param.*;
import ca.uhn.fhir.rest.server.exceptions.*;
import ca.uhn.fhir.util.*;
/**
* @author James Agnew
* @author Doug Martin (Regenstrief Center for Biomedical Informatics)
*/
public class GenericClient extends BaseClient implements IGenericClient {
private static final String I18N_CANNOT_DETEMINE_RESOURCE_TYPE = GenericClient.class.getName() + ".cannotDetermineResourceTypeFromUri";
private static final String I18N_INCOMPLETE_URI_FOR_READ = GenericClient.class.getName() + ".incompleteUriForRead";
private static final String I18N_NO_VERSION_ID_FOR_VREAD = GenericClient.class.getName() + ".noVersionIdForVread";
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(GenericClient.class);
private FhirContext myContext;
private IHttpRequest myLastRequest;
private boolean myLogRequestAndResponse;
/**
* For now, this is a part of the internal API of HAPI - Use with caution as this method may change!
*/
public GenericClient(FhirContext theContext, IHttpClient theHttpClient, String theServerBase, RestfulClientFactory theFactory) {
super(theHttpClient, theServerBase, theFactory);
myContext = theContext;
}
@Override
public IFetchConformanceUntyped capabilities() {
return new FetchConformanceInternal();
}
@Override
public ICreate create() {
return new CreateInternal();
}
@Override
public IDelete delete() {
return new DeleteInternal();
}
private <T extends IBaseResource> T doReadOrVRead(final Class<T> theType, IIdType theId, boolean theVRead, ICallable<T> theNotModifiedHandler, String theIfVersionMatches, Boolean thePrettyPrint,
SummaryEnum theSummary, EncodingEnum theEncoding, Set<String> theSubsetElements) {
String resName = toResourceName(theType);
IIdType id = theId;
if (!id.hasBaseUrl()) {
id = new IdDt(resName, id.getIdPart(), id.getVersionIdPart());
}
HttpGetClientInvocation invocation;
if (id.hasBaseUrl()) {
if (theVRead) {
invocation = ReadMethodBinding.createAbsoluteVReadInvocation(getFhirContext(), id);
} else {
invocation = ReadMethodBinding.createAbsoluteReadInvocation(getFhirContext(), id);
}
} else {
if (theVRead) {
invocation = ReadMethodBinding.createVReadInvocation(getFhirContext(), id, resName);
} else {
invocation = ReadMethodBinding.createReadInvocation(getFhirContext(), id, resName);
}
}
if (isKeepResponses()) {
myLastRequest = invocation.asHttpRequest(getServerBase(), createExtraParams(), getEncoding(), isPrettyPrint());
}
if (theIfVersionMatches != null) {
invocation.addHeader(Constants.HEADER_IF_NONE_MATCH, '"' + theIfVersionMatches + '"');
}
boolean allowHtmlResponse = (theSummary == SummaryEnum.TEXT) || (theSummary == null && getSummary() == SummaryEnum.TEXT);
ResourceResponseHandler<T> binding = new ResourceResponseHandler<T>(theType, (Class<? extends IBaseResource>) null, id, allowHtmlResponse);
if (theNotModifiedHandler == null) {
return invokeClient(myContext, binding, invocation, theEncoding, thePrettyPrint, myLogRequestAndResponse, theSummary, theSubsetElements);
}
try {
return invokeClient(myContext, binding, invocation, theEncoding, thePrettyPrint, myLogRequestAndResponse, theSummary, theSubsetElements);
} catch (NotModifiedException e) {
return theNotModifiedHandler.call();
}
}
// public IResource read(UriDt url) {
// return read(inferResourceClass(url), url);
// }
//
// @SuppressWarnings("unchecked")
// public <T extends IResource> T read(final Class<T> theType, UriDt url) {
// return (T) invoke(theType, url, new ResourceResponseHandler<T>(theType));
// }
//
// public Bundle search(UriDt url) {
// return search(inferResourceClass(url), url);
// }
@Override
public IFetchConformanceUntyped fetchConformance() {
return new FetchConformanceInternal();
}
@Override
public void forceConformanceCheck() {
super.forceConformanceCheck();
}
@Override
public FhirContext getFhirContext() {
return myContext;
}
public IHttpRequest getLastRequest() {
return myLastRequest;
}
protected String getPreferredId(IBaseResource theResource, String theId) {
if (isNotBlank(theId)) {
return theId;
}
return theResource.getIdElement().getIdPart();
}
// @Override
// public <T extends IBaseResource> T read(final Class<T> theType, IdDt theId) {
// return doReadOrVRead(theType, theId, false, null, null);
// }
@Override
public IHistory history() {
return new HistoryInternal();
}
/**
* @deprecated Use {@link LoggingInterceptor} as a client interceptor registered to your
* client instead, as this provides much more fine-grained control over what is logged. This
* method will be removed at some point (deprecated in HAPI 1.6 - 2016-06-16)
*/
@Deprecated
public boolean isLogRequestAndResponse() {
return myLogRequestAndResponse;
}
@Override
public IGetPage loadPage() {
return new LoadPageInternal();
}
@Override
public IMeta meta() {
return new MetaInternal();
}
@Override
public IOperation operation() {
return new OperationInternal();
}
@Override
public IPatch patch() {
return new PatchInternal();
}
@Override
public IRead read() {
return new ReadInternal();
}
@Override
public <T extends IBaseResource> T read(Class<T> theType, String theId) {
return read(theType, new IdDt(theId));
}
@Override
public <T extends IBaseResource> T read(final Class<T> theType, UriDt theUrl) {
IdDt id = theUrl instanceof IdDt ? ((IdDt) theUrl) : new IdDt(theUrl);
return doReadOrVRead(theType, id, false, null, null, false, null, null, null);
}
@Override
public IBaseResource read(UriDt theUrl) {
IdDt id = new IdDt(theUrl);
String resourceType = id.getResourceType();
if (isBlank(resourceType)) {
throw new IllegalArgumentException(myContext.getLocalizer().getMessage(I18N_INCOMPLETE_URI_FOR_READ, theUrl.getValueAsString()));
}
RuntimeResourceDefinition def = myContext.getResourceDefinition(resourceType);
if (def == null) {
throw new IllegalArgumentException(myContext.getLocalizer().getMessage(I18N_CANNOT_DETEMINE_RESOURCE_TYPE, theUrl.getValueAsString()));
}
return read(def.getImplementingClass(), id);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public IUntypedQuery search() {
return new SearchInternal();
}
/**
* For now, this is a part of the internal API of HAPI - Use with caution as this method may change!
*/
public void setLastRequest(IHttpRequest theLastRequest) {
myLastRequest = theLastRequest;
}
@Deprecated // override deprecated method
@Override
public void setLogRequestAndResponse(boolean theLogRequestAndResponse) {
myLogRequestAndResponse = theLogRequestAndResponse;
}
private String toResourceName(Class<? extends IBaseResource> theType) {
return myContext.getResourceDefinition(theType).getName();
}
@Override
public ITransaction transaction() {
return new TransactionInternal();
}
@Override
public IUpdate update() {
return new UpdateInternal();
}
@Override
public MethodOutcome update(IdDt theIdDt, IBaseResource theResource) {
BaseHttpClientInvocation invocation = MethodUtil.createUpdateInvocation(theResource, null, theIdDt, myContext);
if (isKeepResponses()) {
myLastRequest = invocation.asHttpRequest(getServerBase(), createExtraParams(), getEncoding(), isPrettyPrint());
}
OutcomeResponseHandler binding = new OutcomeResponseHandler();
MethodOutcome resp = invokeClient(myContext, binding, invocation, myLogRequestAndResponse);
return resp;
}
@Override
public MethodOutcome update(String theId, IBaseResource theResource) {
return update(new IdDt(theId), theResource);
}
@Override
public IValidate validate() {
return new ValidateInternal();
}
@Override
public MethodOutcome validate(IBaseResource theResource) {
BaseHttpClientInvocation invocation;
invocation = ValidateMethodBindingDstu2Plus.createValidateInvocation(myContext, theResource);
if (isKeepResponses()) {
myLastRequest = invocation.asHttpRequest(getServerBase(), createExtraParams(), getEncoding(), isPrettyPrint());
}
OutcomeResponseHandler binding = new OutcomeResponseHandler();
MethodOutcome resp = invokeClient(myContext, binding, invocation, myLogRequestAndResponse);
return resp;
}
@Override
public <T extends IBaseResource> T vread(final Class<T> theType, IdDt theId) {
if (theId.hasVersionIdPart() == false) {
throw new IllegalArgumentException(myContext.getLocalizer().getMessage(I18N_NO_VERSION_ID_FOR_VREAD, theId.getValue()));
}
return doReadOrVRead(theType, theId, true, null, null, false, null, null, null);
}
@Override
public <T extends IBaseResource> T vread(Class<T> theType, String theId, String theVersionId) {
IdDt resId = new IdDt(toResourceName(theType), theId, theVersionId);
return vread(theType, resId);
}
private static void addParam(Map<String, List<String>> params, String parameterName, String parameterValue) {
if (!params.containsKey(parameterName)) {
params.put(parameterName, new ArrayList<String>());
}
params.get(parameterName).add(parameterValue);
}
private static void addPreferHeader(PreferReturnEnum thePrefer, BaseHttpClientInvocation theInvocation) {
if (thePrefer != null) {
theInvocation.addHeader(Constants.HEADER_PREFER, Constants.HEADER_PREFER_RETURN + '=' + thePrefer.getHeaderValue());
}
}
private static String validateAndEscapeConditionalUrl(String theSearchUrl) {
Validate.notBlank(theSearchUrl, "Conditional URL can not be blank/null");
StringBuilder b = new StringBuilder();
boolean haveHadQuestionMark = false;
for (int i = 0; i < theSearchUrl.length(); i++) {
char nextChar = theSearchUrl.charAt(i);
if (!haveHadQuestionMark) {
if (nextChar == '?') {
haveHadQuestionMark = true;
} else if (!Character.isLetter(nextChar)) {
throw new IllegalArgumentException("Conditional URL must be in the format \"[ResourceType]?[Params]\" and must not have a base URL - Found: " + theSearchUrl);
}
b.append(nextChar);
} else {
switch (nextChar) {
case '|':
case '?':
case '$':
case ':':
b.append(UrlUtil.escape(Character.toString(nextChar)));
break;
default:
b.append(nextChar);
break;
}
}
}
return b.toString();
}
private abstract class BaseClientExecutable<T extends IClientExecutable<?, Y>, Y> implements IClientExecutable<T, Y> {
protected EncodingEnum myParamEncoding;
private List<Class<? extends IBaseResource>> myPreferResponseTypes;
protected Boolean myPrettyPrint;
private boolean myQueryLogRequestAndResponse;
private HashSet<String> mySubsetElements;
protected SummaryEnum mySummaryMode;
@Deprecated // override deprecated method
@SuppressWarnings("unchecked")
@Override
public T andLogRequestAndResponse(boolean theLogRequestAndResponse) {
myQueryLogRequestAndResponse = theLogRequestAndResponse;
return (T) this;
}
@SuppressWarnings("unchecked")
@Override
public T elementsSubset(String... theElements) {
if (theElements != null && theElements.length > 0) {
mySubsetElements = new HashSet<String>(Arrays.asList(theElements));
} else {
mySubsetElements = null;
}
return (T) this;
}
@SuppressWarnings("unchecked")
@Override
public T encodedJson() {
myParamEncoding = EncodingEnum.JSON;
return (T) this;
}
@SuppressWarnings("unchecked")
@Override
public T encodedXml() {
myParamEncoding = EncodingEnum.XML;
return (T) this;
}
protected EncodingEnum getParamEncoding() {
return myParamEncoding;
}
public List<Class<? extends IBaseResource>> getPreferResponseTypes() {
return myPreferResponseTypes;
}
public List<Class<? extends IBaseResource>> getPreferResponseTypes(Class<? extends IBaseResource> theDefault) {
if (myPreferResponseTypes != null) {
return myPreferResponseTypes;
}
return toTypeList(theDefault);
}
protected HashSet<String> getSubsetElements() {
return mySubsetElements;
}
protected <Z> Z invoke(Map<String, List<String>> theParams, IClientResponseHandler<Z> theHandler, BaseHttpClientInvocation theInvocation) {
// if (myParamEncoding != null) {
// theParams.put(Constants.PARAM_FORMAT, Collections.singletonList(myParamEncoding.getFormatContentType()));
// }
//
// if (myPrettyPrint != null) {
// theParams.put(Constants.PARAM_PRETTY, Collections.singletonList(myPrettyPrint.toString()));
// }
if (isKeepResponses()) {
myLastRequest = theInvocation.asHttpRequest(getServerBase(), theParams, getEncoding(), myPrettyPrint);
}
Z resp = invokeClient(myContext, theHandler, theInvocation, myParamEncoding, myPrettyPrint, myQueryLogRequestAndResponse || myLogRequestAndResponse, mySummaryMode, mySubsetElements);
return resp;
}
protected IBaseResource parseResourceBody(String theResourceBody) {
EncodingEnum encoding = EncodingEnum.detectEncodingNoDefault(theResourceBody);
if (encoding == null) {
throw new IllegalArgumentException(myContext.getLocalizer().getMessage(GenericClient.class, "cantDetermineRequestType"));
}
return encoding.newParser(myContext).parseResource(theResourceBody);
}
@SuppressWarnings("unchecked")
@Override
public T preferResponseType(Class<? extends IBaseResource> theClass) {
myPreferResponseTypes = null;
if (theClass != null) {
myPreferResponseTypes = new ArrayList<Class<? extends IBaseResource>>();
myPreferResponseTypes.add(theClass);
}
return (T) this;
}
@SuppressWarnings("unchecked")
@Override
public T preferResponseTypes(List<Class<? extends IBaseResource>> theClass) {
myPreferResponseTypes = theClass;
return (T) this;
}
@SuppressWarnings("unchecked")
@Override
public T prettyPrint() {
myPrettyPrint = true;
return (T) this;
}
@SuppressWarnings("unchecked")
@Override
public T summaryMode(SummaryEnum theSummary) {
mySummaryMode = theSummary;
return ((T) this);
}
}
private abstract class BaseSearch<EXEC extends IClientExecutable<?, OUTPUT>, QUERY extends IBaseQuery<QUERY>, OUTPUT> extends BaseClientExecutable<EXEC, OUTPUT> implements IBaseQuery<QUERY> {
private Map<String, List<String>> myParams = new LinkedHashMap<>();
@Override
public QUERY and(ICriterion<?> theCriterion) {
return where(theCriterion);
}
public Map<String, List<String>> getParamMap() {
return myParams;
}
@SuppressWarnings("unchecked")
@Override
public QUERY where(ICriterion<?> theCriterion) {
ICriterionInternal criterion = (ICriterionInternal) theCriterion;
String parameterName = criterion.getParameterName();
String parameterValue = criterion.getParameterValue(myContext);
if (isNotBlank(parameterValue)) {
addParam(myParams, parameterName, parameterValue);
}
return (QUERY) this;
}
@SuppressWarnings("unchecked")
@Override
public QUERY where(Map<String, List<IQueryParameterType>> theCriterion) {
Validate.notNull(theCriterion, "theCriterion must not be null");
for (Entry<String, List<IQueryParameterType>> nextEntry : theCriterion.entrySet()) {
String nextKey = nextEntry.getKey();
List<IQueryParameterType> nextValues = nextEntry.getValue();
for (IQueryParameterType nextValue : nextValues) {
addParam(myParams, nextKey, nextValue.getValueAsQueryToken(myContext));
}
}
return (QUERY) this;
}
}
private class CreateInternal extends BaseSearch<ICreateTyped, ICreateWithQueryTyped, MethodOutcome> implements ICreate, ICreateTyped, ICreateWithQuery, ICreateWithQueryTyped {
private boolean myConditional;
private PreferReturnEnum myPrefer;
private IBaseResource myResource;
private String myResourceBody;
private String mySearchUrl;
@Override
public ICreateWithQuery conditional() {
myConditional = true;
return this;
}
@Override
public ICreateTyped conditionalByUrl(String theSearchUrl) {
mySearchUrl = validateAndEscapeConditionalUrl(theSearchUrl);
return this;
}
@Override
public MethodOutcome execute() {
if (myResource == null) {
myResource = parseResourceBody(myResourceBody);
}
// If an explicit encoding is chosen, we will re-serialize to ensure the right encoding
if (getParamEncoding() != null) {
myResourceBody = null;
}
BaseHttpClientInvocation invocation;
if (mySearchUrl != null) {
invocation = MethodUtil.createCreateInvocation(myResource, myResourceBody, myContext, mySearchUrl);
} else if (myConditional) {
invocation = MethodUtil.createCreateInvocation(myResource, myResourceBody, myContext, getParamMap());
} else {
invocation = MethodUtil.createCreateInvocation(myResource, myResourceBody, myContext);
}
addPreferHeader(myPrefer, invocation);
OutcomeResponseHandler binding = new OutcomeResponseHandler(myPrefer);
Map<String, List<String>> params = new HashMap<String, List<String>>();
return invoke(params, binding, invocation);
}
@Override
public ICreateTyped prefer(PreferReturnEnum theReturn) {
myPrefer = theReturn;
return this;
}
@Override
public ICreateTyped resource(IBaseResource theResource) {
Validate.notNull(theResource, "Resource can not be null");
myResource = theResource;
return this;
}
@Override
public ICreateTyped resource(String theResourceBody) {
Validate.notBlank(theResourceBody, "Body can not be null or blank");
myResourceBody = theResourceBody;
return this;
}
}
private class DeleteInternal extends BaseSearch<IDeleteTyped, IDeleteWithQueryTyped, IBaseOperationOutcome> implements IDelete, IDeleteTyped, IDeleteWithQuery, IDeleteWithQueryTyped {
private boolean myConditional;
private IIdType myId;
private String myResourceType;
private String mySearchUrl;
@Override
public IBaseOperationOutcome execute() {
HttpDeleteClientInvocation invocation;
if (myId != null) {
invocation = DeleteMethodBinding.createDeleteInvocation(getFhirContext(), myId);
} else if (myConditional) {
invocation = DeleteMethodBinding.createDeleteInvocation(getFhirContext(), myResourceType, getParamMap());
} else {
invocation = DeleteMethodBinding.createDeleteInvocation(getFhirContext(), mySearchUrl);
}
OperationOutcomeResponseHandler binding = new OperationOutcomeResponseHandler();
Map<String, List<String>> params = new HashMap<String, List<String>>();
return invoke(params, binding, invocation);
}
@Override
public IDeleteTyped resource(IBaseResource theResource) {
Validate.notNull(theResource, "theResource can not be null");
IIdType id = theResource.getIdElement();
Validate.notNull(id, "theResource.getIdElement() can not be null");
if (id.hasResourceType() == false || id.hasIdPart() == false) {
throw new IllegalArgumentException("theResource.getId() must contain a resource type and logical ID at a minimum (e.g. Patient/1234), found: " + id.getValue());
}
myId = id;
return this;
}
@Override
public IDeleteTyped resourceById(IIdType theId) {
Validate.notNull(theId, "theId can not be null");
if (theId.hasResourceType() == false || theId.hasIdPart() == false) {
throw new IllegalArgumentException("theId must contain a resource type and logical ID at a minimum (e.g. Patient/1234)found: " + theId.getValue());
}
myId = theId;
return this;
}
@Override
public IDeleteTyped resourceById(String theResourceType, String theLogicalId) {
Validate.notBlank(theResourceType, "theResourceType can not be blank/null");
if (myContext.getResourceDefinition(theResourceType) == null) {
throw new IllegalArgumentException("Unknown resource type");
}
Validate.notBlank(theLogicalId, "theLogicalId can not be blank/null");
if (theLogicalId.contains("/")) {
throw new IllegalArgumentException("LogicalId can not contain '/' (should only be the logical ID portion, not a qualified ID)");
}
myId = new IdDt(theResourceType, theLogicalId);
return this;
}
@Override
public IDeleteWithQuery resourceConditionalByType(Class<? extends IBaseResource> theResourceType) {
Validate.notNull(theResourceType, "theResourceType can not be null");
myConditional = true;
myResourceType = myContext.getResourceDefinition(theResourceType).getName();
return this;
}
@Override
public IDeleteWithQuery resourceConditionalByType(String theResourceType) {
Validate.notBlank(theResourceType, "theResourceType can not be blank/null");
if (myContext.getResourceDefinition(theResourceType) == null) {
throw new IllegalArgumentException("Unknown resource type: " + theResourceType);
}
myResourceType = theResourceType;
myConditional = true;
return this;
}
@Override
public IDeleteTyped resourceConditionalByUrl(String theSearchUrl) {
mySearchUrl = validateAndEscapeConditionalUrl(theSearchUrl);
return this;
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private class FetchConformanceInternal extends BaseClientExecutable implements IFetchConformanceUntyped, IFetchConformanceTyped {
private RuntimeResourceDefinition myType;
@Override
public Object execute() {
ResourceResponseHandler binding = new ResourceResponseHandler(myType.getImplementingClass());
FhirContext fhirContext = getFhirContext();
HttpGetClientInvocation invocation = MethodUtil.createConformanceInvocation(fhirContext);
return super.invoke(null, binding, invocation);
}
@Override
public <T extends IBaseConformance> IFetchConformanceTyped<T> ofType(Class<T> theResourceType) {
Validate.notNull(theResourceType, "theResourceType must not be null");
myType = myContext.getResourceDefinition(theResourceType);
if (myType == null) {
throw new IllegalArgumentException(myContext.getLocalizer().getMessage(I18N_CANNOT_DETEMINE_RESOURCE_TYPE, theResourceType));
}
return this;
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private class GetPageInternal extends BaseClientExecutable<IGetPageTyped<Object>, Object> implements IGetPageTyped<Object> {
private Class<? extends IBaseBundle> myBundleType;
private String myUrl;
public GetPageInternal(String theUrl, Class<? extends IBaseBundle> theBundleType) {
myUrl = theUrl;
myBundleType = theBundleType;
}
@Override
public Object execute() {
IClientResponseHandler binding;
binding = new ResourceResponseHandler(myBundleType, getPreferResponseTypes());
HttpSimpleGetClientInvocation invocation = new HttpSimpleGetClientInvocation(myContext, myUrl);
Map<String, List<String>> params = null;
return invoke(params, binding, invocation);
}
}
@SuppressWarnings("rawtypes")
private class HistoryInternal extends BaseClientExecutable implements IHistory, IHistoryUntyped, IHistoryTyped {
private Integer myCount;
private IIdType myId;
private Class<? extends IBaseBundle> myReturnType;
private IPrimitiveType mySince;
private Class<? extends IBaseResource> myType;
@SuppressWarnings("unchecked")
@Override
public IHistoryTyped andReturnBundle(Class theType) {
Validate.notNull(theType, "theType must not be null on method andReturnBundle(Class)");
myReturnType = theType;
return this;
}
@Override
public IHistoryTyped count(Integer theCount) {
myCount = theCount;
return this;
}
@SuppressWarnings("unchecked")
@Override
public Object execute() {
String resourceName;
String id;
if (myType != null) {
resourceName = myContext.getResourceDefinition(myType).getName();
id = null;
} else if (myId != null) {
resourceName = myId.getResourceType();
id = myId.getIdPart();
} else {
resourceName = null;
id = null;
}
HttpGetClientInvocation invocation = HistoryMethodBinding.createHistoryInvocation(myContext, resourceName, id, mySince, myCount);
IClientResponseHandler handler;
handler = new ResourceResponseHandler(myReturnType, getPreferResponseTypes(myType));
return invoke(null, handler, invocation);
}
@Override
public IHistoryUntyped onInstance(IIdType theId) {
if (theId.hasResourceType() == false) {
throw new IllegalArgumentException("Resource ID does not have a resource type: " + theId.getValue());
}
myId = theId;
return this;
}
@Override
public IHistoryUntyped onServer() {
return this;
}
@Override
public IHistoryUntyped onType(Class<? extends IBaseResource> theResourceType) {
myType = theResourceType;
return this;
}
@Override
public IHistoryTyped since(Date theCutoff) {
if (theCutoff != null) {
mySince = new InstantDt(theCutoff);
} else {
mySince = null;
}
return this;
}
@Override
public IHistoryTyped since(IPrimitiveType theCutoff) {
mySince = theCutoff;
return this;
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private final class LoadPageInternal implements IGetPage, IGetPageUntyped {
private static final String PREV = "prev";
private static final String PREVIOUS = "previous";
private String myPageUrl;
@Override
public <T extends IBaseBundle> IGetPageTyped andReturnBundle(Class<T> theBundleType) {
Validate.notNull(theBundleType, "theBundleType must not be null");
return new GetPageInternal(myPageUrl, theBundleType);
}
@Override
public IGetPageUntyped byUrl(String thePageUrl) {
if (isBlank(thePageUrl)) {
throw new IllegalArgumentException("thePagingUrl must not be blank or null");
}
myPageUrl = thePageUrl;
return this;
}
@Override
public <T extends IBaseBundle> IGetPageTyped<T> next(T theBundle) {
return nextOrPrevious("next", theBundle);
}
private <T extends IBaseBundle> IGetPageTyped<T> nextOrPrevious(String theWantRel, T theBundle) {
RuntimeResourceDefinition def = myContext.getResourceDefinition(theBundle);
List<IBase> links = def.getChildByName("link").getAccessor().getValues(theBundle);
if (links == null || links.isEmpty()) {
throw new IllegalArgumentException(myContext.getLocalizer().getMessage(GenericClient.class, "noPagingLinkFoundInBundle", theWantRel));
}
for (IBase nextLink : links) {
BaseRuntimeElementCompositeDefinition linkDef = (BaseRuntimeElementCompositeDefinition) myContext.getElementDefinition(nextLink.getClass());
List<IBase> rel = linkDef.getChildByName("relation").getAccessor().getValues(nextLink);
if (rel == null || rel.isEmpty()) {
continue;
}
String relation = ((IPrimitiveType<?>) rel.get(0)).getValueAsString();
if (theWantRel.equals(relation) || (theWantRel == PREVIOUS && PREV.equals(relation))) {
List<IBase> urls = linkDef.getChildByName("url").getAccessor().getValues(nextLink);
if (urls == null || urls.isEmpty()) {
continue;
}
String url = ((IPrimitiveType<?>) urls.get(0)).getValueAsString();
if (isBlank(url)) {
continue;
}
return (IGetPageTyped<T>) byUrl(url).andReturnBundle(theBundle.getClass());
}
}
throw new IllegalArgumentException(myContext.getLocalizer().getMessage(GenericClient.class, "noPagingLinkFoundInBundle", theWantRel));
}
@Override
public <T extends IBaseBundle> IGetPageTyped<T> previous(T theBundle) {
return nextOrPrevious(PREVIOUS, theBundle);
}
}
@SuppressWarnings("rawtypes")
private class MetaInternal extends BaseClientExecutable implements IMeta, IMetaAddOrDeleteUnsourced, IMetaGetUnsourced, IMetaAddOrDeleteSourced {
private IIdType myId;
private IBaseMetaType myMeta;
private Class<? extends IBaseMetaType> myMetaType;
private String myOnType;
private MetaOperation myOperation;
@Override
public IMetaAddOrDeleteUnsourced add() {
myOperation = MetaOperation.ADD;
return this;
}
@Override
public IMetaAddOrDeleteUnsourced delete() {
myOperation = MetaOperation.DELETE;
return this;
}
@SuppressWarnings("unchecked")
@Override
public Object execute() {
BaseHttpClientInvocation invocation = null;
IBaseParameters parameters = ParametersUtil.newInstance(myContext);
switch (myOperation) {
case ADD:
ParametersUtil.addParameterToParameters(myContext, parameters, myMeta, "meta");
invocation = OperationMethodBinding.createOperationInvocation(myContext, myId.getResourceType(), myId.getIdPart(), "$meta-add", parameters, false);
break;
case DELETE:
ParametersUtil.addParameterToParameters(myContext, parameters, myMeta, "meta");
invocation = OperationMethodBinding.createOperationInvocation(myContext, myId.getResourceType(), myId.getIdPart(), "$meta-delete", parameters, false);
break;
case GET:
if (myId != null) {
invocation = OperationMethodBinding.createOperationInvocation(myContext, myOnType, myId.getIdPart(), "$meta", parameters, true);
} else if (myOnType != null) {
invocation = OperationMethodBinding.createOperationInvocation(myContext, myOnType, null, "$meta", parameters, true);
} else {
invocation = OperationMethodBinding.createOperationInvocation(myContext, null, null, "$meta", parameters, true);
}
break;
}
// Should not happen
if (invocation == null) {
throw new IllegalStateException();
}
IClientResponseHandler handler;
handler = new MetaParametersResponseHandler(myMetaType);
return invoke(null, handler, invocation);
}
@Override
public IClientExecutable fromResource(IIdType theId) {
setIdInternal(theId);
return this;
}
@Override
public IClientExecutable fromServer() {
return this;
}
@Override
public IClientExecutable fromType(String theResourceName) {
Validate.notBlank(theResourceName, "theResourceName must not be blank");
myOnType = theResourceName;
return this;
}
@SuppressWarnings("unchecked")
@Override
public <T extends IBaseMetaType> IMetaGetUnsourced<T> get(Class<T> theType) {
myMetaType = theType;
myOperation = MetaOperation.GET;
return this;
}
@SuppressWarnings("unchecked")
@Override
public <T extends IBaseMetaType> IClientExecutable<IClientExecutable<?, T>, T> meta(T theMeta) {
Validate.notNull(theMeta, "theMeta must not be null");
myMeta = theMeta;
myMetaType = myMeta.getClass();
return this;
}
@Override
public IMetaAddOrDeleteSourced onResource(IIdType theId) {
setIdInternal(theId);
return this;
}
private void setIdInternal(IIdType theId) {
Validate.notBlank(theId.getResourceType(), "theId must contain a resource type");
Validate.notBlank(theId.getIdPart(), "theId must contain an ID part");
myOnType = theId.getResourceType();
myId = theId;
}
}
private enum MetaOperation {
ADD,
DELETE,
GET
}
private final class MetaParametersResponseHandler<T extends IBaseMetaType> implements IClientResponseHandler<T> {
private Class<T> myType;
public MetaParametersResponseHandler(Class<T> theMetaType) {
myType = theMetaType;