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