001package ca.uhn.fhir.context;
002
003import static org.apache.commons.lang3.StringUtils.isNotBlank;
004
005import java.lang.reflect.Field;
006import java.lang.reflect.Modifier;
007
008/*
009 * #%L
010 * HAPI FHIR - Core Library
011 * %%
012 * Copyright (C) 2014 - 2020 University Health Network
013 * %%
014 * Licensed under the Apache License, Version 2.0 (the "License");
015 * you may not use this file except in compliance with the License.
016 * You may obtain a copy of the License at
017 *
018 *      http://www.apache.org/licenses/LICENSE-2.0
019 *
020 * Unless required by applicable law or agreed to in writing, software
021 * distributed under the License is distributed on an "AS IS" BASIS,
022 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
023 * See the License for the specific language governing permissions and
024 * limitations under the License.
025 * #L%
026 */
027
028import java.util.ArrayList;
029import java.util.Collections;
030import java.util.HashMap;
031import java.util.HashSet;
032import java.util.LinkedList;
033import java.util.List;
034import java.util.ListIterator;
035import java.util.Map;
036import java.util.Map.Entry;
037import java.util.Set;
038import java.util.TreeMap;
039import java.util.TreeSet;
040
041import org.hl7.fhir.instance.model.api.IAnyResource;
042import org.hl7.fhir.instance.model.api.IBase;
043import org.hl7.fhir.instance.model.api.IBaseBackboneElement;
044import org.hl7.fhir.instance.model.api.IBaseDatatype;
045import org.hl7.fhir.instance.model.api.IBaseDatatypeElement;
046import org.hl7.fhir.instance.model.api.IBaseEnumeration;
047import org.hl7.fhir.instance.model.api.IBaseExtension;
048import org.hl7.fhir.instance.model.api.IBaseReference;
049import org.hl7.fhir.instance.model.api.IBaseResource;
050import org.hl7.fhir.instance.model.api.ICompositeType;
051import org.hl7.fhir.instance.model.api.INarrative;
052import org.hl7.fhir.instance.model.api.IPrimitiveType;
053
054import ca.uhn.fhir.model.api.IBoundCodeableConcept;
055import ca.uhn.fhir.model.api.IDatatype;
056import ca.uhn.fhir.model.api.IElement;
057import ca.uhn.fhir.model.api.IResource;
058import ca.uhn.fhir.model.api.IResourceBlock;
059import ca.uhn.fhir.model.api.IValueSetEnumBinder;
060import ca.uhn.fhir.model.api.annotation.Binding;
061import ca.uhn.fhir.model.api.annotation.Child;
062import ca.uhn.fhir.model.api.annotation.ChildOrder;
063import ca.uhn.fhir.model.api.annotation.Description;
064import ca.uhn.fhir.model.api.annotation.Extension;
065import ca.uhn.fhir.model.base.composite.BaseContainedDt;
066import ca.uhn.fhir.model.base.composite.BaseNarrativeDt;
067import ca.uhn.fhir.model.base.composite.BaseResourceReferenceDt;
068import ca.uhn.fhir.model.primitive.BoundCodeDt;
069import ca.uhn.fhir.parser.DataFormatException;
070import ca.uhn.fhir.util.ReflectionUtil;
071
072public abstract class BaseRuntimeElementCompositeDefinition<T extends IBase> extends BaseRuntimeElementDefinition<T> {
073
074        private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(BaseRuntimeElementCompositeDefinition.class);
075        private Map<String, Integer> forcedOrder = null;
076        private List<BaseRuntimeChildDefinition> myChildren = new ArrayList<>();
077        private List<BaseRuntimeChildDefinition> myChildrenAndExtensions;
078        private Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> myClassToElementDefinitions;
079        private final FhirContext myContext;
080        private Map<String, BaseRuntimeChildDefinition> myNameToChild = new HashMap<>();
081        private List<ScannedField> myScannedFields = new ArrayList<>();
082        private volatile boolean mySealed;
083
084        @SuppressWarnings("unchecked")
085        public BaseRuntimeElementCompositeDefinition(String theName, Class<? extends T> theImplementingClass, boolean theStandardType, FhirContext theContext, Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> theClassToElementDefinitions) {
086                super(theName, theImplementingClass, theStandardType);
087                
088                myContext = theContext;
089                myClassToElementDefinitions = theClassToElementDefinitions;
090                
091                /*
092                 * We scan classes for annotated fields in the class but also all of its superclasses
093                 */
094                Class<? extends IBase> current = theImplementingClass;
095                LinkedList<Class<? extends IBase>> classes = new LinkedList<>();
096                do {
097                        if (forcedOrder == null) {
098                                ChildOrder childOrder = current.getAnnotation(ChildOrder.class);
099                                if (childOrder != null) {
100                                        forcedOrder = new HashMap<>();
101                                        for (int i = 0; i < childOrder.names().length; i++) {
102                                                String nextName = childOrder.names()[i];
103                                                if (nextName.endsWith("[x]")) {
104                                                        nextName = nextName.substring(0, nextName.length() - 3);
105                                                }
106                                                forcedOrder.put(nextName, i);
107                                        }
108                                }
109                        }
110                        classes .push(current);
111                        if (IBase.class.isAssignableFrom(current.getSuperclass())) {
112                                current = (Class<? extends IBase>) current.getSuperclass();
113                        } else {
114                                current = null;
115                        }
116                } while (current != null);
117
118                Set<Field> fields = new HashSet<>();
119                for (Class<? extends IBase> nextClass : classes) {
120                        int fieldIndexInClass = 0;
121                        for (Field next : nextClass.getDeclaredFields()) {
122                                if (fields.add(next)) {
123                                        ScannedField scannedField = new ScannedField(next, theImplementingClass, fieldIndexInClass == 0);
124                                        if (scannedField.getChildAnnotation() != null) {
125                                                myScannedFields.add(scannedField);
126                                                fieldIndexInClass++;
127                                        }
128                                }
129                        }
130                }
131
132        }
133
134        void addChild(BaseRuntimeChildDefinition theNext) {
135                if (theNext == null) {
136                        throw new NullPointerException();
137                }
138                if (theNext.getExtensionUrl() != null) {
139                        throw new IllegalArgumentException("Shouldn't haven an extension URL, use addExtension instead");
140                }
141                myChildren.add(theNext);
142        }
143
144        @Override
145        public BaseRuntimeChildDefinition getChildByName(String theName){
146                validateSealed();
147                return myNameToChild.get(theName);
148        }
149
150        public BaseRuntimeChildDefinition getChildByNameOrThrowDataFormatException(String theName) throws DataFormatException {
151                validateSealed();
152                BaseRuntimeChildDefinition retVal = myNameToChild.get(theName);
153                if (retVal == null) {
154                        throw new DataFormatException("Unknown child name '" + theName + "' in element " + getName() + " - Valid names are: " + new TreeSet<String>(myNameToChild.keySet()));
155                }
156                return retVal;
157        }
158
159        @Override
160        public List<BaseRuntimeChildDefinition> getChildren() {
161                validateSealed();
162                return myChildren;
163        }
164        
165        
166        public List<BaseRuntimeChildDefinition> getChildrenAndExtension() {
167                validateSealed();
168                return myChildrenAndExtensions;
169        }
170
171
172        /**
173         * Has this class been sealed
174         */
175        public boolean isSealed() {
176                return mySealed;
177        }
178
179        @SuppressWarnings("unchecked")
180        void populateScanAlso(Set<Class<? extends IBase>> theScanAlso) {
181                for (ScannedField next : myScannedFields) {
182                        if (IBase.class.isAssignableFrom(next.getElementType())) {
183                                if (next.getElementType().isInterface() == false && Modifier.isAbstract(next.getElementType().getModifiers()) == false) {
184                                        theScanAlso.add((Class<? extends IBase>) next.getElementType());
185                                }
186                        }
187                        for (Class<? extends IBase> nextChildType : next.getChoiceTypes()) {
188                                if (nextChildType.isInterface() == false && Modifier.isAbstract(nextChildType.getModifiers()) == false) {
189                                        theScanAlso.add(nextChildType);
190                                }
191                        }
192                }
193        }
194        
195        private void scanCompositeElementForChildren() {
196                Set<String> elementNames = new HashSet<>();
197                TreeMap<Integer, BaseRuntimeDeclaredChildDefinition> orderToElementDef = new TreeMap<>();
198                TreeMap<Integer, BaseRuntimeDeclaredChildDefinition> orderToExtensionDef = new TreeMap<>();
199
200                scanCompositeElementForChildren(elementNames, orderToElementDef, orderToExtensionDef);
201
202                if (forcedOrder != null) {
203                        /* 
204                         * Find out how many elements don't match any entry in the list
205                         * for forced order. Those elements come first.
206                         */
207                        TreeMap<Integer, BaseRuntimeDeclaredChildDefinition> newOrderToExtensionDef = new TreeMap<>();
208                        int unknownCount = 0;
209                        for (BaseRuntimeDeclaredChildDefinition nextEntry : orderToElementDef.values()) {
210                                if (!forcedOrder.containsKey(nextEntry.getElementName())) {
211                                        newOrderToExtensionDef.put(unknownCount, nextEntry);
212                                        unknownCount++;
213                                }
214                        }
215                        for (BaseRuntimeDeclaredChildDefinition nextEntry : orderToElementDef.values()) {
216                                if (forcedOrder.containsKey(nextEntry.getElementName())) {
217                                        Integer newOrder = forcedOrder.get(nextEntry.getElementName());
218                                        newOrderToExtensionDef.put(newOrder + unknownCount, nextEntry);
219                                }
220                        }
221                        orderToElementDef = newOrderToExtensionDef;
222                }
223                
224                TreeSet<Integer> orders = new TreeSet<>();
225                orders.addAll(orderToElementDef.keySet());
226                orders.addAll(orderToExtensionDef.keySet());
227
228                for (Integer i : orders) {
229                        BaseRuntimeChildDefinition nextChild = orderToElementDef.get(i);
230                        if (nextChild != null) {
231                                this.addChild(nextChild);
232                        }
233                        BaseRuntimeDeclaredChildDefinition nextExt = orderToExtensionDef.get(i);
234                        if (nextExt != null) {
235                                this.addExtension((RuntimeChildDeclaredExtensionDefinition) nextExt);
236                        }
237                }
238
239        }
240        
241        @SuppressWarnings("unchecked")
242        private void scanCompositeElementForChildren(Set<String> elementNames, TreeMap<Integer, BaseRuntimeDeclaredChildDefinition> theOrderToElementDef,
243                        TreeMap<Integer, BaseRuntimeDeclaredChildDefinition> theOrderToExtensionDef) {
244                int baseElementOrder = 0; 
245
246                for (ScannedField next : myScannedFields) {
247                        if (next.isFirstFieldInNewClass()) {
248                                baseElementOrder = theOrderToElementDef.isEmpty() ? 0 : theOrderToElementDef.lastEntry().getKey() + 1;
249                        }
250                        
251                        Class<?> declaringClass = next.getField().getDeclaringClass(); 
252
253                        Description descriptionAnnotation = ModelScanner.pullAnnotation(next.getField(), Description.class);
254
255                        TreeMap<Integer, BaseRuntimeDeclaredChildDefinition> orderMap = theOrderToElementDef;
256                        Extension extensionAttr = ModelScanner.pullAnnotation(next.getField(), Extension.class);
257                        if (extensionAttr != null) {
258                                orderMap = theOrderToExtensionDef;
259                        }
260
261                        Child childAnnotation = next.getChildAnnotation();
262                        Field nextField = next.getField();
263                        String elementName = childAnnotation.name();
264                        int order = childAnnotation.order();
265                        boolean childIsChoiceType = false;
266                        boolean orderIsReplaceParent = false;
267                        BaseRuntimeChildDefinition replacedParent = null;
268                        
269                        if (order == Child.REPLACE_PARENT) {
270                                
271                                if (extensionAttr != null) {
272
273                                        for (Entry<Integer, BaseRuntimeDeclaredChildDefinition> nextEntry : orderMap.entrySet()) {
274                                                BaseRuntimeDeclaredChildDefinition nextDef = nextEntry.getValue();
275                                                if (nextDef instanceof RuntimeChildDeclaredExtensionDefinition) {
276                                                        if (nextDef.getExtensionUrl().equals(extensionAttr.url())) {
277                                                                orderIsReplaceParent = true;
278                                                                order = nextEntry.getKey();
279                                                                replacedParent = orderMap.remove(nextEntry.getKey());
280                                                                elementNames.remove(elementName);
281                                                                break;
282                                                        }
283                                                }
284                                        }
285                                        if (order == Child.REPLACE_PARENT) {
286                                                throw new ConfigurationException("Field " + nextField.getName() + "' on target type " + declaringClass.getSimpleName() + " has order() of REPLACE_PARENT (" + Child.REPLACE_PARENT
287                                                                + ") but no parent element with extension URL " + extensionAttr.url() + " could be found on type " + nextField.getDeclaringClass().getSimpleName());
288                                        }
289
290                                } else {
291
292                                        for (Entry<Integer, BaseRuntimeDeclaredChildDefinition> nextEntry : orderMap.entrySet()) {
293                                                BaseRuntimeDeclaredChildDefinition nextDef = nextEntry.getValue();
294                                                if (elementName.equals(nextDef.getElementName())) {
295                                                        orderIsReplaceParent = true;
296                                                        order = nextEntry.getKey();
297                                                        BaseRuntimeDeclaredChildDefinition existing = orderMap.remove(nextEntry.getKey());
298                                                        replacedParent = existing;
299                                                        elementNames.remove(elementName);
300                                                        
301                                                        /*
302                                                         * See #350 - If the original field (in the superclass) with the given name is a choice, then we need to make sure
303                                                         * that the field which replaces is a choice even if it's only a choice of one type - this is because the
304                                                         * element name when serialized still needs to reflect the datatype
305                                                         */
306                                                        if (existing instanceof RuntimeChildChoiceDefinition) {
307                                                                childIsChoiceType = true;
308                                                        }
309                                                        break;
310                                                }
311                                        }
312                                        if (order == Child.REPLACE_PARENT) {
313                                                throw new ConfigurationException("Field " + nextField.getName() + "' on target type " + declaringClass.getSimpleName() + " has order() of REPLACE_PARENT (" + Child.REPLACE_PARENT
314                                                                + ") but no parent element with name " + elementName + " could be found on type " + nextField.getDeclaringClass().getSimpleName());
315                                        }
316
317                                }
318
319                        }
320                        
321                        if (order < 0 && order != Child.ORDER_UNKNOWN) {
322                                throw new ConfigurationException("Invalid order '" + order + "' on @Child for field '" + nextField.getName() + "' on target type: " + declaringClass);
323                        }
324                        
325                        if (order != Child.ORDER_UNKNOWN && !orderIsReplaceParent) {
326                                order = order + baseElementOrder;
327                        }
328                        // int min = childAnnotation.min();
329                        // int max = childAnnotation.max();
330
331                        /*
332                         * Anything that's marked as unknown is given a new ID that is <0 so that it doesn't conflict with any given IDs and can be figured out later
333                         */
334                        if (order == Child.ORDER_UNKNOWN) {
335                                order = 0;
336                                while (orderMap.containsKey(order)) {
337                                        order++;
338                                }
339                        }
340
341                        List<Class<? extends IBase>> choiceTypes = next.getChoiceTypes();
342                        
343                        if (orderMap.containsKey(order)) {
344                                throw new ConfigurationException("Detected duplicate field order '" + childAnnotation.order() + "' for element named '" + elementName + "' in type '" + declaringClass.getCanonicalName() + "' - Already had: " + orderMap.get(order).getElementName());
345                        }
346
347                        if (elementNames.contains(elementName)) {
348                                throw new ConfigurationException("Detected duplicate field name '" + elementName + "' in type '" + declaringClass.getCanonicalName() + "'");
349                        }
350
351                        Class<?> nextElementType = next.getElementType();
352
353                        BaseRuntimeDeclaredChildDefinition def;
354                        if (childAnnotation.name().equals("extension") && IBaseExtension.class.isAssignableFrom(nextElementType)) {
355                                def = new RuntimeChildExtension(nextField, childAnnotation.name(), childAnnotation, descriptionAnnotation);
356                        } else if (childAnnotation.name().equals("modifierExtension") && IBaseExtension.class.isAssignableFrom(nextElementType)) {
357                                def = new RuntimeChildExtension(nextField, childAnnotation.name(), childAnnotation, descriptionAnnotation);
358                        } else if (BaseContainedDt.class.isAssignableFrom(nextElementType) || (childAnnotation.name().equals("contained") && IBaseResource.class.isAssignableFrom(nextElementType))) {
359                                /*
360                                 * Child is contained resources
361                                 */
362                                def = new RuntimeChildContainedResources(nextField, childAnnotation, descriptionAnnotation, elementName);
363                        } else if (IAnyResource.class.isAssignableFrom(nextElementType) || IResource.class.equals(nextElementType)) {
364                                /*
365                                 * Child is a resource as a direct child, as in Bundle.entry.resource
366                                 */
367                                def = new RuntimeChildDirectResource(nextField, childAnnotation, descriptionAnnotation, elementName);
368                        } else {
369                                childIsChoiceType |= choiceTypes.size() > 1;
370                                if (extensionAttr == null && childIsChoiceType && !BaseResourceReferenceDt.class.isAssignableFrom(nextElementType) && !IBaseReference.class.isAssignableFrom(nextElementType)) {
371                                        def = new RuntimeChildChoiceDefinition(nextField, elementName, childAnnotation, descriptionAnnotation, choiceTypes);
372                                } else if (extensionAttr != null) {
373                                        /*
374                                         * Child is an extension
375                                         */
376                                        Class<? extends IBase> et = (Class<? extends IBase>) nextElementType;
377
378                                        Object binder = null;
379                                        if (BoundCodeDt.class.isAssignableFrom(nextElementType) || IBoundCodeableConcept.class.isAssignableFrom(nextElementType)) {
380                                                binder = ModelScanner.getBoundCodeBinder(nextField);
381                                        }
382
383                                        def = new RuntimeChildDeclaredExtensionDefinition(nextField, childAnnotation, descriptionAnnotation, extensionAttr, elementName, extensionAttr.url(), et,                                                       binder);
384
385                                        if (IBaseEnumeration.class.isAssignableFrom(nextElementType)) {
386                                                ((RuntimeChildDeclaredExtensionDefinition)def).setEnumerationType(ReflectionUtil.getGenericCollectionTypeOfFieldWithSecondOrderForList(nextField));
387                                        }
388                                } else if (BaseResourceReferenceDt.class.isAssignableFrom(nextElementType) || IBaseReference.class.isAssignableFrom(nextElementType)) {
389                                        /*
390                                         * Child is a resource reference
391                                         */
392                                        List<Class<? extends IBaseResource>> refTypesList = new ArrayList<>();
393                                        for (Class<? extends IElement> nextType : childAnnotation.type()) {
394                                                if (IBaseReference.class.isAssignableFrom(nextType)) {
395                                                        refTypesList.add(myContext.getVersion().getVersion().isRi() ? IAnyResource.class : IResource.class);
396                                                        continue;
397                                                } else if (IBaseResource.class.isAssignableFrom(nextType) == false) {
398                                                        throw new ConfigurationException("Field '" + nextField.getName() + "' in class '" + nextField.getDeclaringClass().getCanonicalName() + "' is of type " + BaseResourceReferenceDt.class + " but contains a non-resource type: " + nextType.getCanonicalName());
399                                                }
400                                                refTypesList.add((Class<? extends IBaseResource>) nextType);
401                                        }
402                                        def = new RuntimeChildResourceDefinition(nextField, elementName, childAnnotation, descriptionAnnotation, refTypesList);
403
404                                } else if (IResourceBlock.class.isAssignableFrom(nextElementType) || IBaseBackboneElement.class.isAssignableFrom(nextElementType)
405                                                || IBaseDatatypeElement.class.isAssignableFrom(nextElementType)) {
406                                        /*
407                                         * Child is a resource block (i.e. a sub-tag within a resource) TODO: do these have a better name according to HL7?
408                                         */
409
410                                        Class<? extends IBase> blockDef = (Class<? extends IBase>) nextElementType;
411                                        def = new RuntimeChildResourceBlockDefinition(myContext, nextField, childAnnotation, descriptionAnnotation, elementName, blockDef);
412                                } else if (IDatatype.class.equals(nextElementType) || IElement.class.equals(nextElementType) || "Type".equals(nextElementType.getSimpleName())
413                                                || IBaseDatatype.class.equals(nextElementType)) {
414
415                                        def = new RuntimeChildAny(nextField, elementName, childAnnotation, descriptionAnnotation);
416                                } else if (IDatatype.class.isAssignableFrom(nextElementType) || IPrimitiveType.class.isAssignableFrom(nextElementType) || ICompositeType.class.isAssignableFrom(nextElementType)
417                                                || IBaseDatatype.class.isAssignableFrom(nextElementType) || IBaseExtension.class.isAssignableFrom(nextElementType)) {
418                                        Class<? extends IBase> nextDatatype = (Class<? extends IBase>) nextElementType;
419
420                                        if (IPrimitiveType.class.isAssignableFrom(nextElementType)) {
421                                                if (nextElementType.equals(BoundCodeDt.class)) {
422                                                        IValueSetEnumBinder<Enum<?>> binder = ModelScanner.getBoundCodeBinder(nextField);
423                                                        Class<? extends Enum<?>> enumType = ModelScanner.determineEnumTypeForBoundField(nextField);
424                                                        def = new RuntimeChildPrimitiveBoundCodeDatatypeDefinition(nextField, elementName, childAnnotation, descriptionAnnotation, nextDatatype, binder, enumType);
425                                                } else if (IBaseEnumeration.class.isAssignableFrom(nextElementType)) {
426                                                        Class<? extends Enum<?>> binderType = ModelScanner.determineEnumTypeForBoundField(nextField);
427                                                        def = new RuntimeChildPrimitiveEnumerationDatatypeDefinition(nextField, elementName, childAnnotation, descriptionAnnotation, nextDatatype, binderType);
428                                                } else {
429                                                        def = new RuntimeChildPrimitiveDatatypeDefinition(nextField, elementName, descriptionAnnotation, childAnnotation, nextDatatype);
430                                                }
431                                        } else {
432                                                if (IBoundCodeableConcept.class.isAssignableFrom(nextElementType)) {
433                                                        IValueSetEnumBinder<Enum<?>> binder = ModelScanner.getBoundCodeBinder(nextField);
434                                                        Class<? extends Enum<?>> enumType = ModelScanner.determineEnumTypeForBoundField(nextField);
435                                                        def = new RuntimeChildCompositeBoundDatatypeDefinition(nextField, elementName, childAnnotation, descriptionAnnotation, nextDatatype, binder, enumType);
436                                                } else if (BaseNarrativeDt.class.isAssignableFrom(nextElementType) || INarrative.class.isAssignableFrom(nextElementType)) {
437                                                        def = new RuntimeChildNarrativeDefinition(nextField, elementName, childAnnotation, descriptionAnnotation, nextDatatype);
438                                                } else {
439                                                        def = new RuntimeChildCompositeDatatypeDefinition(nextField, elementName, childAnnotation, descriptionAnnotation, nextDatatype);
440                                                }
441                                        }
442
443                                } else {
444                                        throw new ConfigurationException("Field '" + elementName + "' in type '" + declaringClass.getCanonicalName() + "' is not a valid child type: " + nextElementType);
445                                }
446
447                                Binding bindingAnnotation = ModelScanner.pullAnnotation(nextField, Binding.class);
448                                if (bindingAnnotation != null) {
449                                        if (isNotBlank(bindingAnnotation.valueSet())) {
450                                                def.setBindingValueSet(bindingAnnotation.valueSet());
451                                        }
452                                }
453                                
454                        }
455
456                        def.setReplacedParentDefinition(replacedParent);
457                        orderMap.put(order, def);
458                        elementNames.add(elementName);
459                }
460        }
461        @Override 
462        void sealAndInitialize(FhirContext theContext, Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> theClassToElementDefinitions) {
463                if (mySealed) {
464                        return;
465                }
466                mySealed = true;
467
468                scanCompositeElementForChildren();
469                
470                super.sealAndInitialize(theContext, theClassToElementDefinitions);
471
472                for (BaseRuntimeChildDefinition next : myChildren) {
473                        next.sealAndInitialize(theContext, theClassToElementDefinitions);
474                }
475
476                myNameToChild = new HashMap<>();
477                for (BaseRuntimeChildDefinition next : myChildren) {    
478                        if (next instanceof RuntimeChildChoiceDefinition) {
479                                String key = next.getElementName()+"[x]";
480                                myNameToChild.put(key, next);
481                        }
482                        for (String nextName : next.getValidChildNames()) {
483                                if (myNameToChild.containsKey(nextName)) {
484                                        throw new ConfigurationException("Duplicate child name[" + nextName + "] in Element[" + getName() + "]");
485                                }
486                                myNameToChild.put(nextName, next);
487                        }
488                }
489
490                myChildren = Collections.unmodifiableList(myChildren);
491                myNameToChild = Collections.unmodifiableMap(myNameToChild);
492                
493                List<BaseRuntimeChildDefinition> children = new ArrayList<>();
494                children.addAll(myChildren);
495                
496                /*
497                 * Because of the way the type hierarchy works for DSTU2 resources,
498                 * things end up in the wrong order
499                 */
500                if (theContext.getVersion().getVersion() == FhirVersionEnum.DSTU2) {
501                        int extIndex = findIndex(children, "extension", false);
502                        int containedIndex = findIndex(children, "contained", false);
503                        if (containedIndex != -1 && extIndex != -1 && extIndex < containedIndex) {
504                                BaseRuntimeChildDefinition extension = children.remove(extIndex);
505                                if (containedIndex > children.size()) {
506                                        children.add(extension);
507                                } else {
508                                        children.add(containedIndex, extension);
509                                }
510                                int modIndex = findIndex(children, "modifierExtension", false);
511                                if (modIndex < containedIndex) {
512                                        extension = children.remove(modIndex);
513                                        if (containedIndex > children.size()) {
514                                                children.add(extension);
515                                        } else {
516                                                children.add(containedIndex, extension);
517                                        }
518                                }
519                        }
520                }
521                
522                /*
523                 * Add declared extensions alongside the undeclared ones
524                 */
525                if (getExtensionsNonModifier().isEmpty() == false) {
526                        children.addAll(findIndex(children, "extension", true), getExtensionsNonModifier());
527                }
528                if (getExtensionsModifier().isEmpty() == false) {
529                        children.addAll(findIndex(children, "modifierExtension", true), getExtensionsModifier());
530                }
531                
532                myChildrenAndExtensions=Collections.unmodifiableList(children);
533        }
534
535        
536        @Override
537        protected void validateSealed() {
538                if (!mySealed) {
539                        synchronized(myContext) {
540                                if(!mySealed) {
541                                        sealAndInitialize(myContext, myClassToElementDefinitions);
542                                }
543                        }
544                }
545        }
546
547        private static int findIndex(List<BaseRuntimeChildDefinition> theChildren, String theName, boolean theDefaultAtEnd) {
548                int index = theDefaultAtEnd ? theChildren.size() : -1;
549                for (ListIterator<BaseRuntimeChildDefinition> iter = theChildren.listIterator(); iter.hasNext(); ) {
550                        if (iter.next().getElementName().equals(theName)) {
551                                index = iter.previousIndex();
552                                break;
553                        }
554                }
555                return index;
556        }
557
558        private static class ScannedField {
559                private Child myChildAnnotation;
560
561                private List<Class<? extends IBase>> myChoiceTypes = new ArrayList<>();
562                private Class<?> myElementType;
563                private Field myField;
564                private boolean myFirstFieldInNewClass;
565                ScannedField(Field theField, Class<?> theClass, boolean theFirstFieldInNewClass) {
566                        myField = theField;
567                        myFirstFieldInNewClass = theFirstFieldInNewClass;
568
569                        Child childAnnotation = ModelScanner.pullAnnotation(theField, Child.class);
570                        if (childAnnotation == null) {
571                                ourLog.trace("Ignoring non @Child field {} on target type {}", theField.getName(), theClass);
572                                return;
573                        }
574                        if (Modifier.isFinal(theField.getModifiers())) {
575                                ourLog.trace("Ignoring constant {} on target type {}", theField.getName(), theClass);
576                                return;
577                        }
578                        
579                        myChildAnnotation = childAnnotation;
580                        myElementType = ModelScanner.determineElementType(theField);
581
582                        Collections.addAll(myChoiceTypes, childAnnotation.type());
583                }
584                
585                public Child getChildAnnotation() {
586                        return myChildAnnotation;
587                }
588
589                public List<Class<? extends IBase>> getChoiceTypes() {
590                        return myChoiceTypes;
591                }
592
593                public Class<?> getElementType() {
594                        return myElementType;
595                }
596
597                public Field getField() {
598                        return myField;
599                }
600
601                public boolean isFirstFieldInNewClass() {
602                        return myFirstFieldInNewClass;
603                }
604        }
605
606}