001package ca.uhn.fhir.parser;
002
003/*-
004 * #%L
005 * HAPI FHIR - Core Library
006 * %%
007 * Copyright (C) 2014 - 2019 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.model.api.*;
025import ca.uhn.fhir.model.base.composite.BaseCodingDt;
026import ca.uhn.fhir.model.primitive.IdDt;
027import ca.uhn.fhir.model.primitive.InstantDt;
028import ca.uhn.fhir.model.primitive.XhtmlDt;
029import ca.uhn.fhir.narrative.INarrativeGenerator;
030import ca.uhn.fhir.rest.api.EncodingEnum;
031import ca.uhn.fhir.util.ElementUtil;
032import ca.uhn.fhir.util.NonPrettyPrintWriterWrapper;
033import ca.uhn.fhir.util.PrettyPrintWriterWrapper;
034import ca.uhn.fhir.util.XmlUtil;
035import org.apache.commons.lang3.StringUtils;
036import org.hl7.fhir.instance.model.api.*;
037
038import javax.xml.namespace.QName;
039import javax.xml.stream.*;
040import javax.xml.stream.events.*;
041import java.io.Reader;
042import java.io.Writer;
043import java.util.ArrayList;
044import java.util.Iterator;
045import java.util.List;
046import java.util.Optional;
047
048import static org.apache.commons.lang3.StringUtils.isBlank;
049import static org.apache.commons.lang3.StringUtils.isNotBlank;
050
051/**
052 * This class is the FHIR XML parser/encoder. Users should not interact with this class directly, but should use
053 * {@link FhirContext#newXmlParser()} to get an instance.
054 */
055public class XmlParser extends BaseParser {
056
057        static final String FHIR_NS = "http://hl7.org/fhir";
058        private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(XmlParser.class);
059
060        // private static final Set<String> RESOURCE_NAMESPACES;
061        private FhirContext myContext;
062        private boolean myPrettyPrint;
063
064        /**
065         * Do not use this constructor, the recommended way to obtain a new instance of the XML parser is to invoke
066         * {@link FhirContext#newXmlParser()}.
067         *
068         * @param theParserErrorHandler
069         */
070        public XmlParser(FhirContext theContext, IParserErrorHandler theParserErrorHandler) {
071                super(theContext, theParserErrorHandler);
072                myContext = theContext;
073        }
074
075        private XMLEventReader createStreamReader(Reader theReader) {
076                try {
077                        return XmlUtil.createXmlReader(theReader);
078                } catch (FactoryConfigurationError e1) {
079                        throw new ConfigurationException("Failed to initialize STaX event factory", e1);
080                } catch (XMLStreamException e1) {
081                        throw new DataFormatException(e1);
082                }
083        }
084
085        private XMLStreamWriter createXmlWriter(Writer theWriter) throws XMLStreamException {
086                XMLStreamWriter eventWriter;
087                eventWriter = XmlUtil.createXmlStreamWriter(theWriter);
088                eventWriter = decorateStreamWriter(eventWriter);
089                return eventWriter;
090        }
091
092        private XMLStreamWriter decorateStreamWriter(XMLStreamWriter eventWriter) {
093                if (myPrettyPrint) {
094                        PrettyPrintWriterWrapper retVal = new PrettyPrintWriterWrapper(eventWriter);
095                        return retVal;
096                }
097                NonPrettyPrintWriterWrapper retVal = new NonPrettyPrintWriterWrapper(eventWriter);
098                return retVal;
099        }
100
101        @Override
102        public void doEncodeResourceToWriter(IBaseResource theResource, Writer theWriter, EncodeContext theEncodeContext) throws DataFormatException {
103                XMLStreamWriter eventWriter;
104                try {
105                        eventWriter = createXmlWriter(theWriter);
106
107                        encodeResourceToXmlStreamWriter(theResource, eventWriter, false, theEncodeContext);
108                        eventWriter.flush();
109                } catch (XMLStreamException e) {
110                        throw new ConfigurationException("Failed to initialize STaX event factory", e);
111                }
112        }
113
114        @Override
115        public <T extends IBaseResource> T doParseResource(Class<T> theResourceType, Reader theReader) {
116                XMLEventReader streamReader = createStreamReader(theReader);
117                return parseResource(theResourceType, streamReader);
118        }
119
120        private <T> T doXmlLoop(XMLEventReader streamReader, ParserState<T> parserState) {
121                ourLog.trace("Entering XML parsing loop with state: {}", parserState);
122
123                try {
124                        List<String> heldComments = new ArrayList<>(1);
125
126                        while (streamReader.hasNext()) {
127                                XMLEvent nextEvent = streamReader.nextEvent();
128                                try {
129
130                                        switch (nextEvent.getEventType()) {
131                                                case XMLStreamConstants.START_ELEMENT: {
132                                                        StartElement elem = nextEvent.asStartElement();
133
134                                                        String namespaceURI = elem.getName().getNamespaceURI();
135
136                                                        if ("extension".equals(elem.getName().getLocalPart())) {
137                                                                Attribute urlAttr = elem.getAttributeByName(new QName("url"));
138                                                                String url;
139                                                                if (urlAttr == null || isBlank(urlAttr.getValue())) {
140                                                                        getErrorHandler().missingRequiredElement(new ParseLocation().setParentElementName("extension"), "url");
141                                                                        url = null;
142                                                                } else {
143                                                                        url = urlAttr.getValue();
144                                                                }
145                                                                parserState.enteringNewElementExtension(elem, url, false, getServerBaseUrl());
146                                                        } else if ("modifierExtension".equals(elem.getName().getLocalPart())) {
147                                                                Attribute urlAttr = elem.getAttributeByName(new QName("url"));
148                                                                String url;
149                                                                if (urlAttr == null || isBlank(urlAttr.getValue())) {
150                                                                        getErrorHandler().missingRequiredElement(new ParseLocation().setParentElementName("modifierExtension"), "url");
151                                                                        url = null;
152                                                                } else {
153                                                                        url = urlAttr.getValue();
154                                                                }
155                                                                parserState.enteringNewElementExtension(elem, url, true, getServerBaseUrl());
156                                                        } else {
157                                                                String elementName = elem.getName().getLocalPart();
158                                                                parserState.enteringNewElement(namespaceURI, elementName);
159                                                        }
160
161                                                        if (!heldComments.isEmpty()) {
162                                                                for (String next : heldComments) {
163                                                                        parserState.commentPre(next);
164                                                                }
165                                                                heldComments.clear();
166                                                        }
167
168                                                        for (Iterator<Attribute> attributes = elem.getAttributes(); attributes.hasNext(); ) {
169                                                                Attribute next = attributes.next();
170                                                                parserState.attributeValue(next.getName().getLocalPart(), next.getValue());
171                                                        }
172
173                                                        break;
174                                                }
175                                                case XMLStreamConstants.END_DOCUMENT:
176                                                case XMLStreamConstants.END_ELEMENT: {
177                                                        if (!heldComments.isEmpty()) {
178                                                                for (String next : heldComments) {
179                                                                        parserState.commentPost(next);
180                                                                }
181                                                                heldComments.clear();
182                                                        }
183                                                        parserState.endingElement();
184//                                              if (parserState.isComplete()) {
185//                                                      return parserState.getObject();
186//                                              }
187                                                        break;
188                                                }
189                                                case XMLStreamConstants.CHARACTERS: {
190                                                        parserState.string(nextEvent.asCharacters().getData());
191                                                        break;
192                                                }
193                                                case XMLStreamConstants.COMMENT: {
194                                                        Comment comment = (Comment) nextEvent;
195                                                        String commentText = comment.getText();
196                                                        heldComments.add(commentText);
197                                                        break;
198                                                }
199                                        }
200
201                                        parserState.xmlEvent(nextEvent);
202
203                                } catch (DataFormatException e) {
204                                        throw new DataFormatException("DataFormatException at [" + nextEvent.getLocation().toString() + "]: " + e.getMessage(), e);
205                                }
206                        }
207                        return parserState.getObject();
208                } catch (XMLStreamException e) {
209                        throw new DataFormatException(e);
210                }
211        }
212
213        private void encodeChildElementToStreamWriter(IBaseResource theResource, XMLStreamWriter theEventWriter, BaseRuntimeChildDefinition theChildDefinition, IBase theElement, String theChildName, BaseRuntimeElementDefinition<?> childDef,
214                                                                                                                                 String theExtensionUrl, boolean theIncludedResource, CompositeChildElement theParent, EncodeContext theEncodeContext) throws XMLStreamException, DataFormatException {
215
216                /*
217                 * Often the two values below will be the same thing. There are cases though
218                 * where they will not be. An example would be Observation.value, which is
219                 * a choice type. If the value contains a Quantity, then:
220                 * childGenericName = "value"
221                 * theChildName = "valueQuantity"
222                 */
223                String childGenericName = theChildDefinition.getElementName();
224
225                theEncodeContext.pushPath(childGenericName, false);
226                try {
227
228                        if (theElement == null || theElement.isEmpty()) {
229                                if (isChildContained(childDef, theIncludedResource)) {
230                                        // We still want to go in..
231                                } else {
232                                        return;
233                                }
234                        }
235
236                        writeCommentsPre(theEventWriter, theElement);
237
238                        switch (childDef.getChildType()) {
239                                case ID_DATATYPE: {
240                                        IIdType value = IIdType.class.cast(theElement);
241                                        String encodedValue = "id".equals(theChildName) ? value.getIdPart() : value.getValue();
242                                        if (StringUtils.isNotBlank(encodedValue) || !super.hasNoExtensions(value)) {
243                                                theEventWriter.writeStartElement(theChildName);
244                                                if (StringUtils.isNotBlank(encodedValue)) {
245                                                        theEventWriter.writeAttribute("value", encodedValue);
246                                                }
247                                                encodeExtensionsIfPresent(theResource, theEventWriter, theElement, theIncludedResource, theEncodeContext);
248                                                theEventWriter.writeEndElement();
249                                        }
250                                        break;
251                                }
252                                case PRIMITIVE_DATATYPE: {
253                                        IPrimitiveType<?> pd = IPrimitiveType.class.cast(theElement);
254                                        String value = pd.getValueAsString();
255                                        if (value != null || !super.hasNoExtensions(pd)) {
256                                                theEventWriter.writeStartElement(theChildName);
257                                                String elementId = getCompositeElementId(theElement);
258                                                if (isNotBlank(elementId)) {
259                                                        theEventWriter.writeAttribute("id", elementId);
260                                                }
261                                                if (value != null) {
262                                                        theEventWriter.writeAttribute("value", value);
263                                                }
264                                                encodeExtensionsIfPresent(theResource, theEventWriter, theElement, theIncludedResource, theEncodeContext);
265                                                theEventWriter.writeEndElement();
266                                        }
267                                        break;
268                                }
269                                case RESOURCE_BLOCK:
270                                case COMPOSITE_DATATYPE: {
271                                        theEventWriter.writeStartElement(theChildName);
272                                        String elementId = getCompositeElementId(theElement);
273                                        if (isNotBlank(elementId)) {
274                                                theEventWriter.writeAttribute("id", elementId);
275                                        }
276                                        if (isNotBlank(theExtensionUrl)) {
277                                                theEventWriter.writeAttribute("url", theExtensionUrl);
278                                        }
279                                        encodeCompositeElementToStreamWriter(theResource, theElement, theEventWriter, theIncludedResource, theParent, theEncodeContext);
280                                        theEventWriter.writeEndElement();
281                                        break;
282                                }
283                                case CONTAINED_RESOURCE_LIST:
284                                case CONTAINED_RESOURCES: {
285                                        /*
286                                         * Disable per #103 for (IResource next : value.getContainedResources()) { if (getContainedResources().getResourceId(next) != null) { continue; }
287                                         * theEventWriter.writeStartElement("contained"); encodeResourceToXmlStreamWriter(next, theEventWriter, true, fixContainedResourceId(next.getId().getValue()));
288                                         * theEventWriter.writeEndElement(); }
289                                         */
290                                        for (IBaseResource next : getContainedResources().getContainedResources()) {
291                                                IIdType resourceId = getContainedResources().getResourceId(next);
292                                                theEventWriter.writeStartElement("contained");
293                                                encodeResourceToXmlStreamWriter(next, theEventWriter, true, fixContainedResourceId(resourceId.getValue()), theEncodeContext);
294                                                theEventWriter.writeEndElement();
295                                        }
296                                        break;
297                                }
298                                case RESOURCE: {
299                                        IBaseResource resource = (IBaseResource) theElement;
300                                        String resourceName = myContext.getResourceDefinition(resource).getName();
301                                        if (!super.shouldEncodeResource(resourceName)) {
302                                                break;
303                                        }
304                                        theEventWriter.writeStartElement(theChildName);
305                                        theEncodeContext.pushPath(resourceName, true);
306                                        encodeResourceToXmlStreamWriter(resource, theEventWriter, false, theEncodeContext);
307                                        theEncodeContext.popPath();
308                                        theEventWriter.writeEndElement();
309                                        break;
310                                }
311                                case PRIMITIVE_XHTML: {
312                                        XhtmlDt dt = XhtmlDt.class.cast(theElement);
313                                        if (dt.hasContent()) {
314                                                encodeXhtml(dt, theEventWriter);
315                                        }
316                                        break;
317                                }
318                                case PRIMITIVE_XHTML_HL7ORG: {
319                                        IBaseXhtml dt = IBaseXhtml.class.cast(theElement);
320                                        if (!dt.isEmpty()) {
321                                                // TODO: this is probably not as efficient as it could be
322                                                XhtmlDt hdt = new XhtmlDt();
323                                                hdt.setValueAsString(dt.getValueAsString());
324                                                encodeXhtml(hdt, theEventWriter);
325                                        }
326                                        break;
327                                }
328                                case EXTENSION_DECLARED:
329                                case UNDECL_EXT: {
330                                        throw new IllegalStateException("state should not happen: " + childDef.getName());
331                                }
332                        }
333
334                        writeCommentsPost(theEventWriter, theElement);
335
336                } finally {
337                        theEncodeContext.popPath();
338                }
339
340        }
341
342        private void encodeCompositeElementToStreamWriter(IBaseResource theResource, IBase theElement, XMLStreamWriter theEventWriter, boolean theContainedResource, CompositeChildElement theParent, EncodeContext theEncodeContext)
343                throws XMLStreamException, DataFormatException {
344
345                for (CompositeChildElement nextChildElem : super.compositeChildIterator(theElement, theContainedResource, theParent, theEncodeContext)) {
346
347                        BaseRuntimeChildDefinition nextChild = nextChildElem.getDef();
348
349                        if (nextChild.getElementName().equals("url") && theElement instanceof IBaseExtension) {
350                                /*
351                                 * XML encoding is a one-off for extensions. The URL element goes in an attribute
352                                 * instead of being encoded as a normal element, only for XML encoding
353                                 */
354                                continue;
355                        }
356
357                        if (nextChild instanceof RuntimeChildNarrativeDefinition) {
358                                Optional<IBase> narr = nextChild.getAccessor().getFirstValueOrNull(theElement);
359                                INarrativeGenerator gen = myContext.getNarrativeGenerator();
360                                if (gen != null && narr.isPresent() == false) {
361                                        gen.populateResourceNarrative(myContext, theResource);
362                                }
363
364                                narr = nextChild.getAccessor().getFirstValueOrNull(theElement);
365                                if (narr.isPresent()) {
366                                        RuntimeChildNarrativeDefinition child = (RuntimeChildNarrativeDefinition) nextChild;
367                                        String childName = nextChild.getChildNameByDatatype(child.getDatatype());
368                                        BaseRuntimeElementDefinition<?> type = child.getChildByName(childName);
369                                        encodeChildElementToStreamWriter(theResource, theEventWriter, nextChild, narr.get(), childName, type, null, theContainedResource, nextChildElem, theEncodeContext);
370                                        continue;
371                                }
372                        }
373
374                        if (nextChild instanceof RuntimeChildContainedResources) {
375                                encodeChildElementToStreamWriter(theResource, theEventWriter, nextChild, null, nextChild.getChildNameByDatatype(null), nextChild.getChildElementDefinitionByDatatype(null), null, theContainedResource, nextChildElem, theEncodeContext);
376                        } else {
377
378                                List<? extends IBase> values = nextChild.getAccessor().getValues(theElement);
379                                values = preProcessValues(nextChild, theResource, values, nextChildElem, theEncodeContext);
380
381                                if (values == null || values.isEmpty()) {
382                                        continue;
383                                }
384                                for (IBase nextValue : values) {
385                                        if ((nextValue == null || nextValue.isEmpty())) {
386                                                continue;
387                                        }
388
389                                        BaseParser.ChildNameAndDef childNameAndDef = super.getChildNameAndDef(nextChild, nextValue);
390                                        if (childNameAndDef == null) {
391                                                continue;
392                                        }
393
394                                        String childName = childNameAndDef.getChildName();
395                                        BaseRuntimeElementDefinition<?> childDef = childNameAndDef.getChildDef();
396                                        String extensionUrl = getExtensionUrl(nextChild.getExtensionUrl());
397
398                                        boolean isExtension = childName.equals("extension") || childName.equals("modifierExtension");
399                                        if (isExtension && nextValue instanceof IBaseExtension) {
400                                                IBaseExtension<?, ?> ext = (IBaseExtension<?, ?>) nextValue;
401                                                if (isBlank(ext.getUrl())) {
402                                                        ParseLocation loc = new ParseLocation(theEncodeContext.toString() + "." + childName);
403                                                        getErrorHandler().missingRequiredElement(loc, "url");
404                                                }
405                                                if (ext.getValue() != null && ext.getExtension().size() > 0) {
406                                                        ParseLocation loc = new ParseLocation(theEncodeContext.toString() + "." + childName);
407                                                        getErrorHandler().extensionContainsValueAndNestedExtensions(loc);
408                                                }
409                                        }
410
411                                        if (extensionUrl != null && isExtension == false) {
412                                                encodeExtension(theResource, theEventWriter, theContainedResource, nextChildElem, nextChild, nextValue, childName, extensionUrl, childDef, theEncodeContext);
413                                        } else if (nextChild instanceof RuntimeChildExtension) {
414                                                IBaseExtension<?, ?> extension = (IBaseExtension<?, ?>) nextValue;
415                                                if ((extension.getValue() == null || extension.getValue().isEmpty())) {
416                                                        if (extension.getExtension().isEmpty()) {
417                                                                continue;
418                                                        }
419                                                }
420                                                encodeChildElementToStreamWriter(theResource, theEventWriter, nextChild, nextValue, childName, childDef, getExtensionUrl(extension.getUrl()), theContainedResource, nextChildElem, theEncodeContext);
421                                        } else if (nextChild instanceof RuntimeChildNarrativeDefinition && theContainedResource) {
422                                                // suppress narratives from contained resources
423                                        } else {
424                                                encodeChildElementToStreamWriter(theResource, theEventWriter, nextChild, nextValue, childName, childDef, extensionUrl, theContainedResource, nextChildElem, theEncodeContext);
425                                        }
426
427                                }
428                        }
429                }
430        }
431
432        private void encodeExtension(IBaseResource theResource, XMLStreamWriter theEventWriter, boolean theContainedResource, CompositeChildElement nextChildElem, BaseRuntimeChildDefinition nextChild, IBase nextValue, String childName, String extensionUrl, BaseRuntimeElementDefinition<?> childDef, EncodeContext theEncodeContext)
433                throws XMLStreamException {
434                BaseRuntimeDeclaredChildDefinition extDef = (BaseRuntimeDeclaredChildDefinition) nextChild;
435                if (extDef.isModifier()) {
436                        theEventWriter.writeStartElement("modifierExtension");
437                } else {
438                        theEventWriter.writeStartElement("extension");
439                }
440
441                String elementId = getCompositeElementId(nextValue);
442                if (isNotBlank(elementId)) {
443                        theEventWriter.writeAttribute("id", elementId);
444                }
445
446                if (isBlank(extensionUrl)) {
447                        ParseLocation loc = new ParseLocation(theEncodeContext.toString());
448                        getErrorHandler().missingRequiredElement(loc, "url");
449                } else {
450                        theEventWriter.writeAttribute("url", extensionUrl);
451                }
452
453                encodeChildElementToStreamWriter(theResource, theEventWriter, nextChild, nextValue, childName, childDef, null, theContainedResource, nextChildElem, theEncodeContext);
454                theEventWriter.writeEndElement();
455        }
456
457        private void encodeExtensionsIfPresent(IBaseResource theResource, XMLStreamWriter theWriter, IBase theElement, boolean theIncludedResource, EncodeContext theEncodeContext) throws XMLStreamException, DataFormatException {
458                if (theElement instanceof ISupportsUndeclaredExtensions) {
459                        ISupportsUndeclaredExtensions res = (ISupportsUndeclaredExtensions) theElement;
460                        encodeUndeclaredExtensions(theResource, theWriter, toBaseExtensionList(res.getUndeclaredExtensions()), "extension", theIncludedResource, theEncodeContext);
461                        encodeUndeclaredExtensions(theResource, theWriter, toBaseExtensionList(res.getUndeclaredModifierExtensions()), "modifierExtension", theIncludedResource, theEncodeContext);
462                }
463                if (theElement instanceof IBaseHasExtensions) {
464                        IBaseHasExtensions res = (IBaseHasExtensions) theElement;
465                        encodeUndeclaredExtensions(theResource, theWriter, res.getExtension(), "extension", theIncludedResource, theEncodeContext);
466                }
467                if (theElement instanceof IBaseHasModifierExtensions) {
468                        IBaseHasModifierExtensions res = (IBaseHasModifierExtensions) theElement;
469                        encodeUndeclaredExtensions(theResource, theWriter, res.getModifierExtension(), "modifierExtension", theIncludedResource, theEncodeContext);
470                }
471        }
472
473        private void encodeResourceToXmlStreamWriter(IBaseResource theResource, XMLStreamWriter theEventWriter, boolean theIncludedResource, EncodeContext theEncodeContext) throws XMLStreamException, DataFormatException {
474                IIdType resourceId = null;
475
476                if (StringUtils.isNotBlank(theResource.getIdElement().getIdPart())) {
477                        resourceId = theResource.getIdElement();
478                        if (theResource.getIdElement().getValue().startsWith("urn:")) {
479                                resourceId = null;
480                        }
481                }
482
483                if (!theIncludedResource) {
484                        if (super.shouldEncodeResourceId(theResource, theEncodeContext) == false) {
485                                resourceId = null;
486                        } else if (theEncodeContext.getResourcePath().size() == 1 && getEncodeForceResourceId() != null) {
487                                resourceId = getEncodeForceResourceId();
488                        }
489                }
490
491                encodeResourceToXmlStreamWriter(theResource, theEventWriter, theIncludedResource, resourceId, theEncodeContext);
492        }
493
494        private void encodeResourceToXmlStreamWriter(IBaseResource theResource, XMLStreamWriter theEventWriter, boolean theContainedResource, IIdType theResourceId, EncodeContext theEncodeContext) throws XMLStreamException {
495                RuntimeResourceDefinition resDef = myContext.getResourceDefinition(theResource);
496                if (resDef == null) {
497                        throw new ConfigurationException("Unknown resource type: " + theResource.getClass());
498                }
499
500                if (!theContainedResource) {
501                        super.containResourcesForEncoding(theResource);
502                }
503
504                theEventWriter.writeStartElement(resDef.getName());
505                theEventWriter.writeDefaultNamespace(FHIR_NS);
506
507                if (theResource instanceof IAnyResource) {
508                        // HL7.org Structures
509                        if (theResourceId != null) {
510                                writeCommentsPre(theEventWriter, theResourceId);
511                                theEventWriter.writeStartElement("id");
512                                theEventWriter.writeAttribute("value", theResourceId.getIdPart());
513                                encodeExtensionsIfPresent(theResource, theEventWriter, theResourceId, false, theEncodeContext);
514                                theEventWriter.writeEndElement();
515                                writeCommentsPost(theEventWriter, theResourceId);
516                        }
517
518                        encodeCompositeElementToStreamWriter(theResource, theResource, theEventWriter, theContainedResource, new CompositeChildElement(resDef, theEncodeContext), theEncodeContext);
519
520                } else {
521
522                        // DSTU2+
523
524                        IResource resource = (IResource) theResource;
525                        if (theResourceId != null) {
526          /*    writeCommentsPre(theEventWriter, theResourceId);
527              writeOptionalTagWithValue(theEventWriter, "id", theResourceId.getIdPart());
528                                            writeCommentsPost(theEventWriter, theResourceId);*/
529                                theEventWriter.writeStartElement("id");
530                                theEventWriter.writeAttribute("value", theResourceId.getIdPart());
531                                encodeExtensionsIfPresent(theResource, theEventWriter, theResourceId, false, theEncodeContext);
532                                theEventWriter.writeEndElement();
533                                writeCommentsPost(theEventWriter, theResourceId);
534                        }
535
536                        InstantDt updated = (InstantDt) resource.getResourceMetadata().get(ResourceMetadataKeyEnum.UPDATED);
537                        IdDt resourceId = resource.getId();
538                        String versionIdPart = resourceId.getVersionIdPart();
539                        if (isBlank(versionIdPart)) {
540                                versionIdPart = ResourceMetadataKeyEnum.VERSION.get(resource);
541                        }
542                        List<BaseCodingDt> securityLabels = extractMetadataListNotNull(resource, ResourceMetadataKeyEnum.SECURITY_LABELS);
543                        List<? extends IIdType> profiles = extractMetadataListNotNull(resource, ResourceMetadataKeyEnum.PROFILES);
544                        profiles = super.getProfileTagsForEncoding(resource, profiles);
545
546                        TagList tags = getMetaTagsForEncoding((resource), theEncodeContext);
547
548                        if (super.shouldEncodeResourceMeta(resource) && ElementUtil.isEmpty(versionIdPart, updated, securityLabels, tags, profiles) == false) {
549                                theEventWriter.writeStartElement("meta");
550                                if (shouldEncodePath(resource, "meta.versionId")) {
551                                        writeOptionalTagWithValue(theEventWriter, "versionId", versionIdPart);
552                                }
553                                if (updated != null) {
554                                        if (shouldEncodePath(resource, "meta.lastUpdated")) {
555                                                writeOptionalTagWithValue(theEventWriter, "lastUpdated", updated.getValueAsString());
556                                        }
557                                }
558
559                                for (IIdType profile : profiles) {
560                                        theEventWriter.writeStartElement("profile");
561                                        theEventWriter.writeAttribute("value", profile.getValue());
562                                        theEventWriter.writeEndElement();
563                                }
564                                for (BaseCodingDt securityLabel : securityLabels) {
565                                        theEventWriter.writeStartElement("security");
566                                        encodeCompositeElementToStreamWriter(resource, securityLabel, theEventWriter, theContainedResource, null, theEncodeContext);
567                                        theEventWriter.writeEndElement();
568                                }
569                                if (tags != null) {
570                                        for (Tag tag : tags) {
571                                                if (tag.isEmpty()) {
572                                                        continue;
573                                                }
574                                                theEventWriter.writeStartElement("tag");
575                                                writeOptionalTagWithValue(theEventWriter, "system", tag.getScheme());
576                                                writeOptionalTagWithValue(theEventWriter, "code", tag.getTerm());
577                                                writeOptionalTagWithValue(theEventWriter, "display", tag.getLabel());
578                                                theEventWriter.writeEndElement();
579                                        }
580                                }
581                                theEventWriter.writeEndElement();
582                        }
583
584                        if (theResource instanceof IBaseBinary) {
585                                IBaseBinary bin = (IBaseBinary) theResource;
586                                writeOptionalTagWithValue(theEventWriter, "contentType", bin.getContentType());
587                                writeOptionalTagWithValue(theEventWriter, "content", bin.getContentAsBase64());
588                        } else {
589                                encodeCompositeElementToStreamWriter(theResource, theResource, theEventWriter, theContainedResource, new CompositeChildElement(resDef, theEncodeContext), theEncodeContext);
590                        }
591
592                }
593
594                theEventWriter.writeEndElement();
595        }
596
597        private void encodeUndeclaredExtensions(IBaseResource theResource, XMLStreamWriter theEventWriter, List<? extends IBaseExtension<?, ?>> theExtensions, String tagName, boolean theIncludedResource, EncodeContext theEncodeContext)
598                throws XMLStreamException, DataFormatException {
599                for (IBaseExtension<?, ?> next : theExtensions) {
600                        if (next == null || (ElementUtil.isEmpty(next.getValue()) && next.getExtension().isEmpty())) {
601                                continue;
602                        }
603
604                        writeCommentsPre(theEventWriter, next);
605
606                        theEventWriter.writeStartElement(tagName);
607
608                        String elementId = getCompositeElementId(next);
609                        if (isNotBlank(elementId)) {
610                                theEventWriter.writeAttribute("id", elementId);
611                        }
612
613                        String url = getExtensionUrl(next.getUrl());
614                        if (isNotBlank(url)) {
615                                theEventWriter.writeAttribute("url", url);
616                        }
617
618                        if (next.getValue() != null) {
619                                IBaseDatatype value = next.getValue();
620                                RuntimeChildUndeclaredExtensionDefinition extDef = myContext.getRuntimeChildUndeclaredExtensionDefinition();
621                                String childName = extDef.getChildNameByDatatype(value.getClass());
622                                BaseRuntimeElementDefinition<?> childDef;
623                                if (childName == null) {
624                                        childDef = myContext.getElementDefinition(value.getClass());
625                                        if (childDef == null) {
626                                                throw new ConfigurationException("Unable to encode extension, unrecognized child element type: " + value.getClass().getCanonicalName());
627                                        }
628                                        childName = RuntimeChildUndeclaredExtensionDefinition.createExtensionChildName(childDef);
629                                } else {
630                                        childDef = extDef.getChildElementDefinitionByDatatype(value.getClass());
631                                        if (childDef == null) {
632                                                throw new ConfigurationException("Unable to encode extension, unrecognized child element type: " + value.getClass().getCanonicalName());
633                                        }
634                                }
635                                encodeChildElementToStreamWriter(theResource, theEventWriter, extDef, value, childName, childDef, null, theIncludedResource, null, theEncodeContext);
636                        }
637
638                        // child extensions
639                        encodeExtensionsIfPresent(theResource, theEventWriter, next, theIncludedResource, theEncodeContext);
640
641                        theEventWriter.writeEndElement();
642
643                        writeCommentsPost(theEventWriter, next);
644
645                }
646        }
647
648
649        private void encodeXhtml(XhtmlDt theDt, XMLStreamWriter theEventWriter) throws XMLStreamException {
650                if (theDt == null || theDt.getValue() == null) {
651                        return;
652                }
653
654                List<XMLEvent> events = XmlUtil.parse(theDt.getValue());
655                boolean firstElement = true;
656
657                for (XMLEvent event : events) {
658                        switch (event.getEventType()) {
659                                case XMLStreamConstants.ATTRIBUTE:
660                                        Attribute attr = (Attribute) event;
661                                        if (isBlank(attr.getName().getPrefix())) {
662                                                if (isBlank(attr.getName().getNamespaceURI())) {
663                                                        theEventWriter.writeAttribute(attr.getName().getLocalPart(), attr.getValue());
664                                                } else {
665                                                        theEventWriter.writeAttribute(attr.getName().getNamespaceURI(), attr.getName().getLocalPart(), attr.getValue());
666                                                }
667                                        } else {
668                                                theEventWriter.writeAttribute(attr.getName().getPrefix(), attr.getName().getNamespaceURI(), attr.getName().getLocalPart(), attr.getValue());
669                                        }
670
671                                        break;
672                                case XMLStreamConstants.CDATA:
673                                        theEventWriter.writeCData(((Characters) event).getData());
674                                        break;
675                                case XMLStreamConstants.CHARACTERS:
676                                case XMLStreamConstants.SPACE:
677                                        String data = ((Characters) event).getData();
678                                        theEventWriter.writeCharacters(data);
679                                        break;
680                                case XMLStreamConstants.COMMENT:
681                                        theEventWriter.writeComment(((Comment) event).getText());
682                                        break;
683                                case XMLStreamConstants.END_ELEMENT:
684                                        theEventWriter.writeEndElement();
685                                        break;
686                                case XMLStreamConstants.ENTITY_REFERENCE:
687                                        EntityReference er = (EntityReference) event;
688                                        theEventWriter.writeEntityRef(er.getName());
689                                        break;
690                                case XMLStreamConstants.NAMESPACE:
691                                        Namespace ns = (Namespace) event;
692                                        theEventWriter.writeNamespace(ns.getPrefix(), ns.getNamespaceURI());
693                                        break;
694                                case XMLStreamConstants.START_ELEMENT:
695                                        StartElement se = event.asStartElement();
696                                        if (firstElement) {
697                                                if (StringUtils.isBlank(se.getName().getPrefix())) {
698                                                        String namespaceURI = se.getName().getNamespaceURI();
699                                                        if (StringUtils.isBlank(namespaceURI)) {
700                                                                namespaceURI = "http://www.w3.org/1999/xhtml";
701                                                        }
702                                                        theEventWriter.writeStartElement(se.getName().getLocalPart());
703                                                        theEventWriter.writeDefaultNamespace(namespaceURI);
704                                                } else {
705                                                        String prefix = se.getName().getPrefix();
706                                                        String namespaceURI = se.getName().getNamespaceURI();
707                                                        theEventWriter.writeStartElement(prefix, se.getName().getLocalPart(), namespaceURI);
708                                                        theEventWriter.writeNamespace(prefix, namespaceURI);
709                                                }
710                                                firstElement = false;
711                                        } else {
712                                                if (isBlank(se.getName().getPrefix())) {
713                                                        if (isBlank(se.getName().getNamespaceURI())) {
714                                                                theEventWriter.writeStartElement(se.getName().getLocalPart());
715                                                        } else {
716                                                                if (StringUtils.isBlank(se.getName().getPrefix())) {
717                                                                        theEventWriter.writeStartElement(se.getName().getLocalPart());
718                                                                        // theEventWriter.writeDefaultNamespace(se.getName().getNamespaceURI());
719                                                                } else {
720                                                                        theEventWriter.writeStartElement(se.getName().getNamespaceURI(), se.getName().getLocalPart());
721                                                                }
722                                                        }
723                                                } else {
724                                                        theEventWriter.writeStartElement(se.getName().getPrefix(), se.getName().getLocalPart(), se.getName().getNamespaceURI());
725                                                }
726                                                for (Iterator<?> attrIter = se.getAttributes(); attrIter.hasNext(); ) {
727                                                        Attribute next = (Attribute) attrIter.next();
728                                                        theEventWriter.writeAttribute(next.getName().getLocalPart(), next.getValue());
729                                                }
730                                        }
731                                        break;
732                                case XMLStreamConstants.DTD:
733                                case XMLStreamConstants.END_DOCUMENT:
734                                case XMLStreamConstants.ENTITY_DECLARATION:
735                                case XMLStreamConstants.NOTATION_DECLARATION:
736                                case XMLStreamConstants.PROCESSING_INSTRUCTION:
737                                case XMLStreamConstants.START_DOCUMENT:
738                                        break;
739                        }
740
741                }
742        }
743
744        @Override
745        public EncodingEnum getEncoding() {
746                return EncodingEnum.XML;
747        }
748
749        private <T extends IBaseResource> T parseResource(Class<T> theResourceType, XMLEventReader theStreamReader) {
750                ParserState<T> parserState = ParserState.getPreResourceInstance(this, theResourceType, myContext, false, getErrorHandler());
751                return doXmlLoop(theStreamReader, parserState);
752        }
753
754        @Override
755        public IParser setPrettyPrint(boolean thePrettyPrint) {
756                myPrettyPrint = thePrettyPrint;
757                return this;
758        }
759
760        /**
761         * This is just to work around the fact that casting java.util.List<ca.uhn.fhir.model.api.ExtensionDt> to
762         * java.util.List<? extends org.hl7.fhir.instance.model.api.IBaseExtension<?, ?>> seems to be
763         * rejected by the compiler some of the time.
764         */
765        private <Q extends IBaseExtension<?, ?>> List<IBaseExtension<?, ?>> toBaseExtensionList(final List<Q> theList) {
766                List<IBaseExtension<?, ?>> retVal = new ArrayList<IBaseExtension<?, ?>>(theList.size());
767                retVal.addAll(theList);
768                return retVal;
769        }
770
771        private void writeCommentsPost(XMLStreamWriter theEventWriter, IBase theElement) throws XMLStreamException {
772                if (theElement != null && theElement.hasFormatComment()) {
773                        for (String next : theElement.getFormatCommentsPost()) {
774                                if (isNotBlank(next)) {
775                                        theEventWriter.writeComment(next);
776                                }
777                        }
778                }
779        }
780
781        private void writeCommentsPre(XMLStreamWriter theEventWriter, IBase theElement) throws XMLStreamException {
782                if (theElement != null && theElement.hasFormatComment()) {
783                        for (String next : theElement.getFormatCommentsPre()) {
784                                if (isNotBlank(next)) {
785                                        theEventWriter.writeComment(next);
786                                }
787                        }
788                }
789        }
790
791        private void writeOptionalTagWithValue(XMLStreamWriter theEventWriter, String theName, String theValue) throws XMLStreamException {
792                if (StringUtils.isNotBlank(theValue)) {
793                        theEventWriter.writeStartElement(theName);
794                        theEventWriter.writeAttribute("value", theValue);
795                        theEventWriter.writeEndElement();
796                }
797        }
798
799}