/
BaseParser.java
1197 lines (1033 loc) 路 38.4 KB
/
BaseParser.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.parser;
/*
* #%L
* HAPI FHIR - Core Library
* %%
* 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 ca.uhn.fhir.context.*;
import ca.uhn.fhir.context.BaseRuntimeElementDefinition.ChildTypeEnum;
import ca.uhn.fhir.model.api.*;
import ca.uhn.fhir.model.primitive.IdDt;
import ca.uhn.fhir.rest.api.Constants;
import ca.uhn.fhir.rest.server.exceptions.InternalErrorException;
import ca.uhn.fhir.util.UrlUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.hl7.fhir.instance.model.api.*;
import java.io.*;
import java.lang.reflect.Modifier;
import java.util.*;
import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
public abstract class BaseParser implements IParser {
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(BaseParser.class);
private ContainedResources myContainedResources;
private FhirContext myContext;
private Set<String> myDontEncodeElements;
private boolean myDontEncodeElementsIncludesStars;
private Set<String> myEncodeElements;
private Set<String> myEncodeElementsAppliesToResourceTypes;
private boolean myEncodeElementsIncludesStars;
private IIdType myEncodeForceResourceId;
private IParserErrorHandler myErrorHandler;
private boolean myOmitResourceId;
private List<Class<? extends IBaseResource>> myPreferTypes;
private String myServerBaseUrl;
private Boolean myStripVersionsFromReferences;
private Boolean myOverrideResourceIdWithBundleEntryFullUrl;
private boolean mySummaryMode;
private boolean mySuppressNarratives;
private Set<String> myDontStripVersionsFromReferencesAtPaths;
/**
* Constructor
*
* @param theParserErrorHandler
*/
public BaseParser(FhirContext theContext, IParserErrorHandler theParserErrorHandler) {
myContext = theContext;
myErrorHandler = theParserErrorHandler;
}
protected Iterable<CompositeChildElement> compositeChildIterator(IBase theCompositeElement, final boolean theContainedResource, final boolean theSubResource, final CompositeChildElement theParent) {
BaseRuntimeElementCompositeDefinition<?> elementDef = (BaseRuntimeElementCompositeDefinition<?>) myContext.getElementDefinition(theCompositeElement.getClass());
final List<BaseRuntimeChildDefinition> children = elementDef.getChildrenAndExtension();
return new Iterable<BaseParser.CompositeChildElement>() {
@Override
public Iterator<CompositeChildElement> iterator() {
return new Iterator<CompositeChildElement>() {
private Iterator<? extends BaseRuntimeChildDefinition> myChildrenIter;
private Boolean myHasNext = null;
private CompositeChildElement myNext;
/**
* Constructor
*/ {
myChildrenIter = children.iterator();
}
@Override
public boolean hasNext() {
if (myHasNext != null) {
return myHasNext;
}
myNext = null;
do {
if (myChildrenIter.hasNext() == false) {
myHasNext = Boolean.FALSE;
return false;
}
myNext = new CompositeChildElement(theParent, myChildrenIter.next(), theSubResource);
/*
* There are lots of reasons we might skip encoding a particular child
*/
if (myNext.getDef().getElementName().equals("id")) {
myNext = null;
} else if (!myNext.shouldBeEncoded()) {
myNext = null;
} else if (isSummaryMode() && !myNext.getDef().isSummary()) {
myNext = null;
} else if (myNext.getDef() instanceof RuntimeChildNarrativeDefinition) {
if (isSuppressNarratives() || isSummaryMode()) {
myNext = null;
} else if (theContainedResource) {
myNext = null;
}
} else if (myNext.getDef() instanceof RuntimeChildContainedResources) {
if (theContainedResource) {
myNext = null;
}
}
} while (myNext == null);
myHasNext = true;
return true;
}
@Override
public CompositeChildElement next() {
if (myHasNext == null) {
if (!hasNext()) {
throw new IllegalStateException();
}
}
CompositeChildElement retVal = myNext;
myNext = null;
myHasNext = null;
return retVal;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
private void containResourcesForEncoding(ContainedResources theContained, IBaseResource theResource, IBaseResource theTarget) {
Set<String> allIds = new HashSet<String>();
Map<String, IBaseResource> existingIdToContainedResource = null;
if (theTarget instanceof IResource) {
List<? extends IResource> containedResources = ((IResource) theTarget).getContained().getContainedResources();
for (IResource next : containedResources) {
String nextId = next.getId().getValue();
if (StringUtils.isNotBlank(nextId)) {
if (!nextId.startsWith("#")) {
nextId = '#' + nextId;
}
allIds.add(nextId);
if (existingIdToContainedResource == null) {
existingIdToContainedResource = new HashMap<String, IBaseResource>();
}
existingIdToContainedResource.put(nextId, next);
}
}
} else if (theTarget instanceof IDomainResource) {
List<? extends IAnyResource> containedResources = ((IDomainResource) theTarget).getContained();
for (IAnyResource next : containedResources) {
String nextId = next.getIdElement().getValue();
if (StringUtils.isNotBlank(nextId)) {
if (!nextId.startsWith("#")) {
nextId = '#' + nextId;
}
allIds.add(nextId);
if (existingIdToContainedResource == null) {
existingIdToContainedResource = new HashMap<String, IBaseResource>();
}
existingIdToContainedResource.put(nextId, next);
}
}
} else {
// no resources to contain
}
{
List<IBaseReference> allElements = myContext.newTerser().getAllPopulatedChildElementsOfType(theResource, IBaseReference.class);
for (IBaseReference next : allElements) {
IBaseResource resource = next.getResource();
if (resource != null) {
if (resource.getIdElement().isEmpty() || resource.getIdElement().isLocal()) {
if (theContained.getResourceId(resource) != null) {
// Prevent infinite recursion if there are circular loops in the contained resources
continue;
}
theContained.addContained(resource);
if (resource.getIdElement().isLocal() && existingIdToContainedResource != null) {
existingIdToContainedResource.remove(resource.getIdElement().getValue());
}
} else {
continue;
}
containResourcesForEncoding(theContained, resource, theTarget);
} else if (next.getReferenceElement().isLocal()) {
if (existingIdToContainedResource != null) {
IBaseResource potentialTarget = existingIdToContainedResource.remove(next.getReferenceElement().getValue());
if (potentialTarget != null) {
theContained.addContained(next.getReferenceElement(), potentialTarget);
containResourcesForEncoding(theContained, potentialTarget, theTarget);
}
}
}
}
}
}
protected void containResourcesForEncoding(IBaseResource theResource) {
ContainedResources contained = new ContainedResources();
containResourcesForEncoding(contained, theResource, theResource);
myContainedResources = contained;
}
private String determineReferenceText(IBaseReference theRef, CompositeChildElement theCompositeChildElement) {
IIdType ref = theRef.getReferenceElement();
if (isBlank(ref.getIdPart())) {
String reference = ref.getValue();
if (theRef.getResource() != null) {
IIdType containedId = getContainedResources().getResourceId(theRef.getResource());
if (containedId != null && !containedId.isEmpty()) {
if (containedId.isLocal()) {
reference = containedId.getValue();
} else {
reference = "#" + containedId.getValue();
}
} else {
IIdType refId = theRef.getResource().getIdElement();
if (refId != null) {
if (refId.hasIdPart()) {
if (refId.getValue().startsWith("urn:")) {
reference = refId.getValue();
} else {
if (!refId.hasResourceType()) {
refId = refId.withResourceType(myContext.getResourceDefinition(theRef.getResource()).getName());
}
if (isStripVersionsFromReferences(theCompositeChildElement)) {
reference = refId.toVersionless().getValue();
} else {
reference = refId.getValue();
}
}
}
}
}
}
return reference;
}
if (!ref.hasResourceType() && !ref.isLocal() && theRef.getResource() != null) {
ref = ref.withResourceType(myContext.getResourceDefinition(theRef.getResource()).getName());
}
if (isNotBlank(myServerBaseUrl) && StringUtils.equals(myServerBaseUrl, ref.getBaseUrl())) {
if (isStripVersionsFromReferences(theCompositeChildElement)) {
return ref.toUnqualifiedVersionless().getValue();
}
return ref.toUnqualified().getValue();
}
if (isStripVersionsFromReferences(theCompositeChildElement)) {
return ref.toVersionless().getValue();
}
return ref.getValue();
}
protected abstract void doEncodeResourceToWriter(IBaseResource theResource, Writer theWriter) throws IOException, DataFormatException;
protected abstract <T extends IBaseResource> T doParseResource(Class<T> theResourceType, Reader theReader) throws DataFormatException;
@Override
public String encodeResourceToString(IBaseResource theResource) throws DataFormatException {
Writer stringWriter = new StringWriter();
try {
encodeResourceToWriter(theResource, stringWriter);
} catch (IOException e) {
throw new Error("Encountered IOException during write to string - This should not happen!");
}
return stringWriter.toString();
}
@Override
public final void encodeResourceToWriter(IBaseResource theResource, Writer theWriter) throws IOException, DataFormatException {
Validate.notNull(theResource, "theResource can not be null");
Validate.notNull(theWriter, "theWriter can not be null");
if (theResource.getStructureFhirVersionEnum() != myContext.getVersion().getVersion()) {
throw new IllegalArgumentException(
"This parser is for FHIR version " + myContext.getVersion().getVersion() + " - Can not encode a structure for version " + theResource.getStructureFhirVersionEnum());
}
doEncodeResourceToWriter(theResource, theWriter);
}
private void filterCodingsWithNoCodeOrSystem(List<? extends IBaseCoding> tagList) {
for (int i = 0; i < tagList.size(); i++) {
if (isBlank(tagList.get(i).getCode()) && isBlank(tagList.get(i).getSystem())) {
tagList.remove(i);
i--;
}
}
}
protected IIdType fixContainedResourceId(String theValue) {
IIdType retVal = (IIdType) myContext.getElementDefinition("id").newInstance();
if (StringUtils.isNotBlank(theValue) && theValue.charAt(0) == '#') {
retVal.setValue(theValue.substring(1));
} else {
retVal.setValue(theValue);
}
return retVal;
}
@SuppressWarnings("unchecked")
ChildNameAndDef getChildNameAndDef(BaseRuntimeChildDefinition theChild, IBase theValue) {
Class<? extends IBase> type = theValue.getClass();
String childName = theChild.getChildNameByDatatype(type);
BaseRuntimeElementDefinition<?> childDef = theChild.getChildElementDefinitionByDatatype(type);
if (childDef == null) {
// if (theValue instanceof IBaseExtension) {
// return null;
// }
/*
* For RI structures Enumeration class, this replaces the child def
* with the "code" one. This is messy, and presumably there is a better
* way..
*/
BaseRuntimeElementDefinition<?> elementDef = myContext.getElementDefinition(type);
if (elementDef.getName().equals("code")) {
Class<? extends IBase> type2 = myContext.getElementDefinition("code").getImplementingClass();
childDef = theChild.getChildElementDefinitionByDatatype(type2);
childName = theChild.getChildNameByDatatype(type2);
}
// See possibly the user has extended a built-in type without
// declaring it anywhere, as in XmlParserDstu3Test#testEncodeUndeclaredBlock
if (childDef == null) {
Class<?> nextSuperType = theValue.getClass();
while (IBase.class.isAssignableFrom(nextSuperType) && childDef == null) {
if (Modifier.isAbstract(nextSuperType.getModifiers()) == false) {
BaseRuntimeElementDefinition<?> def = myContext.getElementDefinition((Class<? extends IBase>) nextSuperType);
Class<?> nextChildType = def.getImplementingClass();
childDef = theChild.getChildElementDefinitionByDatatype((Class<? extends IBase>) nextChildType);
childName = theChild.getChildNameByDatatype((Class<? extends IBase>) nextChildType);
}
nextSuperType = nextSuperType.getSuperclass();
}
}
if (childDef == null) {
throwExceptionForUnknownChildType(theChild, type);
}
}
return new ChildNameAndDef(childName, childDef);
}
protected String getCompositeElementId(IBase theElement) {
String elementId = null;
if (!(theElement instanceof IBaseResource)) {
if (theElement instanceof IBaseElement) {
elementId = ((IBaseElement) theElement).getId();
} else if (theElement instanceof IIdentifiableElement) {
elementId = ((IIdentifiableElement) theElement).getElementSpecificId();
}
}
return elementId;
}
ContainedResources getContainedResources() {
return myContainedResources;
}
@Override
public Set<String> getDontStripVersionsFromReferencesAtPaths() {
return myDontStripVersionsFromReferencesAtPaths;
}
/**
* See {@link #setEncodeElements(Set)}
*/
@Override
public Set<String> getEncodeElements() {
return myEncodeElements;
}
@Override
public void setEncodeElements(Set<String> theEncodeElements) {
myEncodeElementsIncludesStars = false;
if (theEncodeElements == null || theEncodeElements.isEmpty()) {
myEncodeElements = null;
} else {
myEncodeElements = theEncodeElements;
for (String next : theEncodeElements) {
if (next.startsWith("*.")) {
myEncodeElementsIncludesStars = true;
}
}
}
}
/**
* See {@link #setEncodeElementsAppliesToResourceTypes(Set)}
*/
@Override
public Set<String> getEncodeElementsAppliesToResourceTypes() {
return myEncodeElementsAppliesToResourceTypes;
}
@Override
public void setEncodeElementsAppliesToResourceTypes(Set<String> theEncodeElementsAppliesToResourceTypes) {
if (theEncodeElementsAppliesToResourceTypes == null || theEncodeElementsAppliesToResourceTypes.isEmpty()) {
myEncodeElementsAppliesToResourceTypes = null;
} else {
myEncodeElementsAppliesToResourceTypes = theEncodeElementsAppliesToResourceTypes;
}
}
@Override
public IIdType getEncodeForceResourceId() {
return myEncodeForceResourceId;
}
@Override
public BaseParser setEncodeForceResourceId(IIdType theEncodeForceResourceId) {
myEncodeForceResourceId = theEncodeForceResourceId;
return this;
}
protected IParserErrorHandler getErrorHandler() {
return myErrorHandler;
}
protected String getExtensionUrl(final String extensionUrl) {
String url = extensionUrl;
if (StringUtils.isNotBlank(extensionUrl) && StringUtils.isNotBlank(myServerBaseUrl)) {
url = !UrlUtil.isValid(extensionUrl) && extensionUrl.startsWith("/") ? myServerBaseUrl + extensionUrl : extensionUrl;
}
return url;
}
protected TagList getMetaTagsForEncoding(IResource theIResource) {
TagList tags = ResourceMetadataKeyEnum.TAG_LIST.get(theIResource);
if (shouldAddSubsettedTag()) {
tags = new TagList(tags);
tags.add(new Tag(Constants.TAG_SUBSETTED_SYSTEM, Constants.TAG_SUBSETTED_CODE, subsetDescription()));
}
return tags;
}
@Override
public Boolean getOverrideResourceIdWithBundleEntryFullUrl() {
return myOverrideResourceIdWithBundleEntryFullUrl;
}
@Override
public List<Class<? extends IBaseResource>> getPreferTypes() {
return myPreferTypes;
}
@Override
public void setPreferTypes(List<Class<? extends IBaseResource>> thePreferTypes) {
if (thePreferTypes != null) {
ArrayList<Class<? extends IBaseResource>> types = new ArrayList<Class<? extends IBaseResource>>();
for (Class<? extends IBaseResource> next : thePreferTypes) {
if (Modifier.isAbstract(next.getModifiers()) == false) {
types.add(next);
}
}
myPreferTypes = Collections.unmodifiableList(types);
} else {
myPreferTypes = thePreferTypes;
}
}
@SuppressWarnings("deprecation")
protected <T extends IPrimitiveType<String>> List<T> getProfileTagsForEncoding(IBaseResource theResource, List<T> theProfiles) {
switch (myContext.getAddProfileTagWhenEncoding()) {
case NEVER:
return theProfiles;
case ONLY_FOR_CUSTOM:
RuntimeResourceDefinition resDef = myContext.getResourceDefinition(theResource);
if (resDef.isStandardType()) {
return theProfiles;
}
break;
case ALWAYS:
break;
}
RuntimeResourceDefinition nextDef = myContext.getResourceDefinition(theResource);
String profile = nextDef.getResourceProfile(myServerBaseUrl);
if (isNotBlank(profile)) {
for (T next : theProfiles) {
if (profile.equals(next.getValue())) {
return theProfiles;
}
}
List<T> newList = new ArrayList<T>();
newList.addAll(theProfiles);
BaseRuntimeElementDefinition<?> idElement = myContext.getElementDefinition("id");
@SuppressWarnings("unchecked")
T newId = (T) idElement.newInstance();
newId.setValue(profile);
newList.add(newId);
return newList;
}
return theProfiles;
}
protected String getServerBaseUrl() {
return myServerBaseUrl;
}
@Override
public Boolean getStripVersionsFromReferences() {
return myStripVersionsFromReferences;
}
/**
* If set to <code>true</code> (default is <code>false</code>), narratives will not be included in the encoded
* values.
*
* @deprecated Use {@link #isSuppressNarratives()}
*/
@Deprecated
public boolean getSuppressNarratives() {
return mySuppressNarratives;
}
protected boolean isChildContained(BaseRuntimeElementDefinition<?> childDef, boolean theIncludedResource) {
return (childDef.getChildType() == ChildTypeEnum.CONTAINED_RESOURCES || childDef.getChildType() == ChildTypeEnum.CONTAINED_RESOURCE_LIST) && getContainedResources().isEmpty() == false
&& theIncludedResource == false;
}
@Override
public boolean isOmitResourceId() {
return myOmitResourceId;
}
private boolean isOverrideResourceIdWithBundleEntryFullUrl() {
Boolean overrideResourceIdWithBundleEntryFullUrl = myOverrideResourceIdWithBundleEntryFullUrl;
if (overrideResourceIdWithBundleEntryFullUrl != null) {
return overrideResourceIdWithBundleEntryFullUrl;
}
return myContext.getParserOptions().isOverrideResourceIdWithBundleEntryFullUrl();
}
private boolean isStripVersionsFromReferences(CompositeChildElement theCompositeChildElement) {
Boolean stripVersionsFromReferences = myStripVersionsFromReferences;
if (stripVersionsFromReferences != null) {
return stripVersionsFromReferences;
}
if (myContext.getParserOptions().isStripVersionsFromReferences() == false) {
return false;
}
Set<String> dontStripVersionsFromReferencesAtPaths = myDontStripVersionsFromReferencesAtPaths;
if (dontStripVersionsFromReferencesAtPaths != null) {
if (dontStripVersionsFromReferencesAtPaths.isEmpty() == false && theCompositeChildElement.anyPathMatches(dontStripVersionsFromReferencesAtPaths)) {
return false;
}
}
dontStripVersionsFromReferencesAtPaths = myContext.getParserOptions().getDontStripVersionsFromReferencesAtPaths();
if (dontStripVersionsFromReferencesAtPaths.isEmpty() == false && theCompositeChildElement.anyPathMatches(dontStripVersionsFromReferencesAtPaths)) {
return false;
}
return true;
}
@Override
public boolean isSummaryMode() {
return mySummaryMode;
}
/**
* If set to <code>true</code> (default is <code>false</code>), narratives will not be included in the encoded
* values.
*
* @since 1.2
*/
public boolean isSuppressNarratives() {
return mySuppressNarratives;
}
@Override
public <T extends IBaseResource> T parseResource(Class<T> theResourceType, Reader theReader) throws DataFormatException {
/*
* We do this so that the context can verify that the structure is for
* the correct FHIR version
*/
if (theResourceType != null) {
myContext.getResourceDefinition(theResourceType);
}
// Actually do the parse
T retVal = doParseResource(theResourceType, theReader);
RuntimeResourceDefinition def = myContext.getResourceDefinition(retVal);
if ("Bundle".equals(def.getName())) {
BaseRuntimeChildDefinition entryChild = def.getChildByName("entry");
BaseRuntimeElementCompositeDefinition<?> entryDef = (BaseRuntimeElementCompositeDefinition<?>) entryChild.getChildByName("entry");
List<IBase> entries = entryChild.getAccessor().getValues(retVal);
if (entries != null) {
for (IBase nextEntry : entries) {
/**
* If Bundle.entry.fullUrl is populated, set the resource ID to that
*/
// TODO: should emit a warning and maybe notify the error handler if the resource ID doesn't match the
// fullUrl idPart
BaseRuntimeChildDefinition fullUrlChild = entryDef.getChildByName("fullUrl");
if (fullUrlChild == null) {
continue; // TODO: remove this once the data model in tinder plugin catches up to 1.2
}
if (isOverrideResourceIdWithBundleEntryFullUrl()) {
List<IBase> fullUrl = fullUrlChild.getAccessor().getValues(nextEntry);
if (fullUrl != null && !fullUrl.isEmpty()) {
IPrimitiveType<?> value = (IPrimitiveType<?>) fullUrl.get(0);
if (value.isEmpty() == false) {
List<IBase> entryResources = entryDef.getChildByName("resource").getAccessor().getValues(nextEntry);
if (entryResources != null && entryResources.size() > 0) {
IBaseResource res = (IBaseResource) entryResources.get(0);
String versionId = res.getIdElement().getVersionIdPart();
res.setId(value.getValueAsString());
if (isNotBlank(versionId) && res.getIdElement().hasVersionIdPart() == false) {
res.setId(res.getIdElement().withVersion(versionId));
}
}
}
}
}
}
}
}
return retVal;
}
@SuppressWarnings("cast")
@Override
public <T extends IBaseResource> T parseResource(Class<T> theResourceType, String theMessageString) {
StringReader reader = new StringReader(theMessageString);
return (T) parseResource(theResourceType, reader);
}
@Override
public IBaseResource parseResource(Reader theReader) throws ConfigurationException, DataFormatException {
return parseResource(null, theReader);
}
@Override
public IBaseResource parseResource(String theMessageString) throws ConfigurationException, DataFormatException {
return parseResource(null, theMessageString);
}
protected List<? extends IBase> preProcessValues(BaseRuntimeChildDefinition theMetaChildUncast, IBaseResource theResource, List<? extends IBase> theValues,
CompositeChildElement theCompositeChildElement) {
if (myContext.getVersion().getVersion().isRi()) {
/*
* If we're encoding the meta tag, we do some massaging of the meta values before
* encoding. But if there is no meta element at all, we create one since we're possibly going to be
* adding things to it
*/
if (theValues.isEmpty() && theMetaChildUncast.getElementName().equals("meta")) {
BaseRuntimeElementDefinition<?> metaChild = theMetaChildUncast.getChildByName("meta");
if (IBaseMetaType.class.isAssignableFrom(metaChild.getImplementingClass())) {
IBaseMetaType newType = (IBaseMetaType) metaChild.newInstance();
theValues = Collections.singletonList(newType);
}
}
if (theValues.size() == 1 && theValues.get(0) instanceof IBaseMetaType) {
IBaseMetaType metaValue = (IBaseMetaType) theValues.get(0);
try {
metaValue = (IBaseMetaType) metaValue.getClass().getMethod("copy").invoke(metaValue);
} catch (Exception e) {
throw new InternalErrorException("Failed to duplicate meta", e);
}
if (isBlank(metaValue.getVersionId())) {
if (theResource.getIdElement().hasVersionIdPart()) {
metaValue.setVersionId(theResource.getIdElement().getVersionIdPart());
}
}
filterCodingsWithNoCodeOrSystem(metaValue.getTag());
filterCodingsWithNoCodeOrSystem(metaValue.getSecurity());
List<? extends IPrimitiveType<String>> newProfileList = getProfileTagsForEncoding(theResource, metaValue.getProfile());
List<? extends IPrimitiveType<String>> oldProfileList = metaValue.getProfile();
if (oldProfileList != newProfileList) {
oldProfileList.clear();
for (IPrimitiveType<String> next : newProfileList) {
if (isNotBlank(next.getValue())) {
metaValue.addProfile(next.getValue());
}
}
}
if (shouldAddSubsettedTag()) {
IBaseCoding coding = metaValue.addTag();
coding.setCode(Constants.TAG_SUBSETTED_CODE);
coding.setSystem(Constants.TAG_SUBSETTED_SYSTEM);
coding.setDisplay(subsetDescription());
}
return Collections.singletonList(metaValue);
}
}
@SuppressWarnings("unchecked")
List<IBase> retVal = (List<IBase>) theValues;
for (int i = 0; i < retVal.size(); i++) {
IBase next = retVal.get(i);
/*
* If we have automatically contained any resources via
* their references, this ensures that we output the new
* local reference
*/
if (next instanceof IBaseReference) {
IBaseReference nextRef = (IBaseReference) next;
String refText = determineReferenceText(nextRef, theCompositeChildElement);
if (!StringUtils.equals(refText, nextRef.getReferenceElement().getValue())) {
if (retVal == theValues) {
retVal = new ArrayList<IBase>(theValues);
}
IBaseReference newRef = (IBaseReference) myContext.getElementDefinition(nextRef.getClass()).newInstance();
myContext.newTerser().cloneInto(nextRef, newRef, true);
newRef.setReference(refText);
retVal.set(i, newRef);
}
}
}
return retVal;
}
@Override
public void setDontEncodeElements(Set<String> theDontEncodeElements) {
myDontEncodeElementsIncludesStars = false;
if (theDontEncodeElements == null || theDontEncodeElements.isEmpty()) {
myDontEncodeElements = null;
} else {
myDontEncodeElements = theDontEncodeElements;
for (String next : theDontEncodeElements) {
if (next.startsWith("*.")) {
myDontEncodeElementsIncludesStars = true;
}
}
}
}
@Override
public IParser setDontStripVersionsFromReferencesAtPaths(String... thePaths) {
if (thePaths == null) {
setDontStripVersionsFromReferencesAtPaths((List<String>) null);
} else {
setDontStripVersionsFromReferencesAtPaths(Arrays.asList(thePaths));
}
return this;
}
@SuppressWarnings("unchecked")
@Override
public IParser setDontStripVersionsFromReferencesAtPaths(Collection<String> thePaths) {
if (thePaths == null) {
myDontStripVersionsFromReferencesAtPaths = Collections.emptySet();
} else if (thePaths instanceof HashSet) {
myDontStripVersionsFromReferencesAtPaths = (Set<String>) ((HashSet<String>) thePaths).clone();
} else {
myDontStripVersionsFromReferencesAtPaths = new HashSet<String>(thePaths);
}
return this;
}
@Override
public IParser setOmitResourceId(boolean theOmitResourceId) {
myOmitResourceId = theOmitResourceId;
return this;
}
@Override
public IParser setOverrideResourceIdWithBundleEntryFullUrl(Boolean theOverrideResourceIdWithBundleEntryFullUrl) {
myOverrideResourceIdWithBundleEntryFullUrl = theOverrideResourceIdWithBundleEntryFullUrl;
return this;
}
@Override
public IParser setParserErrorHandler(IParserErrorHandler theErrorHandler) {
Validate.notNull(theErrorHandler, "theErrorHandler must not be null");
myErrorHandler = theErrorHandler;
return this;
}
@Override
public IParser setServerBaseUrl(String theUrl) {
myServerBaseUrl = isNotBlank(theUrl) ? theUrl : null;
return this;
}
@Override
public IParser setStripVersionsFromReferences(Boolean theStripVersionsFromReferences) {
myStripVersionsFromReferences = theStripVersionsFromReferences;
return this;
}
@Override
public IParser setSummaryMode(boolean theSummaryMode) {
mySummaryMode = theSummaryMode;
return this;
}
@Override
public IParser setSuppressNarratives(boolean theSuppressNarratives) {
mySuppressNarratives = theSuppressNarratives;
return this;
}
protected boolean shouldAddSubsettedTag() {
return isSummaryMode() || isSuppressNarratives() || getEncodeElements() != null;
}
protected boolean shouldEncodeResourceId(IBaseResource theResource, boolean theSubResource) {
boolean retVal = true;
if (isOmitResourceId()) {
retVal = false;
} else {
if (myDontEncodeElements != null) {
String resourceName = myContext.getResourceDefinition(theResource).getName();
if (myDontEncodeElements.contains(resourceName + ".id")) {
retVal = false;
} else if (myDontEncodeElements.contains("*.id")) {
retVal = false;
} else if (theSubResource == false && myDontEncodeElements.contains("id")) {
retVal = false;
}
}
}
return retVal;
}
/**
* Used for DSTU2 only
*/
protected boolean shouldEncodeResourceMeta(IResource theResource) {
if (myDontEncodeElements != null) {
String resourceName = myContext.getResourceDefinition(theResource).getName();
if (myDontEncodeElements.contains(resourceName + ".meta")) {
return false;
} else if (myDontEncodeElements.contains("*.meta")) {
return false;
}
}
return true;
}
private String subsetDescription() {
return "Resource encoded in summary mode";
}
protected void throwExceptionForUnknownChildType(BaseRuntimeChildDefinition nextChild, Class<? extends IBase> theType) {
if (nextChild instanceof BaseRuntimeDeclaredChildDefinition) {
StringBuilder b = new StringBuilder();
b.append(((BaseRuntimeDeclaredChildDefinition) nextChild).getElementName());
b.append(" has type ");
b.append(theType.getName());
b.append(" but this is not a valid type for this element");
if (nextChild instanceof RuntimeChildChoiceDefinition) {
RuntimeChildChoiceDefinition choice = (RuntimeChildChoiceDefinition) nextChild;
b.append(" - Expected one of: " + choice.getValidChildTypes());
}
throw new DataFormatException(b.toString());
}
throw new DataFormatException(nextChild + " has no child of type " + theType);
}
protected List<Map.Entry<ResourceMetadataKeyEnum<?>, Object>> getExtensionMetadataKeys(IResource resource) {
List<Map.Entry<ResourceMetadataKeyEnum<?>, Object>> extensionMetadataKeys = new ArrayList<Map.Entry<ResourceMetadataKeyEnum<?>, Object>>();
for (Map.Entry<ResourceMetadataKeyEnum<?>, Object> entry : resource.getResourceMetadata().entrySet()) {
if (entry.getKey() instanceof ResourceMetadataKeyEnum.ExtensionResourceMetadataKey) {
extensionMetadataKeys.add(entry);
}
}
return extensionMetadataKeys;
}
protected static <T> List<T> extractMetadataListNotNull(IResource resource, ResourceMetadataKeyEnum<List<T>> key) {
List<? extends T> securityLabels = key.get(resource);
if (securityLabels == null) {
securityLabels = Collections.emptyList();
}
return new ArrayList<T>(securityLabels);
}
static boolean hasExtensions(IBase theElement) {
if (theElement instanceof ISupportsUndeclaredExtensions) {
ISupportsUndeclaredExtensions res = (ISupportsUndeclaredExtensions) theElement;
if (res.getUndeclaredExtensions().size() > 0 || res.getUndeclaredModifierExtensions().size() > 0) {
return true;
}
}
if (theElement instanceof IBaseHasExtensions) {
IBaseHasExtensions res = (IBaseHasExtensions) theElement;
if (res.hasExtension()) {
return true;
}
}
if (theElement instanceof IBaseHasModifierExtensions) {
IBaseHasModifierExtensions res = (IBaseHasModifierExtensions) theElement;
if (res.hasModifierExtension()) {
return true;
}
}
return false;
}
class ChildNameAndDef {
private final BaseRuntimeElementDefinition<?> myChildDef;
private final String myChildName;
public ChildNameAndDef(String theChildName, BaseRuntimeElementDefinition<?> theChildDef) {
myChildName = theChildName;
myChildDef = theChildDef;
}
public BaseRuntimeElementDefinition<?> getChildDef() {
return myChildDef;
}
public String getChildName() {
return myChildName;
}
}
protected class CompositeChildElement {
private final BaseRuntimeChildDefinition myDef;
private final CompositeChildElement myParent;
private final RuntimeResourceDefinition myResDef;
private final boolean mySubResource;
public CompositeChildElement(CompositeChildElement theParent, BaseRuntimeChildDefinition theDef, boolean theSubResource) {
myDef = theDef;
myParent = theParent;
myResDef = null;
mySubResource = theSubResource;
if (ourLog.isTraceEnabled()) {
if (theParent != null) {
StringBuilder path = theParent.buildPath();
if (path != null) {
path.append('.');
path.append(myDef.getElementName());
ourLog.trace(" * Next path: {}", path.toString());
}
}
}
}