001package ca.uhn.fhir.parser;
002
003/*
004 * #%L
005 * HAPI FHIR - Core Library
006 * %%
007 * Copyright (C) 2014 - 2020 University Health Network
008 * %%
009 * Licensed under the Apache License, Version 2.0 (the "License");
010 * you may not use this file except in compliance with the License.
011 * You may obtain a copy of the License at
012 *
013 * http://www.apache.org/licenses/LICENSE-2.0
014 *
015 * Unless required by applicable law or agreed to in writing, software
016 * distributed under the License is distributed on an "AS IS" BASIS,
017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
018 * See the License for the specific language governing permissions and
019 * limitations under the License.
020 * #L%
021 */
022
023import ca.uhn.fhir.context.*;
024import ca.uhn.fhir.context.BaseRuntimeElementDefinition.ChildTypeEnum;
025import ca.uhn.fhir.model.api.ExtensionDt;
026import ca.uhn.fhir.model.api.IPrimitiveDatatype;
027import ca.uhn.fhir.model.api.IResource;
028import ca.uhn.fhir.model.api.ISupportsUndeclaredExtensions;
029import ca.uhn.fhir.model.api.ResourceMetadataKeyEnum;
030import ca.uhn.fhir.model.api.Tag;
031import ca.uhn.fhir.model.api.TagList;
032import ca.uhn.fhir.model.api.annotation.Child;
033import ca.uhn.fhir.model.base.composite.BaseCodingDt;
034import ca.uhn.fhir.model.base.composite.BaseContainedDt;
035import ca.uhn.fhir.model.primitive.IdDt;
036import ca.uhn.fhir.model.primitive.InstantDt;
037import ca.uhn.fhir.narrative.INarrativeGenerator;
038import ca.uhn.fhir.parser.json.JsonLikeArray;
039import ca.uhn.fhir.parser.json.JsonLikeObject;
040import ca.uhn.fhir.parser.json.JsonLikeStructure;
041import ca.uhn.fhir.parser.json.JsonLikeValue;
042import ca.uhn.fhir.parser.json.JsonLikeValue.ScalarType;
043import ca.uhn.fhir.parser.json.JsonLikeValue.ValueType;
044import ca.uhn.fhir.parser.json.JsonLikeWriter;
045import ca.uhn.fhir.parser.json.jackson.JacksonStructure;
046import ca.uhn.fhir.rest.api.EncodingEnum;
047import ca.uhn.fhir.util.ElementUtil;
048import org.apache.commons.lang3.StringUtils;
049import org.apache.commons.lang3.Validate;
050import org.apache.commons.text.WordUtils;
051import org.hl7.fhir.instance.model.api.*;
052
053import java.io.IOException;
054import java.io.Reader;
055import java.io.Writer;
056import java.math.BigDecimal;
057import java.util.ArrayList;
058import java.util.Collections;
059import java.util.List;
060import java.util.Map;
061import java.util.Set;
062
063import static ca.uhn.fhir.context.BaseRuntimeElementDefinition.ChildTypeEnum.ID_DATATYPE;
064import static ca.uhn.fhir.context.BaseRuntimeElementDefinition.ChildTypeEnum.PRIMITIVE_DATATYPE;
065import static org.apache.commons.lang3.StringUtils.defaultString;
066import static org.apache.commons.lang3.StringUtils.isBlank;
067import static org.apache.commons.lang3.StringUtils.isNotBlank;
068
069/**
070 * This class is the FHIR JSON parser/encoder. Users should not interact with this class directly, but should use
071 * {@link FhirContext#newJsonParser()} to get an instance.
072 */
073public class JsonParser extends BaseParser implements IJsonLikeParser {
074
075        private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(JsonParser.HeldExtension.class);
076
077        private FhirContext myContext;
078        private boolean myPrettyPrint;
079
080        /**
081         * Do not use this constructor, the recommended way to obtain a new instance of the JSON parser is to invoke
082         * {@link FhirContext#newJsonParser()}.
083         *
084         * @param theParserErrorHandler
085         */
086        public JsonParser(FhirContext theContext, IParserErrorHandler theParserErrorHandler) {
087                super(theContext, theParserErrorHandler);
088                myContext = theContext;
089        }
090
091        private boolean addToHeldComments(int valueIdx, List<String> theCommentsToAdd, ArrayList<ArrayList<String>> theListToAddTo) {
092                if (theCommentsToAdd.size() > 0) {
093                        theListToAddTo.ensureCapacity(valueIdx);
094                        while (theListToAddTo.size() <= valueIdx) {
095                                theListToAddTo.add(null);
096                        }
097                        if (theListToAddTo.get(valueIdx) == null) {
098                                theListToAddTo.set(valueIdx, new ArrayList<>());
099                        }
100                        theListToAddTo.get(valueIdx).addAll(theCommentsToAdd);
101                        return true;
102                }
103                return false;
104        }
105
106        private boolean addToHeldExtensions(int valueIdx, List<? extends IBaseExtension<?, ?>> ext, ArrayList<ArrayList<HeldExtension>> list, boolean theIsModifier, CompositeChildElement theChildElem,
107                                        CompositeChildElement theParent, EncodeContext theEncodeContext, boolean theContainedResource, IBase theContainingElement) {
108                boolean retVal = false;
109                if (ext.size() > 0) {
110                        Boolean encodeExtension = null;
111                        for (IBaseExtension<?, ?> next : ext) {
112
113                                if (next.isEmpty()) {
114                                        continue;
115                                }
116
117                                // Make sure we respect _summary and _elements
118                                if (encodeExtension == null) {
119                                        encodeExtension = isEncodeExtension(theParent, theEncodeContext, theContainedResource, theContainingElement);
120                                }
121
122                                if (encodeExtension) {
123                                        HeldExtension extension = new HeldExtension(next, theIsModifier, theChildElem, theParent);
124                                        list.ensureCapacity(valueIdx);
125                                        while (list.size() <= valueIdx) {
126                                                list.add(null);
127                                        }
128                                        ArrayList<HeldExtension> extensionList = list.get(valueIdx);
129                                        if (extensionList == null) {
130                                                extensionList = new ArrayList<>();
131                                                list.set(valueIdx, extensionList);
132                                        }
133                                        extensionList.add(extension);
134                                        retVal = true;
135                                }
136                        }
137                }
138                return retVal;
139        }
140
141        private void addToHeldIds(int theValueIdx, ArrayList<String> theListToAddTo, String theId) {
142                theListToAddTo.ensureCapacity(theValueIdx);
143                while (theListToAddTo.size() <= theValueIdx) {
144                        theListToAddTo.add(null);
145                }
146                if (theListToAddTo.get(theValueIdx) == null) {
147                        theListToAddTo.set(theValueIdx, theId);
148                }
149        }
150
151        // private void assertObjectOfType(JsonLikeValue theResourceTypeObj, Object theValueType, String thePosition) {
152        // if (theResourceTypeObj == null) {
153        // throw new DataFormatException("Invalid JSON content detected, missing required element: '" + thePosition + "'");
154        // }
155        //
156        // if (theResourceTypeObj.getValueType() != theValueType) {
157        // throw new DataFormatException("Invalid content of element " + thePosition + ", expected " + theValueType);
158        // }
159        // }
160
161        private void beginArray(JsonLikeWriter theEventWriter, String arrayName) throws IOException {
162                theEventWriter.beginArray(arrayName);
163        }
164
165        private void beginObject(JsonLikeWriter theEventWriter, String arrayName) throws IOException {
166                theEventWriter.beginObject(arrayName);
167        }
168
169        private JsonLikeWriter createJsonWriter(Writer theWriter) throws IOException {
170                JsonLikeStructure jsonStructure = new JacksonStructure();
171                return jsonStructure.getJsonLikeWriter(theWriter);
172        }
173
174        public void doEncodeResourceToJsonLikeWriter(IBaseResource theResource, JsonLikeWriter theEventWriter, EncodeContext theEncodeContext) throws IOException {
175                if (myPrettyPrint) {
176                        theEventWriter.setPrettyPrint(myPrettyPrint);
177                }
178                theEventWriter.init();
179
180                RuntimeResourceDefinition resDef = myContext.getResourceDefinition(theResource);
181                encodeResourceToJsonStreamWriter(resDef, theResource, theEventWriter, null, false, theEncodeContext);
182                theEventWriter.flush();
183        }
184
185        @Override
186        protected void doEncodeResourceToWriter(IBaseResource theResource, Writer theWriter, EncodeContext theEncodeContext) throws IOException {
187                JsonLikeWriter eventWriter = createJsonWriter(theWriter);
188                doEncodeResourceToJsonLikeWriter(theResource, eventWriter, theEncodeContext);
189                eventWriter.close();
190        }
191
192        @Override
193        public <T extends IBaseResource> T doParseResource(Class<T> theResourceType, Reader theReader) {
194                JsonLikeStructure jsonStructure = new JacksonStructure();
195                jsonStructure.load(theReader);
196
197                T retVal = doParseResource(theResourceType, jsonStructure);
198
199                return retVal;
200        }
201
202        public <T extends IBaseResource> T doParseResource(Class<T> theResourceType, JsonLikeStructure theJsonStructure) {
203                JsonLikeObject object = theJsonStructure.getRootObject();
204
205                JsonLikeValue resourceTypeObj = object.get("resourceType");
206                if (resourceTypeObj == null || !resourceTypeObj.isString() || isBlank(resourceTypeObj.getAsString())) {
207                        throw new DataFormatException("Invalid JSON content detected, missing required element: 'resourceType'");
208                }
209
210                String resourceType = resourceTypeObj.getAsString();
211
212                ParserState<? extends IBaseResource> state = ParserState.getPreResourceInstance(this, theResourceType, myContext, true, getErrorHandler());
213                state.enteringNewElement(null, resourceType);
214
215                parseChildren(object, state);
216
217                state.endingElement();
218                state.endingElement();
219
220                @SuppressWarnings("unchecked")
221                T retVal = (T) state.getObject();
222
223                return retVal;
224        }
225
226        private void encodeChildElementToStreamWriter(RuntimeResourceDefinition theResDef, IBaseResource theResource, JsonLikeWriter theEventWriter, IBase theNextValue,
227                                                                                                                                 BaseRuntimeElementDefinition<?> theChildDef, String theChildName, boolean theContainedResource, CompositeChildElement theChildElem,
228                                                                                                                                 boolean theForceEmpty, EncodeContext theEncodeContext) throws IOException {
229
230                switch (theChildDef.getChildType()) {
231                        case ID_DATATYPE: {
232                                IIdType value = (IIdType) theNextValue;
233                                String encodedValue = "id".equals(theChildName) ? value.getIdPart() : value.getValue();
234                                if (isBlank(encodedValue)) {
235                                        break;
236                                }
237                                if (theChildName != null) {
238                                        write(theEventWriter, theChildName, encodedValue);
239                                } else {
240                                        theEventWriter.write(encodedValue);
241                                }
242                                break;
243                        }
244                        case PRIMITIVE_DATATYPE: {
245                                final IPrimitiveType<?> value = (IPrimitiveType<?>) theNextValue;
246                                final String valueStr = value.getValueAsString();
247                                if (isBlank(valueStr)) {
248                                        if (theForceEmpty) {
249                                                theEventWriter.writeNull();
250                                        }
251                                        break;
252                                }
253
254                                // check for the common case first - String value types
255                                Object valueObj = value.getValue();
256                                if (valueObj instanceof String) {
257                                        if (theChildName != null) {
258                                                theEventWriter.write(theChildName, valueStr);
259                                        } else {
260                                                theEventWriter.write(valueStr);
261                                        }
262                                        break;
263                                } else if (valueObj instanceof Long) {
264                                        if (theChildName != null) {
265                                                theEventWriter.write(theChildName, (long) valueObj);
266                                        } else {
267                                                theEventWriter.write((long) valueObj);
268                                        }
269                                        break;
270                                }
271
272                                if (value instanceof IBaseIntegerDatatype) {
273                                        if (theChildName != null) {
274                                                write(theEventWriter, theChildName, ((IBaseIntegerDatatype) value).getValue());
275                                        } else {
276                                                theEventWriter.write(((IBaseIntegerDatatype) value).getValue());
277                                        }
278                                } else if (value instanceof IBaseDecimalDatatype) {
279                                        BigDecimal decimalValue = ((IBaseDecimalDatatype) value).getValue();
280                                        decimalValue = new BigDecimal(decimalValue.toString()) {
281                                                private static final long serialVersionUID = 1L;
282
283                                                @Override
284                                                public String toString() {
285                                                        return value.getValueAsString();
286                                                }
287                                        };
288                                        if (theChildName != null) {
289                                                write(theEventWriter, theChildName, decimalValue);
290                                        } else {
291                                                theEventWriter.write(decimalValue);
292                                        }
293                                } else if (value instanceof IBaseBooleanDatatype) {
294                                        if (theChildName != null) {
295                                                write(theEventWriter, theChildName, ((IBaseBooleanDatatype) value).getValue());
296                                        } else {
297                                                Boolean booleanValue = ((IBaseBooleanDatatype) value).getValue();
298                                                if (booleanValue != null) {
299                                                        theEventWriter.write(booleanValue.booleanValue());
300                                                }
301                                        }
302                                } else {
303                                        if (theChildName != null) {
304                                                write(theEventWriter, theChildName, valueStr);
305                                        } else {
306                                                theEventWriter.write(valueStr);
307                                        }
308                                }
309                                break;
310                        }
311                        case RESOURCE_BLOCK:
312                        case COMPOSITE_DATATYPE: {
313                                if (theChildName != null) {
314                                        theEventWriter.beginObject(theChildName);
315                                } else {
316                                        theEventWriter.beginObject();
317                                }
318                                encodeCompositeElementToStreamWriter(theResDef, theResource, theNextValue, theEventWriter, theContainedResource, theChildElem, theEncodeContext);
319                                theEventWriter.endObject();
320                                break;
321                        }
322                        case CONTAINED_RESOURCE_LIST:
323                        case CONTAINED_RESOURCES: {
324                                List<IBaseResource> containedResources = getContainedResources().getContainedResources();
325                                if (containedResources.size() > 0) {
326                                        beginArray(theEventWriter, theChildName);
327
328                                        for (IBaseResource next : containedResources) {
329                                                IIdType resourceId = getContainedResources().getResourceId(next);
330                                                String value = resourceId.getValue();
331                                                encodeResourceToJsonStreamWriter(theResDef, next, theEventWriter, null, true, fixContainedResourceId(value), theEncodeContext);
332                                        }
333
334                                        theEventWriter.endArray();
335                                }
336                                break;
337                        }
338                        case PRIMITIVE_XHTML_HL7ORG:
339                        case PRIMITIVE_XHTML: {
340                                if (!isSuppressNarratives()) {
341                                        IPrimitiveType<?> dt = (IPrimitiveType<?>) theNextValue;
342                                        if (theChildName != null) {
343                                                write(theEventWriter, theChildName, dt.getValueAsString());
344                                        } else {
345                                                theEventWriter.write(dt.getValueAsString());
346                                        }
347                                } else {
348                                        if (theChildName != null) {
349                                                // do nothing
350                                        } else {
351                                                theEventWriter.writeNull();
352                                        }
353                                }
354                                break;
355                        }
356                        case RESOURCE:
357                                IBaseResource resource = (IBaseResource) theNextValue;
358                                RuntimeResourceDefinition def = myContext.getResourceDefinition(resource);
359
360                                theEncodeContext.pushPath(def.getName(), true);
361                                encodeResourceToJsonStreamWriter(def, resource, theEventWriter, theChildName, theContainedResource, theEncodeContext);
362                                theEncodeContext.popPath();
363
364                                break;
365                        case UNDECL_EXT:
366                        default:
367                                throw new IllegalStateException("Should not have this state here: " + theChildDef.getChildType().name());
368                }
369
370        }
371
372        private void encodeCompositeElementChildrenToStreamWriter(RuntimeResourceDefinition theResDef, IBaseResource theResource, IBase theElement, JsonLikeWriter theEventWriter,
373                                                                                                                                                                 boolean theContainedResource, CompositeChildElement theParent, EncodeContext theEncodeContext) throws IOException {
374
375                {
376                        String elementId = getCompositeElementId(theElement);
377                        if (isNotBlank(elementId)) {
378                                write(theEventWriter, "id", elementId);
379                        }
380                }
381
382                boolean haveWrittenExtensions = false;
383                for (CompositeChildElement nextChildElem : super.compositeChildIterator(theElement, theContainedResource, theParent, theEncodeContext)) {
384
385                        BaseRuntimeChildDefinition nextChild = nextChildElem.getDef();
386
387                        if (nextChildElem.getDef().getElementName().equals("extension") || nextChildElem.getDef().getElementName().equals("modifierExtension")
388                                || nextChild instanceof RuntimeChildDeclaredExtensionDefinition) {
389                                if (!haveWrittenExtensions) {
390                                        extractAndWriteExtensionsAsDirectChild(theElement, theEventWriter, myContext.getElementDefinition(theElement.getClass()), theResDef, theResource, nextChildElem, theParent, theEncodeContext, theContainedResource);
391                                        haveWrittenExtensions = true;
392                                }
393                                continue;
394                        }
395
396                        if (nextChild instanceof RuntimeChildNarrativeDefinition) {
397                                INarrativeGenerator gen = myContext.getNarrativeGenerator();
398                                if (gen != null) {
399                                        INarrative narr;
400                                        if (theResource instanceof IResource) {
401                                                narr = ((IResource) theResource).getText();
402                                        } else if (theResource instanceof IDomainResource) {
403                                                narr = ((IDomainResource) theResource).getText();
404                                        } else {
405                                                narr = null;
406                                        }
407                                        if (narr != null && narr.isEmpty()) {
408                                                gen.populateResourceNarrative(myContext, theResource);
409                                                if (!narr.isEmpty()) {
410                                                        RuntimeChildNarrativeDefinition child = (RuntimeChildNarrativeDefinition) nextChild;
411                                                        String childName = nextChild.getChildNameByDatatype(child.getDatatype());
412                                                        BaseRuntimeElementDefinition<?> type = child.getChildByName(childName);
413                                                        encodeChildElementToStreamWriter(theResDef, theResource, theEventWriter, narr, type, childName, theContainedResource, nextChildElem, false, theEncodeContext);
414                                                        continue;
415                                                }
416                                        }
417                                }
418                        } else if (nextChild instanceof RuntimeChildContainedResources) {
419                                String childName = nextChild.getValidChildNames().iterator().next();
420                                BaseRuntimeElementDefinition<?> child = nextChild.getChildByName(childName);
421                                encodeChildElementToStreamWriter(theResDef, theResource, theEventWriter, null, child, childName, theContainedResource, nextChildElem, false, theEncodeContext);
422                                continue;
423                        }
424
425                        List<? extends IBase> values = nextChild.getAccessor().getValues(theElement);
426                        values = preProcessValues(nextChild, theResource, values, nextChildElem, theEncodeContext);
427
428                        if (values == null || values.isEmpty()) {
429                                continue;
430                        }
431
432                        String currentChildName = null;
433                        boolean inArray = false;
434
435                        ArrayList<ArrayList<HeldExtension>> extensions = new ArrayList<>(0);
436                        ArrayList<ArrayList<HeldExtension>> modifierExtensions = new ArrayList<>(0);
437                        ArrayList<ArrayList<String>> comments = new ArrayList<>(0);
438                        ArrayList<String> ids = new ArrayList<>(0);
439
440                        int valueIdx = 0;
441                        for (IBase nextValue : values) {
442
443                                if (nextValue == null || nextValue.isEmpty()) {
444                                        if (nextValue instanceof BaseContainedDt) {
445                                                if (theContainedResource || getContainedResources().isEmpty()) {
446                                                        continue;
447                                                }
448                                        } else {
449                                                continue;
450                                        }
451                                }
452
453                                BaseParser.ChildNameAndDef childNameAndDef = super.getChildNameAndDef(nextChild, nextValue);
454                                if (childNameAndDef == null) {
455                                        continue;
456                                }
457
458                                /*
459                                 * Often the two values below will be the same thing. There are cases though
460                                 * where they will not be. An example would be Observation.value, which is
461                                 * a choice type. If the value contains a Quantity, then:
462                                 * nextChildGenericName = "value"
463                                 * nextChildSpecificName = "valueQuantity"
464                                 */
465                                String nextChildSpecificName = childNameAndDef.getChildName();
466                                String nextChildGenericName = nextChild.getElementName();
467
468                                theEncodeContext.pushPath(nextChildGenericName, false);
469
470                                BaseRuntimeElementDefinition<?> childDef = childNameAndDef.getChildDef();
471                                boolean primitive = childDef.getChildType() == ChildTypeEnum.PRIMITIVE_DATATYPE;
472
473                                if ((childDef.getChildType() == ChildTypeEnum.CONTAINED_RESOURCES || childDef.getChildType() == ChildTypeEnum.CONTAINED_RESOURCE_LIST) && theContainedResource) {
474                                        continue;
475                                }
476
477                                boolean force = false;
478                                if (primitive) {
479                                        if (nextValue instanceof ISupportsUndeclaredExtensions) {
480                                                List<ExtensionDt> ext = ((ISupportsUndeclaredExtensions) nextValue).getUndeclaredExtensions();
481                                                force |= addToHeldExtensions(valueIdx, ext, extensions, false, nextChildElem, theParent, theEncodeContext, theContainedResource, theElement);
482
483                                                ext = ((ISupportsUndeclaredExtensions) nextValue).getUndeclaredModifierExtensions();
484                                                force |= addToHeldExtensions(valueIdx, ext, modifierExtensions, true, nextChildElem, theParent, theEncodeContext, theContainedResource, theElement);
485                                        } else {
486                                                if (nextValue instanceof IBaseHasExtensions) {
487                                                        IBaseHasExtensions element = (IBaseHasExtensions) nextValue;
488                                                        List<? extends IBaseExtension<?, ?>> ext = element.getExtension();
489                                                        force |= addToHeldExtensions(valueIdx, ext, extensions, false, nextChildElem, theParent, theEncodeContext, theContainedResource, theElement);
490                                                }
491                                                if (nextValue instanceof IBaseHasModifierExtensions) {
492                                                        IBaseHasModifierExtensions element = (IBaseHasModifierExtensions) nextValue;
493                                                        List<? extends IBaseExtension<?, ?>> ext = element.getModifierExtension();
494                                                        force |= addToHeldExtensions(valueIdx, ext, modifierExtensions, true, nextChildElem, theParent, theEncodeContext, theContainedResource, theElement);
495                                                }
496                                        }
497                                        if (nextValue.hasFormatComment()) {
498                                                force |= addToHeldComments(valueIdx, nextValue.getFormatCommentsPre(), comments);
499                                                force |= addToHeldComments(valueIdx, nextValue.getFormatCommentsPost(), comments);
500                                        }
501                                        String elementId = getCompositeElementId(nextValue);
502                                        if (isNotBlank(elementId)) {
503                                                force = true;
504                                                addToHeldIds(valueIdx, ids, elementId);
505                                        }
506                                }
507
508                                if (currentChildName == null || !currentChildName.equals(nextChildSpecificName)) {
509                                        if (inArray) {
510                                                theEventWriter.endArray();
511                                        }
512                                        BaseRuntimeChildDefinition replacedParentDefinition = nextChild.getReplacedParentDefinition();
513                                        if (isMultipleCardinality(nextChild.getMax()) || (replacedParentDefinition != null && isMultipleCardinality(replacedParentDefinition.getMax()))) {
514                                                beginArray(theEventWriter, nextChildSpecificName);
515                                                inArray = true;
516                                                encodeChildElementToStreamWriter(theResDef, theResource, theEventWriter, nextValue, childDef, null, theContainedResource, nextChildElem, force, theEncodeContext);
517                                        } else if (nextChild instanceof RuntimeChildNarrativeDefinition && theContainedResource) {
518                                                // suppress narratives from contained resources
519                                        } else {
520                                                encodeChildElementToStreamWriter(theResDef, theResource, theEventWriter, nextValue, childDef, nextChildSpecificName, theContainedResource, nextChildElem, false, theEncodeContext);
521                                        }
522                                        currentChildName = nextChildSpecificName;
523                                } else {
524                                        encodeChildElementToStreamWriter(theResDef, theResource, theEventWriter, nextValue, childDef, null, theContainedResource, nextChildElem, force, theEncodeContext);
525                                }
526
527                                valueIdx++;
528                                theEncodeContext.popPath();
529                        }
530
531                        if (inArray) {
532                                theEventWriter.endArray();
533                        }
534
535
536                        if (!extensions.isEmpty() || !modifierExtensions.isEmpty() || !comments.isEmpty()) {
537                                if (inArray) {
538                                        // If this is a repeatable field, the extensions go in an array too
539                                        beginArray(theEventWriter, '_' + currentChildName);
540                                } else {
541                                        beginObject(theEventWriter, '_' + currentChildName);
542                                }
543
544                                for (int i = 0; i < valueIdx; i++) {
545                                        boolean haveContent = false;
546
547                                        List<HeldExtension> heldExts = Collections.emptyList();
548                                        List<HeldExtension> heldModExts = Collections.emptyList();
549                                        if (extensions.size() > i && extensions.get(i) != null && extensions.get(i).isEmpty() == false) {
550                                                haveContent = true;
551                                                heldExts = extensions.get(i);
552                                        }
553
554                                        if (modifierExtensions.size() > i && modifierExtensions.get(i) != null && modifierExtensions.get(i).isEmpty() == false) {
555                                                haveContent = true;
556                                                heldModExts = modifierExtensions.get(i);
557                                        }
558
559                                        ArrayList<String> nextComments;
560                                        if (comments.size() > i) {
561                                                nextComments = comments.get(i);
562                                        } else {
563                                                nextComments = null;
564                                        }
565                                        if (nextComments != null && nextComments.isEmpty() == false) {
566                                                haveContent = true;
567                                        }
568
569                                        String elementId = null;
570                                        if (ids.size() > i) {
571                                                elementId = ids.get(i);
572                                                haveContent |= isNotBlank(elementId);
573                                        }
574
575                                        if (!haveContent) {
576                                                theEventWriter.writeNull();
577                                        } else {
578                                                if (inArray) {
579                                                        theEventWriter.beginObject();
580                                                }
581                                                if (isNotBlank(elementId)) {
582                                                        write(theEventWriter, "id", elementId);
583                                                }
584                                                if (nextComments != null && !nextComments.isEmpty()) {
585                                                        beginArray(theEventWriter, "fhir_comments");
586                                                        for (String next : nextComments) {
587                                                                theEventWriter.write(next);
588                                                        }
589                                                        theEventWriter.endArray();
590                                                }
591                                                writeExtensionsAsDirectChild(theResource, theEventWriter, theResDef, heldExts, heldModExts, theEncodeContext, theContainedResource);
592                                                if (inArray) {
593                                                        theEventWriter.endObject();
594                                                }
595                                        }
596                                }
597
598                                if (inArray) {
599                                        theEventWriter.endArray();
600                                } else {
601                                        theEventWriter.endObject();
602                                }
603                        }
604                }
605        }
606
607        private boolean isMultipleCardinality(int maxCardinality) {
608                return maxCardinality > 1 || maxCardinality == Child.MAX_UNLIMITED;
609        }
610
611        private void encodeCompositeElementToStreamWriter(RuntimeResourceDefinition theResDef, IBaseResource theResource, IBase theNextValue, JsonLikeWriter theEventWriter, boolean theContainedResource, CompositeChildElement theParent, EncodeContext theEncodeContext) throws IOException, DataFormatException {
612
613                writeCommentsPreAndPost(theNextValue, theEventWriter);
614                encodeCompositeElementChildrenToStreamWriter(theResDef, theResource, theNextValue, theEventWriter, theContainedResource, theParent, theEncodeContext);
615        }
616
617        @Override
618        public void encodeResourceToJsonLikeWriter(IBaseResource theResource, JsonLikeWriter theJsonLikeWriter) throws IOException, DataFormatException {
619                Validate.notNull(theResource, "theResource can not be null");
620                Validate.notNull(theJsonLikeWriter, "theJsonLikeWriter can not be null");
621
622                if (theResource.getStructureFhirVersionEnum() != myContext.getVersion().getVersion()) {
623                        throw new IllegalArgumentException(
624                                "This parser is for FHIR version " + myContext.getVersion().getVersion() + " - Can not encode a structure for version " + theResource.getStructureFhirVersionEnum());
625                }
626
627                EncodeContext encodeContext = new EncodeContext();
628                String resourceName = myContext.getResourceType(theResource);
629                encodeContext.pushPath(resourceName, true);
630                doEncodeResourceToJsonLikeWriter(theResource, theJsonLikeWriter, encodeContext);
631        }
632
633        private void encodeResourceToJsonStreamWriter(RuntimeResourceDefinition theResDef, IBaseResource theResource, JsonLikeWriter theEventWriter, String theObjectNameOrNull,
634                                                                                                                                 boolean theContainedResource, EncodeContext theEncodeContext) throws IOException {
635                IIdType resourceId = null;
636
637                if (StringUtils.isNotBlank(theResource.getIdElement().getIdPart())) {
638                        resourceId = theResource.getIdElement();
639                        if (theResource.getIdElement().getValue().startsWith("urn:")) {
640                                resourceId = null;
641                        }
642                }
643
644                if (!theContainedResource) {
645                        if (!super.shouldEncodeResourceId(theResource, theEncodeContext)) {
646                                resourceId = null;
647                        } else if (theEncodeContext.getResourcePath().size() == 1 && getEncodeForceResourceId() != null) {
648                                resourceId = getEncodeForceResourceId();
649                        }
650                }
651
652                encodeResourceToJsonStreamWriter(theResDef, theResource, theEventWriter, theObjectNameOrNull, theContainedResource, resourceId, theEncodeContext);
653        }
654
655        private void encodeResourceToJsonStreamWriter(RuntimeResourceDefinition theResDef, IBaseResource theResource, JsonLikeWriter theEventWriter, String theObjectNameOrNull,
656                                                                                                                                 boolean theContainedResource, IIdType theResourceId, EncodeContext theEncodeContext) throws IOException {
657
658                if (!super.shouldEncodeResource(theResDef.getName())) {
659                        return;
660                }
661
662                if (!theContainedResource) {
663                        super.containResourcesForEncoding(theResource);
664                }
665
666                RuntimeResourceDefinition resDef = myContext.getResourceDefinition(theResource);
667
668                if (theObjectNameOrNull == null) {
669                        theEventWriter.beginObject();
670                } else {
671                        beginObject(theEventWriter, theObjectNameOrNull);
672                }
673
674                write(theEventWriter, "resourceType", resDef.getName());
675                if (theResourceId != null && theResourceId.hasIdPart()) {
676                        write(theEventWriter, "id", theResourceId.getIdPart());
677                        final List<HeldExtension> extensions = new ArrayList<>(0);
678                        final List<HeldExtension> modifierExtensions = new ArrayList<>(0);
679                        // Undeclared extensions
680                        extractUndeclaredExtensions(theResourceId, extensions, modifierExtensions, null, null, theEncodeContext, theContainedResource);
681                        boolean haveExtension = false;
682                        if (!extensions.isEmpty()) {
683                                haveExtension = true;
684                        }
685
686                        if (theResourceId.hasFormatComment() || haveExtension) {
687                                beginObject(theEventWriter, "_id");
688                                if (theResourceId.hasFormatComment()) {
689                                        writeCommentsPreAndPost(theResourceId, theEventWriter);
690                                }
691                                if (haveExtension) {
692                                        writeExtensionsAsDirectChild(theResource, theEventWriter, theResDef, extensions, modifierExtensions, theEncodeContext, theContainedResource);
693                                }
694                                theEventWriter.endObject();
695                        }
696                }
697
698                if (theResource instanceof IResource) {
699                        IResource resource = (IResource) theResource;
700                        // Object securityLabelRawObj =
701
702                        List<BaseCodingDt> securityLabels = extractMetadataListNotNull(resource, ResourceMetadataKeyEnum.SECURITY_LABELS);
703                        List<? extends IIdType> profiles = extractMetadataListNotNull(resource, ResourceMetadataKeyEnum.PROFILES);
704                        profiles = super.getProfileTagsForEncoding(resource, profiles);
705
706                        TagList tags = getMetaTagsForEncoding(resource, theEncodeContext);
707                        InstantDt updated = (InstantDt) resource.getResourceMetadata().get(ResourceMetadataKeyEnum.UPDATED);
708                        IdDt resourceId = resource.getId();
709                        String versionIdPart = resourceId.getVersionIdPart();
710                        if (isBlank(versionIdPart)) {
711                                versionIdPart = ResourceMetadataKeyEnum.VERSION.get(resource);
712                        }
713                        List<Map.Entry<ResourceMetadataKeyEnum<?>, Object>> extensionMetadataKeys = getExtensionMetadataKeys(resource);
714
715                        if (super.shouldEncodeResourceMeta(resource) && (ElementUtil.isEmpty(versionIdPart, updated, securityLabels, tags, profiles) == false) || !extensionMetadataKeys.isEmpty()) {
716                                beginObject(theEventWriter, "meta");
717
718                                if (shouldEncodePath(resource, "meta.versionId")) {
719                                        writeOptionalTagWithTextNode(theEventWriter, "versionId", versionIdPart);
720                                }
721                                if (shouldEncodePath(resource, "meta.lastUpdated")) {
722                                        writeOptionalTagWithTextNode(theEventWriter, "lastUpdated", updated);
723                                }
724
725                                if (profiles != null && profiles.isEmpty() == false) {
726                                        beginArray(theEventWriter, "profile");
727                                        for (IIdType profile : profiles) {
728                                                if (profile != null && isNotBlank(profile.getValue())) {
729                                                        theEventWriter.write(profile.getValue());
730                                                }
731                                        }
732                                        theEventWriter.endArray();
733                                }
734
735                                if (securityLabels.isEmpty() == false) {
736                                        beginArray(theEventWriter, "security");
737                                        for (BaseCodingDt securityLabel : securityLabels) {
738                                                theEventWriter.beginObject();
739                                                theEncodeContext.pushPath("security", false);
740                                                encodeCompositeElementChildrenToStreamWriter(resDef, resource, securityLabel, theEventWriter, theContainedResource, null, theEncodeContext);
741                                                theEncodeContext.popPath();
742                                                theEventWriter.endObject();
743                                        }
744                                        theEventWriter.endArray();
745                                }
746
747                                if (tags != null && tags.isEmpty() == false) {
748                                        beginArray(theEventWriter, "tag");
749                                        for (Tag tag : tags) {
750                                                if (tag.isEmpty()) {
751                                                        continue;
752                                                }
753                                                theEventWriter.beginObject();
754                                                writeOptionalTagWithTextNode(theEventWriter, "system", tag.getScheme());
755                                                writeOptionalTagWithTextNode(theEventWriter, "code", tag.getTerm());
756                                                writeOptionalTagWithTextNode(theEventWriter, "display", tag.getLabel());
757                                                theEventWriter.endObject();
758                                        }
759                                        theEventWriter.endArray();
760                                }
761
762                                addExtensionMetadata(theResDef, theResource, theContainedResource, extensionMetadataKeys, resDef, theEventWriter, theEncodeContext);
763
764                                theEventWriter.endObject(); // end meta
765                        }
766                }
767
768                encodeCompositeElementToStreamWriter(theResDef, theResource, theResource, theEventWriter, theContainedResource, new CompositeChildElement(resDef, theEncodeContext), theEncodeContext);
769
770                theEventWriter.endObject();
771        }
772
773
774        private void addExtensionMetadata(RuntimeResourceDefinition theResDef, IBaseResource theResource,
775                                                                                                 boolean theContainedResource,
776                                                                                                 List<Map.Entry<ResourceMetadataKeyEnum<?>, Object>> extensionMetadataKeys,
777                                                                                                 RuntimeResourceDefinition resDef,
778                                                                                                 JsonLikeWriter theEventWriter, EncodeContext theEncodeContext) throws IOException {
779                if (extensionMetadataKeys.isEmpty()) {
780                        return;
781                }
782
783                ExtensionDt metaResource = new ExtensionDt();
784                for (Map.Entry<ResourceMetadataKeyEnum<?>, Object> entry : extensionMetadataKeys) {
785                        metaResource.addUndeclaredExtension((ExtensionDt) entry.getValue());
786                }
787                encodeCompositeElementToStreamWriter(theResDef, theResource, metaResource, theEventWriter, theContainedResource, new CompositeChildElement(resDef, theEncodeContext), theEncodeContext);
788        }
789
790        /**
791         * This is useful only for the two cases where extensions are encoded as direct children (e.g. not in some object
792         * called _name): resource extensions, and extension extensions
793         */
794        private void extractAndWriteExtensionsAsDirectChild(IBase theElement, JsonLikeWriter theEventWriter, BaseRuntimeElementDefinition<?> theElementDef, RuntimeResourceDefinition theResDef,
795                                                                                                                                                 IBaseResource theResource, CompositeChildElement theChildElem, CompositeChildElement theParent, EncodeContext theEncodeContext, boolean theContainedResource) throws IOException {
796                List<HeldExtension> extensions = new ArrayList<>(0);
797                List<HeldExtension> modifierExtensions = new ArrayList<>(0);
798
799                // Undeclared extensions
800                extractUndeclaredExtensions(theElement, extensions, modifierExtensions, theChildElem, theParent, theEncodeContext, theContainedResource);
801
802                // Declared extensions
803                if (theElementDef != null) {
804                        extractDeclaredExtensions(theElement, theElementDef, extensions, modifierExtensions, theChildElem);
805                }
806
807                // Write the extensions
808                writeExtensionsAsDirectChild(theResource, theEventWriter, theResDef, extensions, modifierExtensions, theEncodeContext, theContainedResource);
809        }
810
811        private void extractDeclaredExtensions(IBase theResource, BaseRuntimeElementDefinition<?> resDef, List<HeldExtension> extensions, List<HeldExtension> modifierExtensions,
812                                                                                                                CompositeChildElement theChildElem) {
813                for (RuntimeChildDeclaredExtensionDefinition nextDef : resDef.getExtensionsNonModifier()) {
814                        for (IBase nextValue : nextDef.getAccessor().getValues(theResource)) {
815                                if (nextValue != null) {
816                                        if (nextValue.isEmpty()) {
817                                                continue;
818                                        }
819                                        extensions.add(new HeldExtension(nextDef, nextValue, theChildElem));
820                                }
821                        }
822                }
823                for (RuntimeChildDeclaredExtensionDefinition nextDef : resDef.getExtensionsModifier()) {
824                        for (IBase nextValue : nextDef.getAccessor().getValues(theResource)) {
825                                if (nextValue != null) {
826                                        if (nextValue.isEmpty()) {
827                                                continue;
828                                        }
829                                        modifierExtensions.add(new HeldExtension(nextDef, nextValue, theChildElem));
830                                }
831                        }
832                }
833        }
834
835        private void extractUndeclaredExtensions(IBase theElement, List<HeldExtension> extensions, List<HeldExtension> modifierExtensions, CompositeChildElement theChildElem,
836                                                                                                                  CompositeChildElement theParent, EncodeContext theEncodeContext, boolean theContainedResource) {
837                if (theElement instanceof ISupportsUndeclaredExtensions) {
838                        ISupportsUndeclaredExtensions element = (ISupportsUndeclaredExtensions) theElement;
839                        List<ExtensionDt> ext = element.getUndeclaredExtensions();
840                        for (ExtensionDt next : ext) {
841                                if (next == null || next.isEmpty()) {
842                                        continue;
843                                }
844                                extensions.add(new HeldExtension(next, false, theChildElem, theParent));
845                        }
846
847                        ext = element.getUndeclaredModifierExtensions();
848                        for (ExtensionDt next : ext) {
849                                if (next == null || next.isEmpty()) {
850                                        continue;
851                                }
852                                modifierExtensions.add(new HeldExtension(next, true, theChildElem, theParent));
853                        }
854                } else {
855                        if (theElement instanceof IBaseHasExtensions) {
856                                IBaseHasExtensions element = (IBaseHasExtensions) theElement;
857                                List<? extends IBaseExtension<?, ?>> ext = element.getExtension();
858                                Boolean encodeExtension = null;
859                                for (IBaseExtension<?, ?> next : ext) {
860                                        if (next == null || (ElementUtil.isEmpty(next.getValue()) && next.getExtension().isEmpty())) {
861                                                continue;
862                                        }
863
864                                        // Make sure we respect _elements and _summary
865                                        if (encodeExtension == null) {
866                                                encodeExtension = isEncodeExtension(theParent, theEncodeContext, theContainedResource, element);
867                                        }
868                                        if (encodeExtension) {
869                                                HeldExtension extension = new HeldExtension(next, false, theChildElem, theParent);
870                                                extensions.add(extension);
871                                        }
872
873                                }
874                        }
875                        if (theElement instanceof IBaseHasModifierExtensions) {
876                                IBaseHasModifierExtensions element = (IBaseHasModifierExtensions) theElement;
877                                List<? extends IBaseExtension<?, ?>> ext = element.getModifierExtension();
878                                for (IBaseExtension<?, ?> next : ext) {
879                                        if (next == null || next.isEmpty()) {
880                                                continue;
881                                        }
882
883                                        HeldExtension extension = new HeldExtension(next, true, theChildElem, theParent);
884                                        modifierExtensions.add(extension);
885                                }
886                        }
887                }
888        }
889
890        private boolean isEncodeExtension(CompositeChildElement theParent, EncodeContext theEncodeContext, boolean theContainedResource, IBase theElement) {
891//              theEncodeContext.pushPath("extension", false);
892                BaseRuntimeElementDefinition<?> runtimeElementDefinition = myContext.getElementDefinition(theElement.getClass());
893                boolean retVal = true;
894                if (runtimeElementDefinition instanceof BaseRuntimeElementCompositeDefinition) {
895                        BaseRuntimeElementCompositeDefinition definition = (BaseRuntimeElementCompositeDefinition) runtimeElementDefinition;
896                        BaseRuntimeChildDefinition childDef = definition.getChildByName("extension");
897                        CompositeChildElement c = new CompositeChildElement(theParent, childDef, theEncodeContext);
898                        retVal = c.shouldBeEncoded(theContainedResource);
899                }
900//              theEncodeContext.popPath();
901                return retVal;
902        }
903
904        @Override
905        public EncodingEnum getEncoding() {
906                return EncodingEnum.JSON;
907        }
908
909        private JsonLikeArray grabJsonArray(JsonLikeObject theObject, String nextName, String thePosition) {
910                JsonLikeValue object = theObject.get(nextName);
911                if (object == null || object.isNull()) {
912                        return null;
913                }
914                if (!object.isArray()) {
915                        throw new DataFormatException("Syntax error parsing JSON FHIR structure: Expected ARRAY at element '" + thePosition + "', found '" + object.getJsonType() + "'");
916                }
917                return object.getAsArray();
918        }
919
920        // private JsonObject parse(Reader theReader) {
921        //
922        // PushbackReader pbr = new PushbackReader(theReader);
923        // JsonObject object;
924        // try {
925        // while(true) {
926        // int nextInt;
927        // nextInt = pbr.read();
928        // if (nextInt == -1) {
929        // throw new DataFormatException("Did not find any content to parse");
930        // }
931        // if (nextInt == '{') {
932        // pbr.unread('{');
933        // break;
934        // }
935        // if (Character.isWhitespace(nextInt)) {
936        // continue;
937        // }
938        // throw new DataFormatException("Content does not appear to be FHIR JSON, first non-whitespace character was: '" + (char)nextInt + "' (must be '{')");
939        // }
940        //
941        // Gson gson = newGson();
942        //
943        // object = gson.fromJson(pbr, JsonObject.class);
944        // } catch (Exception e) {
945        // throw new DataFormatException("Failed to parse JSON content, error was: " + e.getMessage(), e);
946        // }
947        //
948        // return object;
949        // }
950
951        private void parseAlternates(JsonLikeValue theAlternateVal, ParserState<?> theState, String theElementName, String theAlternateName) {
952                if (theAlternateVal == null || theAlternateVal.isNull()) {
953                        return;
954                }
955
956                if (theAlternateVal.isArray()) {
957                        JsonLikeArray array = theAlternateVal.getAsArray();
958                        if (array.size() > 1) {
959                                throw new DataFormatException("Unexpected array of length " + array.size() + " (expected 0 or 1) for element: " + theElementName);
960                        }
961                        if (array.size() == 0) {
962                                return;
963                        }
964                        parseAlternates(array.get(0), theState, theElementName, theAlternateName);
965                        return;
966                }
967
968                JsonLikeValue alternateVal = theAlternateVal;
969                if (alternateVal.isObject() == false) {
970                        getErrorHandler().incorrectJsonType(null, theAlternateName, ValueType.OBJECT, null, alternateVal.getJsonType(), null);
971                        return;
972                }
973
974                JsonLikeObject alternate = alternateVal.getAsObject();
975                for (String nextKey : alternate.keySet()) {
976                        JsonLikeValue nextVal = alternate.get(nextKey);
977                        if ("extension".equals(nextKey)) {
978                                boolean isModifier = false;
979                                JsonLikeArray array = nextVal.getAsArray();
980                                parseExtension(theState, array, isModifier);
981                        } else if ("modifierExtension".equals(nextKey)) {
982                                boolean isModifier = true;
983                                JsonLikeArray array = nextVal.getAsArray();
984                                parseExtension(theState, array, isModifier);
985                        } else if ("id".equals(nextKey)) {
986                                if (nextVal.isString()) {
987                                        theState.attributeValue("id", nextVal.getAsString());
988                                } else {
989                                        getErrorHandler().incorrectJsonType(null, "id", ValueType.SCALAR, ScalarType.STRING, nextVal.getJsonType(), nextVal.getDataType());
990                                }
991                        } else if ("fhir_comments".equals(nextKey)) {
992                                parseFhirComments(nextVal, theState);
993                        }
994                }
995        }
996
997        private void parseChildren(JsonLikeObject theObject, ParserState<?> theState) {
998                Set<String> keySet = theObject.keySet();
999
1000                int allUnderscoreNames = 0;
1001                int handledUnderscoreNames = 0;
1002
1003                for (String nextName : keySet) {
1004                        if ("resourceType".equals(nextName)) {
1005                                continue;
1006                        } else if ("extension".equals(nextName)) {
1007                                JsonLikeArray array = grabJsonArray(theObject, nextName, "extension");
1008                                parseExtension(theState, array, false);
1009                                continue;
1010                        } else if ("modifierExtension".equals(nextName)) {
1011                                JsonLikeArray array = grabJsonArray(theObject, nextName, "modifierExtension");
1012                                parseExtension(theState, array, true);
1013                                continue;
1014                        } else if (nextName.equals("fhir_comments")) {
1015                                parseFhirComments(theObject.get(nextName), theState);
1016                                continue;
1017                        } else if (nextName.charAt(0) == '_') {
1018                                allUnderscoreNames++;
1019                                continue;
1020                        }
1021
1022                        JsonLikeValue nextVal = theObject.get(nextName);
1023                        String alternateName = '_' + nextName;
1024                        JsonLikeValue alternateVal = theObject.get(alternateName);
1025                        if (alternateVal != null) {
1026                                handledUnderscoreNames++;
1027                        }
1028
1029                        parseChildren(theState, nextName, nextVal, alternateVal, alternateName, false);
1030
1031                }
1032
1033                // if (elementId != null) {
1034                // IBase object = (IBase) theState.getObject();
1035                // if (object instanceof IIdentifiableElement) {
1036                // ((IIdentifiableElement) object).setElementSpecificId(elementId);
1037                // } else if (object instanceof IBaseResource) {
1038                // ((IBaseResource) object).getIdElement().setValue(elementId);
1039                // }
1040                // }
1041
1042                /*
1043                 * This happens if an element has an extension but no actual value. I.e.
1044                 * if a resource has a "_status" element but no corresponding "status"
1045                 * element. This could be used to handle a null value with an extension
1046                 * for example.
1047                 */
1048                if (allUnderscoreNames > handledUnderscoreNames) {
1049                        for (String alternateName : keySet) {
1050                                if (alternateName.startsWith("_") && alternateName.length() > 1) {
1051                                        JsonLikeValue nextValue = theObject.get(alternateName);
1052                                        if (nextValue != null) {
1053                                                if (nextValue.isObject()) {
1054                                                        String nextName = alternateName.substring(1);
1055                                                        if (theObject.get(nextName) == null) {
1056                                                                theState.enteringNewElement(null, nextName);
1057                                                                parseAlternates(nextValue, theState, alternateName, alternateName);
1058                                                                theState.endingElement();
1059                                                        }
1060                                                } else {
1061                                                        getErrorHandler().incorrectJsonType(null, alternateName, ValueType.OBJECT, null, nextValue.getJsonType(), null);
1062                                                }
1063                                        }
1064                                }
1065                        }
1066                }
1067
1068        }
1069
1070        private void parseChildren(ParserState<?> theState, String theName, JsonLikeValue theJsonVal, JsonLikeValue theAlternateVal, String theAlternateName, boolean theInArray) {
1071                if (theName.equals("id")) {
1072                        if (!theJsonVal.isString()) {
1073                                getErrorHandler().incorrectJsonType(null, "id", ValueType.SCALAR, ScalarType.STRING, theJsonVal.getJsonType(), theJsonVal.getDataType());
1074                        }
1075                }
1076
1077                if (theJsonVal.isArray()) {
1078                        JsonLikeArray nextArray = theJsonVal.getAsArray();
1079
1080                        JsonLikeValue alternateVal = theAlternateVal;
1081                        if (alternateVal != null && alternateVal.isArray() == false) {
1082                                getErrorHandler().incorrectJsonType(null, theAlternateName, ValueType.ARRAY, null, alternateVal.getJsonType(), null);
1083                                alternateVal = null;
1084                        }
1085
1086                        JsonLikeArray nextAlternateArray = JsonLikeValue.asArray(alternateVal); // could be null
1087                        for (int i = 0; i < nextArray.size(); i++) {
1088                                JsonLikeValue nextObject = nextArray.get(i);
1089                                JsonLikeValue nextAlternate = null;
1090                                if (nextAlternateArray != null && nextAlternateArray.size() >= (i + 1)) {
1091                                        nextAlternate = nextAlternateArray.get(i);
1092                                }
1093                                parseChildren(theState, theName, nextObject, nextAlternate, theAlternateName, true);
1094                        }
1095                } else if (theJsonVal.isObject()) {
1096                        if (!theInArray && theState.elementIsRepeating(theName)) {
1097                                getErrorHandler().incorrectJsonType(null, theName, ValueType.ARRAY, null, ValueType.OBJECT, null);
1098                        }
1099
1100                        theState.enteringNewElement(null, theName);
1101                        parseAlternates(theAlternateVal, theState, theAlternateName, theAlternateName);
1102                        JsonLikeObject nextObject = theJsonVal.getAsObject();
1103                        boolean preResource = false;
1104                        if (theState.isPreResource()) {
1105                                JsonLikeValue resType = nextObject.get("resourceType");
1106                                if (resType == null || !resType.isString()) {
1107                                        throw new DataFormatException("Missing required element 'resourceType' from JSON resource object, unable to parse");
1108                                }
1109                                theState.enteringNewElement(null, resType.getAsString());
1110                                preResource = true;
1111                        }
1112                        parseChildren(nextObject, theState);
1113                        if (preResource) {
1114                                theState.endingElement();
1115                        }
1116                        theState.endingElement();
1117                } else if (theJsonVal.isNull()) {
1118                        theState.enteringNewElement(null, theName);
1119                        parseAlternates(theAlternateVal, theState, theAlternateName, theAlternateName);
1120                        theState.endingElement();
1121                } else {
1122                        // must be a SCALAR
1123                        theState.enteringNewElement(null, theName);
1124                        String asString = theJsonVal.getAsString();
1125                        theState.attributeValue("value", asString);
1126                        parseAlternates(theAlternateVal, theState, theAlternateName, theAlternateName);
1127                        theState.endingElement();
1128                }
1129        }
1130
1131        private void parseExtension(ParserState<?> theState, JsonLikeArray theValues, boolean theIsModifier) {
1132                int allUnderscoreNames = 0;
1133                int handledUnderscoreNames = 0;
1134
1135                for (int i = 0; i < theValues.size(); i++) {
1136                        JsonLikeObject nextExtObj = JsonLikeValue.asObject(theValues.get(i));
1137                        JsonLikeValue jsonElement = nextExtObj.get("url");
1138                        String url;
1139                        if (null == jsonElement || !(jsonElement.isScalar())) {
1140                                String parentElementName;
1141                                if (theIsModifier) {
1142                                        parentElementName = "modifierExtension";
1143                                } else {
1144                                        parentElementName = "extension";
1145                                }
1146                                getErrorHandler().missingRequiredElement(new ParseLocation().setParentElementName(parentElementName), "url");
1147                                url = null;
1148                        } else {
1149                                url = getExtensionUrl(jsonElement.getAsString());
1150                        }
1151                        theState.enteringNewElementExtension(null, url, theIsModifier, getServerBaseUrl());
1152                        for (String next : nextExtObj.keySet()) {
1153                                if ("url".equals(next)) {
1154                                        continue;
1155                                } else if ("extension".equals(next)) {
1156                                        JsonLikeArray jsonVal = JsonLikeValue.asArray(nextExtObj.get(next));
1157                                        parseExtension(theState, jsonVal, false);
1158                                } else if ("modifierExtension".equals(next)) {
1159                                        JsonLikeArray jsonVal = JsonLikeValue.asArray(nextExtObj.get(next));
1160                                        parseExtension(theState, jsonVal, true);
1161                                } else if (next.charAt(0) == '_') {
1162                                        allUnderscoreNames++;
1163                                        continue;
1164                                } else {
1165                                        JsonLikeValue jsonVal = nextExtObj.get(next);
1166                                        String alternateName = '_' + next;
1167                                        JsonLikeValue alternateVal = nextExtObj.get(alternateName);
1168                                        if (alternateVal != null) {
1169                                                handledUnderscoreNames++;
1170                                        }
1171                                        parseChildren(theState, next, jsonVal, alternateVal, alternateName, false);
1172                                }
1173                        }
1174
1175                        /*
1176                         * This happens if an element has an extension but no actual value. I.e.
1177                         * if a resource has a "_status" element but no corresponding "status"
1178                         * element. This could be used to handle a null value with an extension
1179                         * for example.
1180                         */
1181                        if (allUnderscoreNames > handledUnderscoreNames) {
1182                                for (String alternateName : nextExtObj.keySet()) {
1183                                        if (alternateName.startsWith("_") && alternateName.length() > 1) {
1184                                                JsonLikeValue nextValue = nextExtObj.get(alternateName);
1185                                                if (nextValue != null) {
1186                                                        if (nextValue.isObject()) {
1187                                                                String nextName = alternateName.substring(1);
1188                                                                if (nextExtObj.get(nextName) == null) {
1189                                                                        theState.enteringNewElement(null, nextName);
1190                                                                        parseAlternates(nextValue, theState, alternateName, alternateName);
1191                                                                        theState.endingElement();
1192                                                                }
1193                                                        } else {
1194                                                                getErrorHandler().incorrectJsonType(null, alternateName, ValueType.OBJECT, null, nextValue.getJsonType(), null);
1195                                                        }
1196                                                }
1197                                        }
1198                                }
1199                        }
1200                        theState.endingElement();
1201                }
1202        }
1203
1204        private void parseFhirComments(JsonLikeValue theObject, ParserState<?> theState) {
1205                if (theObject.isArray()) {
1206                        JsonLikeArray comments = theObject.getAsArray();
1207                        for (int i = 0; i < comments.size(); i++) {
1208                                JsonLikeValue nextComment = comments.get(i);
1209                                if (nextComment.isString()) {
1210                                        String commentText = nextComment.getAsString();
1211                                        if (commentText != null) {
1212                                                theState.commentPre(commentText);
1213                                        }
1214                                }
1215                        }
1216                }
1217        }
1218
1219        @Override
1220        public <T extends IBaseResource> T parseResource(Class<T> theResourceType, JsonLikeStructure theJsonLikeStructure) throws DataFormatException {
1221
1222                /*****************************************************
1223                 * ************************************************* *
1224                 * ** NOTE: this duplicates most of the code in ** *
1225                 * ** BaseParser.parseResource(Class<T>, Reader). ** *
1226                 * ** Unfortunately, there is no way to avoid ** *
1227                 * ** this without doing some refactoring of the ** *
1228                 * ** BaseParser class. ** *
1229                 * ************************************************* *
1230                 *****************************************************/
1231
1232                /*
1233                 * We do this so that the context can verify that the structure is for
1234                 * the correct FHIR version
1235                 */
1236                if (theResourceType != null) {
1237                        myContext.getResourceDefinition(theResourceType);
1238                }
1239
1240                // Actually do the parse
1241                T retVal = doParseResource(theResourceType, theJsonLikeStructure);
1242
1243                RuntimeResourceDefinition def = myContext.getResourceDefinition(retVal);
1244                if ("Bundle".equals(def.getName())) {
1245
1246                        BaseRuntimeChildDefinition entryChild = def.getChildByName("entry");
1247                        BaseRuntimeElementCompositeDefinition<?> entryDef = (BaseRuntimeElementCompositeDefinition<?>) entryChild.getChildByName("entry");
1248                        List<IBase> entries = entryChild.getAccessor().getValues(retVal);
1249                        if (entries != null) {
1250                                for (IBase nextEntry : entries) {
1251
1252                                        /**
1253                                         * If Bundle.entry.fullUrl is populated, set the resource ID to that
1254                                         */
1255                                        // TODO: should emit a warning and maybe notify the error handler if the resource ID doesn't match the
1256                                        // fullUrl idPart
1257                                        BaseRuntimeChildDefinition fullUrlChild = entryDef.getChildByName("fullUrl");
1258                                        if (fullUrlChild == null) {
1259                                                continue; // TODO: remove this once the data model in tinder plugin catches up to 1.2
1260                                        }
1261                                        List<IBase> fullUrl = fullUrlChild.getAccessor().getValues(nextEntry);
1262                                        if (fullUrl != null && !fullUrl.isEmpty()) {
1263                                                IPrimitiveType<?> value = (IPrimitiveType<?>) fullUrl.get(0);
1264                                                if (value.isEmpty() == false) {
1265                                                        List<IBase> entryResources = entryDef.getChildByName("resource").getAccessor().getValues(nextEntry);
1266                                                        if (entryResources != null && entryResources.size() > 0) {
1267                                                                IBaseResource res = (IBaseResource) entryResources.get(0);
1268                                                                String versionId = res.getIdElement().getVersionIdPart();
1269                                                                res.setId(value.getValueAsString());
1270                                                                if (isNotBlank(versionId) && res.getIdElement().hasVersionIdPart() == false) {
1271                                                                        res.setId(res.getIdElement().withVersion(versionId));
1272                                                                }
1273                                                        }
1274                                                }
1275                                        }
1276
1277                                }
1278                        }
1279
1280                }
1281
1282                return retVal;
1283        }
1284
1285        @Override
1286        public IBaseResource parseResource(JsonLikeStructure theJsonLikeStructure) throws DataFormatException {
1287                return parseResource(null, theJsonLikeStructure);
1288        }
1289
1290        @Override
1291        public IParser setPrettyPrint(boolean thePrettyPrint) {
1292                myPrettyPrint = thePrettyPrint;
1293                return this;
1294        }
1295
1296        private void write(JsonLikeWriter theEventWriter, String theChildName, Boolean theValue) throws IOException {
1297                if (theValue != null) {
1298                        theEventWriter.write(theChildName, theValue.booleanValue());
1299                }
1300        }
1301
1302        // private void parseExtensionInDstu2Style(boolean theModifier, ParserState<?> theState, String
1303        // theParentExtensionUrl, String theExtensionUrl, JsonArray theValues) {
1304        // String extUrl = UrlUtil.constructAbsoluteUrl(theParentExtensionUrl, theExtensionUrl);
1305        // theState.enteringNewElementExtension(null, extUrl, theModifier);
1306        //
1307        // for (int extIdx = 0; extIdx < theValues.size(); extIdx++) {
1308        // JsonObject nextExt = theValues.getJsonObject(extIdx);
1309        // for (String nextKey : nextExt.keySet()) {
1310        // // if (nextKey.startsWith("value") && nextKey.length() > 5 &&
1311        // // myContext.getRuntimeChildUndeclaredExtensionDefinition().getChildByName(nextKey) != null) {
1312        // JsonElement jsonVal = nextExt.get(nextKey);
1313        // if (jsonVal.getValueType() == ValueType.ARRAY) {
1314        // /*
1315        // * Extension children which are arrays are sub-extensions. Any other value type should be treated as a value.
1316        // */
1317        // JsonArray arrayValue = (JsonArray) jsonVal;
1318        // parseExtensionInDstu2Style(theModifier, theState, extUrl, nextKey, arrayValue);
1319        // } else {
1320        // parseChildren(theState, nextKey, jsonVal, null, null);
1321        // }
1322        // }
1323        // }
1324        //
1325        // theState.endingElement();
1326        // }
1327
1328        private void write(JsonLikeWriter theEventWriter, String theChildName, BigDecimal theDecimalValue) throws IOException {
1329                theEventWriter.write(theChildName, theDecimalValue);
1330        }
1331
1332        private void write(JsonLikeWriter theEventWriter, String theChildName, Integer theValue) throws IOException {
1333                theEventWriter.write(theChildName, theValue);
1334        }
1335
1336        private void writeCommentsPreAndPost(IBase theNextValue, JsonLikeWriter theEventWriter) throws IOException {
1337                if (theNextValue.hasFormatComment()) {
1338                        beginArray(theEventWriter, "fhir_comments");
1339                        List<String> pre = theNextValue.getFormatCommentsPre();
1340                        if (pre.isEmpty() == false) {
1341                                for (String next : pre) {
1342                                        theEventWriter.write(next);
1343                                }
1344                        }
1345                        List<String> post = theNextValue.getFormatCommentsPost();
1346                        if (post.isEmpty() == false) {
1347                                for (String next : post) {
1348                                        theEventWriter.write(next);
1349                                }
1350                        }
1351                        theEventWriter.endArray();
1352                }
1353        }
1354
1355        private void writeExtensionsAsDirectChild(IBaseResource theResource, JsonLikeWriter theEventWriter, RuntimeResourceDefinition resDef, List<HeldExtension> extensions,
1356                                                                                                                        List<HeldExtension> modifierExtensions, EncodeContext theEncodeContext, boolean theContainedResource) throws IOException {
1357                // Write Extensions
1358                if (extensions.isEmpty() == false) {
1359                        theEncodeContext.pushPath("extension", false);
1360                        beginArray(theEventWriter, "extension");
1361                        for (HeldExtension next : extensions) {
1362                                next.write(resDef, theResource, theEventWriter, theEncodeContext, theContainedResource);
1363                        }
1364                        theEventWriter.endArray();
1365                        theEncodeContext.popPath();
1366                }
1367
1368                // Write ModifierExtensions
1369                if (modifierExtensions.isEmpty() == false) {
1370                        theEncodeContext.pushPath("modifierExtension", false);
1371                        beginArray(theEventWriter, "modifierExtension");
1372                        for (HeldExtension next : modifierExtensions) {
1373                                next.write(resDef, theResource, theEventWriter, theEncodeContext, theContainedResource);
1374                        }
1375                        theEventWriter.endArray();
1376                        theEncodeContext.popPath();
1377                }
1378        }
1379
1380        private void writeOptionalTagWithTextNode(JsonLikeWriter theEventWriter, String theElementName, IPrimitiveDatatype<?> thePrimitive) throws IOException {
1381                if (thePrimitive == null) {
1382                        return;
1383                }
1384                String str = thePrimitive.getValueAsString();
1385                writeOptionalTagWithTextNode(theEventWriter, theElementName, str);
1386        }
1387
1388        private void writeOptionalTagWithTextNode(JsonLikeWriter theEventWriter, String theElementName, String theValue) throws IOException {
1389                if (StringUtils.isNotBlank(theValue)) {
1390                        write(theEventWriter, theElementName, theValue);
1391                }
1392        }
1393
1394        private class HeldExtension implements Comparable<HeldExtension> {
1395
1396                private CompositeChildElement myChildElem;
1397                private RuntimeChildDeclaredExtensionDefinition myDef;
1398                private boolean myModifier;
1399                private IBaseExtension<?, ?> myUndeclaredExtension;
1400                private IBase myValue;
1401                private CompositeChildElement myParent;
1402
1403                public HeldExtension(IBaseExtension<?, ?> theUndeclaredExtension, boolean theModifier, CompositeChildElement theChildElem, CompositeChildElement theParent) {
1404                        assert theUndeclaredExtension != null;
1405                        myUndeclaredExtension = theUndeclaredExtension;
1406                        myModifier = theModifier;
1407                        myChildElem = theChildElem;
1408                        myParent = theParent;
1409                }
1410
1411                public HeldExtension(RuntimeChildDeclaredExtensionDefinition theDef, IBase theValue, CompositeChildElement theChildElem) {
1412                        assert theDef != null;
1413                        assert theValue != null;
1414                        myDef = theDef;
1415                        myValue = theValue;
1416                        myChildElem = theChildElem;
1417                }
1418
1419                @Override
1420                public int compareTo(HeldExtension theArg0) {
1421                        String url1 = myDef != null ? myDef.getExtensionUrl() : myUndeclaredExtension.getUrl();
1422                        String url2 = theArg0.myDef != null ? theArg0.myDef.getExtensionUrl() : theArg0.myUndeclaredExtension.getUrl();
1423                        url1 = defaultString(getExtensionUrl(url1));
1424                        url2 = defaultString(getExtensionUrl(url2));
1425                        return url1.compareTo(url2);
1426                }
1427
1428                private void managePrimitiveExtension(final IBase theValue, final RuntimeResourceDefinition theResDef, final IBaseResource theResource, final JsonLikeWriter theEventWriter, final BaseRuntimeElementDefinition<?> def, final String childName, EncodeContext theEncodeContext, boolean theContainedResource) throws IOException {
1429                        if (def.getChildType().equals(ID_DATATYPE) || def.getChildType().equals(PRIMITIVE_DATATYPE)) {
1430                                final List<HeldExtension> extensions = new ArrayList<HeldExtension>(0);
1431                                final List<HeldExtension> modifierExtensions = new ArrayList<HeldExtension>(0);
1432                                // Undeclared extensions
1433                                extractUndeclaredExtensions(theValue, extensions, modifierExtensions, myParent, null, theEncodeContext, theContainedResource);
1434                                // Declared extensions
1435                                if (def != null) {
1436                                        extractDeclaredExtensions(theValue, def, extensions, modifierExtensions, myParent);
1437                                }
1438                                boolean haveContent = false;
1439                                if (!extensions.isEmpty() || !modifierExtensions.isEmpty()) {
1440                                        haveContent = true;
1441                                }
1442                                if (haveContent) {
1443                                        beginObject(theEventWriter, '_' + childName);
1444                                        writeExtensionsAsDirectChild(theResource, theEventWriter, theResDef, extensions, modifierExtensions, theEncodeContext, theContainedResource);
1445                                        theEventWriter.endObject();
1446                                }
1447                        }
1448                }
1449
1450                public void write(RuntimeResourceDefinition theResDef, IBaseResource theResource, JsonLikeWriter theEventWriter, EncodeContext theEncodeContext, boolean theContainedResource) throws IOException {
1451                        if (myUndeclaredExtension != null) {
1452                                writeUndeclaredExtension(theResDef, theResource, theEventWriter, myUndeclaredExtension, theEncodeContext, theContainedResource);
1453                        } else {
1454                                theEventWriter.beginObject();
1455
1456                                writeCommentsPreAndPost(myValue, theEventWriter);
1457
1458                                JsonParser.write(theEventWriter, "url", getExtensionUrl(myDef.getExtensionUrl()));
1459
1460                                /*
1461                                 * This makes sure that even if the extension contains a reference to a contained
1462                                 * resource which has a HAPI-assigned ID we'll still encode that ID.
1463                                 *
1464                                 * See #327
1465                                 */
1466                                List<? extends IBase> preProcessedValue = preProcessValues(myDef, theResource, Collections.singletonList(myValue), myChildElem, theEncodeContext);
1467
1468                                // // Check for undeclared extensions on the declared extension
1469                                // // (grrrrrr....)
1470                                // if (myValue instanceof ISupportsUndeclaredExtensions) {
1471                                // ISupportsUndeclaredExtensions value = (ISupportsUndeclaredExtensions)myValue;
1472                                // List<ExtensionDt> exts = value.getUndeclaredExtensions();
1473                                // if (exts.size() > 0) {
1474                                // ArrayList<IBase> newValueList = new ArrayList<IBase>();
1475                                // newValueList.addAll(preProcessedValue);
1476                                // newValueList.addAll(exts);
1477                                // preProcessedValue = newValueList;
1478                                // }
1479                                // }
1480
1481                                myValue = preProcessedValue.get(0);
1482
1483                                BaseRuntimeElementDefinition<?> def = myDef.getChildElementDefinitionByDatatype(myValue.getClass());
1484                                if (def.getChildType() == ChildTypeEnum.RESOURCE_BLOCK) {
1485                                        extractAndWriteExtensionsAsDirectChild(myValue, theEventWriter, def, theResDef, theResource, myChildElem, null, theEncodeContext, theContainedResource);
1486                                } else {
1487                                        String childName = myDef.getChildNameByDatatype(myValue.getClass());
1488                                        encodeChildElementToStreamWriter(theResDef, theResource, theEventWriter, myValue, def, childName, false, myParent, false, theEncodeContext);
1489                                        managePrimitiveExtension(myValue, theResDef, theResource, theEventWriter, def, childName, theEncodeContext, theContainedResource);
1490                                }
1491
1492                                theEventWriter.endObject();
1493                        }
1494                }
1495
1496                private void writeUndeclaredExtension(RuntimeResourceDefinition theResDef, IBaseResource theResource, JsonLikeWriter theEventWriter, IBaseExtension<?, ?> ext, EncodeContext theEncodeContext, boolean theContainedResource) throws IOException {
1497                        IBase value = ext.getValue();
1498                        final String extensionUrl = getExtensionUrl(ext.getUrl());
1499
1500                        theEventWriter.beginObject();
1501
1502                        writeCommentsPreAndPost(myUndeclaredExtension, theEventWriter);
1503
1504                        String elementId = getCompositeElementId(ext);
1505                        if (isNotBlank(elementId)) {
1506                                JsonParser.write(theEventWriter, "id", getCompositeElementId(ext));
1507                        }
1508
1509                        if (isBlank(extensionUrl)) {
1510                                ParseLocation loc = new ParseLocation(theEncodeContext.toString());
1511                                getErrorHandler().missingRequiredElement(loc, "url");
1512                        }
1513
1514                        JsonParser.write(theEventWriter, "url", extensionUrl);
1515
1516                        boolean noValue = value == null || value.isEmpty();
1517                        if (noValue && ext.getExtension().isEmpty()) {
1518
1519                                ParseLocation loc = new ParseLocation(theEncodeContext.toString());
1520                                getErrorHandler().missingRequiredElement(loc, "value");
1521                                ourLog.debug("Extension with URL[{}] has no value", extensionUrl);
1522
1523                        } else {
1524
1525                                if (!noValue && !ext.getExtension().isEmpty()) {
1526                                        ParseLocation loc = new ParseLocation(theEncodeContext.toString());
1527                                        getErrorHandler().extensionContainsValueAndNestedExtensions(loc);
1528                                }
1529
1530                                // Write child extensions
1531                                if (!ext.getExtension().isEmpty()) {
1532
1533                                        if (myModifier) {
1534                                                beginArray(theEventWriter, "modifierExtension");
1535                                        } else {
1536                                                beginArray(theEventWriter, "extension");
1537                                        }
1538
1539                                        for (Object next : ext.getExtension()) {
1540                                                writeUndeclaredExtension(theResDef, theResource, theEventWriter, (IBaseExtension<?, ?>) next, theEncodeContext, theContainedResource);
1541                                        }
1542                                        theEventWriter.endArray();
1543
1544                                }
1545
1546                                // Write value
1547                                if (!noValue) {
1548                                        theEncodeContext.pushPath("value", false);
1549
1550                                        /*
1551                                         * Pre-process value - This is called in case the value is a reference
1552                                         * since we might modify the text
1553                                         */
1554                                        value = preProcessValues(myDef, theResource, Collections.singletonList(value), myChildElem, theEncodeContext).get(0);
1555
1556                                        RuntimeChildUndeclaredExtensionDefinition extDef = myContext.getRuntimeChildUndeclaredExtensionDefinition();
1557                                        String childName = extDef.getChildNameByDatatype(value.getClass());
1558                                        if (childName == null) {
1559                                                childName = "value" + WordUtils.capitalize(myContext.getElementDefinition(value.getClass()).getName());
1560                                        }
1561                                        BaseRuntimeElementDefinition<?> childDef = extDef.getChildElementDefinitionByDatatype(value.getClass());
1562                                        if (childDef == null) {
1563                                                throw new ConfigurationException("Unable to encode extension, unrecognized child element type: " + value.getClass().getCanonicalName());
1564                                        }
1565                                        encodeChildElementToStreamWriter(theResDef, theResource, theEventWriter, value, childDef, childName, false, myParent, false, theEncodeContext);
1566                                        managePrimitiveExtension(value, theResDef, theResource, theEventWriter, childDef, childName, theEncodeContext, theContainedResource);
1567
1568                                        theEncodeContext.popPath();
1569                                }
1570                        }
1571
1572                        // theEventWriter.name(myUndeclaredExtension.get);
1573
1574                        theEventWriter.endObject();
1575                }
1576        }
1577
1578        private static void write(JsonLikeWriter theWriter, String theName, String theValue) throws IOException {
1579                theWriter.write(theName, theValue);
1580        }
1581}