001package ca.uhn.fhir.context;
002
003import ca.uhn.fhir.context.api.AddProfileTagEnum;
004import ca.uhn.fhir.context.support.DefaultProfileValidationSupport;
005import ca.uhn.fhir.context.support.IValidationSupport;
006import ca.uhn.fhir.fhirpath.IFhirPath;
007import ca.uhn.fhir.i18n.HapiLocalizer;
008import ca.uhn.fhir.model.api.IElement;
009import ca.uhn.fhir.model.api.IFhirVersion;
010import ca.uhn.fhir.model.api.IResource;
011import ca.uhn.fhir.model.view.ViewGenerator;
012import ca.uhn.fhir.narrative.INarrativeGenerator;
013import ca.uhn.fhir.parser.DataFormatException;
014import ca.uhn.fhir.parser.IParser;
015import ca.uhn.fhir.parser.IParserErrorHandler;
016import ca.uhn.fhir.parser.JsonParser;
017import ca.uhn.fhir.parser.LenientErrorHandler;
018import ca.uhn.fhir.parser.RDFParser;
019import ca.uhn.fhir.parser.XmlParser;
020import ca.uhn.fhir.rest.api.IVersionSpecificBundleFactory;
021import ca.uhn.fhir.rest.client.api.IBasicClient;
022import ca.uhn.fhir.rest.client.api.IGenericClient;
023import ca.uhn.fhir.rest.client.api.IRestfulClient;
024import ca.uhn.fhir.rest.client.api.IRestfulClientFactory;
025import ca.uhn.fhir.util.FhirTerser;
026import ca.uhn.fhir.util.ReflectionUtil;
027import ca.uhn.fhir.util.VersionUtil;
028import ca.uhn.fhir.validation.FhirValidator;
029import org.apache.commons.lang3.Validate;
030import org.apache.commons.lang3.exception.ExceptionUtils;
031import org.apache.jena.riot.Lang;
032import org.hl7.fhir.instance.model.api.IBase;
033import org.hl7.fhir.instance.model.api.IBaseBundle;
034import org.hl7.fhir.instance.model.api.IBaseResource;
035
036import javax.annotation.Nullable;
037import java.io.IOException;
038import java.lang.reflect.Method;
039import java.lang.reflect.Modifier;
040import java.util.ArrayList;
041import java.util.Arrays;
042import java.util.Collection;
043import java.util.Collections;
044import java.util.EnumMap;
045import java.util.Enumeration;
046import java.util.HashMap;
047import java.util.HashSet;
048import java.util.List;
049import java.util.Map;
050import java.util.Map.Entry;
051import java.util.Properties;
052import java.util.Set;
053
054/*
055 * #%L
056 * HAPI FHIR - Core Library
057 * %%
058 * Copyright (C) 2014 - 2020 University Health Network
059 * %%
060 * Licensed under the Apache License, Version 2.0 (the "License");
061 * you may not use this file except in compliance with the License.
062 * You may obtain a copy of the License at
063 *
064 * http://www.apache.org/licenses/LICENSE-2.0
065 *
066 * Unless required by applicable law or agreed to in writing, software
067 * distributed under the License is distributed on an "AS IS" BASIS,
068 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
069 * See the License for the specific language governing permissions and
070 * limitations under the License.
071 * #L%
072 */
073
074/**
075 * The FHIR context is the central starting point for the use of the HAPI FHIR API. It should be created once, and then
076 * used as a factory for various other types of objects (parsers, clients, etc.).
077 *
078 * <p>
079 * Important usage notes:
080 * </p>
081 * <ul>
082 * <li>
083 * Thread safety: <b>This class is thread safe</b> and may be shared between multiple processing
084 * threads, except for the {@link #registerCustomType} and {@link #registerCustomTypes} methods.
085 * </li>
086 * <li>
087 * Performance: <b>This class is expensive</b> to create, as it scans every resource class it needs to parse or encode
088 * to build up an internal model of those classes. For that reason, you should try to create one FhirContext instance
089 * which remains for the life of your application and reuse that instance. Note that it will not cause problems to
090 * create multiple instances (ie. resources originating from one FhirContext may be passed to parsers originating from
091 * another) but you will incur a performance penalty if a new FhirContext is created for every message you parse/encode.
092 * </li>
093 * </ul>
094 */
095public class FhirContext {
096
097        private static final List<Class<? extends IBaseResource>> EMPTY_LIST = Collections.emptyList();
098        private static final Map<FhirVersionEnum, FhirContext> ourStaticContexts = Collections.synchronizedMap(new EnumMap<>(FhirVersionEnum.class));
099        private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(FhirContext.class);
100        private final IFhirVersion myVersion;
101        private AddProfileTagEnum myAddProfileTagWhenEncoding = AddProfileTagEnum.ONLY_FOR_CUSTOM;
102        private volatile Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> myClassToElementDefinition = Collections.emptyMap();
103        private ArrayList<Class<? extends IBase>> myCustomTypes;
104        private Map<String, Class<? extends IBaseResource>> myDefaultTypeForProfile = new HashMap<>();
105        private volatile Map<String, RuntimeResourceDefinition> myIdToResourceDefinition = Collections.emptyMap();
106        private volatile boolean myInitialized;
107        private volatile boolean myInitializing = false;
108        private HapiLocalizer myLocalizer = new HapiLocalizer();
109        private volatile Map<String, BaseRuntimeElementDefinition<?>> myNameToElementDefinition = Collections.emptyMap();
110        private volatile Map<String, RuntimeResourceDefinition> myNameToResourceDefinition = Collections.emptyMap();
111        private volatile Map<String, Class<? extends IBaseResource>> myNameToResourceType;
112        private volatile INarrativeGenerator myNarrativeGenerator;
113        private volatile IParserErrorHandler myParserErrorHandler = new LenientErrorHandler();
114        private ParserOptions myParserOptions = new ParserOptions();
115        private Set<PerformanceOptionsEnum> myPerformanceOptions = new HashSet<>();
116        private Collection<Class<? extends IBaseResource>> myResourceTypesToScan;
117        private volatile IRestfulClientFactory myRestfulClientFactory;
118        private volatile RuntimeChildUndeclaredExtensionDefinition myRuntimeChildUndeclaredExtensionDefinition;
119        private IValidationSupport myValidationSupport;
120        private Map<FhirVersionEnum, Map<String, Class<? extends IBaseResource>>> myVersionToNameToResourceType = Collections.emptyMap();
121
122        /**
123         * @deprecated It is recommended that you use one of the static initializer methods instead
124         * of this method, e.g. {@link #forDstu2()} or {@link #forDstu3()} or {@link #forR4()}
125         */
126        @Deprecated
127        public FhirContext() {
128                this(EMPTY_LIST);
129        }
130
131        /**
132         * @deprecated It is recommended that you use one of the static initializer methods instead
133         * of this method, e.g. {@link #forDstu2()} or {@link #forDstu3()} or {@link #forR4()}
134         */
135        @Deprecated
136        public FhirContext(final Class<? extends IBaseResource> theResourceType) {
137                this(toCollection(theResourceType));
138        }
139
140        /**
141         * @deprecated It is recommended that you use one of the static initializer methods instead
142         * of this method, e.g. {@link #forDstu2()} or {@link #forDstu3()} or {@link #forR4()}
143         */
144        @Deprecated
145        public FhirContext(final Class<?>... theResourceTypes) {
146                this(toCollection(theResourceTypes));
147        }
148
149        /**
150         * @deprecated It is recommended that you use one of the static initializer methods instead
151         * of this method, e.g. {@link #forDstu2()} or {@link #forDstu3()} or {@link #forR4()}
152         */
153        @Deprecated
154        public FhirContext(final Collection<Class<? extends IBaseResource>> theResourceTypes) {
155                this(null, theResourceTypes);
156        }
157
158        /**
159         * In most cases it is recommended that you use one of the static initializer methods instead
160         * of this method, e.g. {@link #forDstu2()} or {@link #forDstu3()} or {@link #forR4()}, but
161         * this method can also be used if you wish to supply the version programmatically.
162         */
163        public FhirContext(final FhirVersionEnum theVersion) {
164                this(theVersion, null);
165        }
166
167        private FhirContext(final FhirVersionEnum theVersion, final Collection<Class<? extends IBaseResource>> theResourceTypes) {
168                VersionUtil.getVersion();
169
170                if (theVersion != null) {
171                        if (!theVersion.isPresentOnClasspath()) {
172                                throw new IllegalStateException(getLocalizer().getMessage(FhirContext.class, "noStructuresForSpecifiedVersion", theVersion.name()));
173                        }
174                        myVersion = theVersion.getVersionImplementation();
175                } else if (FhirVersionEnum.DSTU2.isPresentOnClasspath()) {
176                        myVersion = FhirVersionEnum.DSTU2.getVersionImplementation();
177                } else if (FhirVersionEnum.DSTU2_HL7ORG.isPresentOnClasspath()) {
178                        myVersion = FhirVersionEnum.DSTU2_HL7ORG.getVersionImplementation();
179                } else if (FhirVersionEnum.DSTU2_1.isPresentOnClasspath()) {
180                        myVersion = FhirVersionEnum.DSTU2_1.getVersionImplementation();
181                } else if (FhirVersionEnum.DSTU3.isPresentOnClasspath()) {
182                        myVersion = FhirVersionEnum.DSTU3.getVersionImplementation();
183                } else if (FhirVersionEnum.R4.isPresentOnClasspath()) {
184                        myVersion = FhirVersionEnum.R4.getVersionImplementation();
185                } else {
186                        throw new IllegalStateException(getLocalizer().getMessage(FhirContext.class, "noStructures"));
187                }
188
189                if (theVersion == null) {
190                        ourLog.info("Creating new FhirContext with auto-detected version [{}]. It is recommended to explicitly select a version for future compatibility by invoking FhirContext.forDstuX()",
191                                myVersion.getVersion().name());
192                } else {
193                        if ("true".equals(System.getProperty("unit_test_mode"))) {
194                                String calledAt = ExceptionUtils.getStackFrames(new Throwable())[4];
195                                ourLog.info("Creating new FHIR context for FHIR version [{}]{}", myVersion.getVersion().name(), calledAt);
196                        } else {
197                                ourLog.info("Creating new FHIR context for FHIR version [{}]", myVersion.getVersion().name());
198                        }
199                }
200
201                myResourceTypesToScan = theResourceTypes;
202
203                /*
204                 * Check if we're running in Android mode and configure the context appropriately if so
205                 */
206                try {
207                        Class<?> clazz = Class.forName("ca.uhn.fhir.android.AndroidMarker");
208                        ourLog.info("Android mode detected, configuring FhirContext for Android operation");
209                        try {
210                                Method method = clazz.getMethod("configureContext", FhirContext.class);
211                                method.invoke(null, this);
212                        } catch (Throwable e) {
213                                ourLog.warn("Failed to configure context for Android operation", e);
214                        }
215                } catch (ClassNotFoundException e) {
216                        ourLog.trace("Android mode not detected");
217                }
218
219        }
220
221        private String createUnknownResourceNameError(final String theResourceName, final FhirVersionEnum theVersion) {
222                return getLocalizer().getMessage(FhirContext.class, "unknownResourceName", theResourceName, theVersion);
223        }
224
225        private void ensureCustomTypeList() {
226                myClassToElementDefinition.clear();
227                if (myCustomTypes == null) {
228                        myCustomTypes = new ArrayList<>();
229                }
230        }
231
232        /**
233         * When encoding resources, this setting configures the parser to include
234         * an entry in the resource's metadata section which indicates which profile(s) the
235         * resource claims to conform to. The default is {@link AddProfileTagEnum#ONLY_FOR_CUSTOM}.
236         *
237         * @see #setAddProfileTagWhenEncoding(AddProfileTagEnum) for more information
238         */
239        public AddProfileTagEnum getAddProfileTagWhenEncoding() {
240                return myAddProfileTagWhenEncoding;
241        }
242
243        /**
244         * When encoding resources, this setting configures the parser to include
245         * an entry in the resource's metadata section which indicates which profile(s) the
246         * resource claims to conform to. The default is {@link AddProfileTagEnum#ONLY_FOR_CUSTOM}.
247         * <p>
248         * This feature is intended for situations where custom resource types are being used,
249         * avoiding the need to manually add profile declarations for these custom types.
250         * </p>
251         * <p>
252         * See <a href="http://jamesagnew.gihhub.io/hapi-fhir/doc_extensions.html">Profiling and Extensions</a>
253         * for more information on using custom types.
254         * </p>
255         * <p>
256         * Note that this feature automatically adds the profile, but leaves any profile tags
257         * which have been manually added in place as well.
258         * </p>
259         *
260         * @param theAddProfileTagWhenEncoding The add profile mode (must not be <code>null</code>)
261         */
262        public void setAddProfileTagWhenEncoding(final AddProfileTagEnum theAddProfileTagWhenEncoding) {
263                Validate.notNull(theAddProfileTagWhenEncoding, "theAddProfileTagWhenEncoding must not be null");
264                myAddProfileTagWhenEncoding = theAddProfileTagWhenEncoding;
265        }
266
267        Collection<RuntimeResourceDefinition> getAllResourceDefinitions() {
268                validateInitialized();
269                return myNameToResourceDefinition.values();
270        }
271
272        /**
273         * Returns the default resource type for the given profile
274         *
275         * @see #setDefaultTypeForProfile(String, Class)
276         */
277        public Class<? extends IBaseResource> getDefaultTypeForProfile(final String theProfile) {
278                validateInitialized();
279                return myDefaultTypeForProfile.get(theProfile);
280        }
281
282        /**
283         * Returns the scanned runtime model for the given type. This is an advanced feature which is generally only needed
284         * for extending the core library.
285         */
286        @SuppressWarnings("unchecked")
287        public BaseRuntimeElementDefinition<?> getElementDefinition(final Class<? extends IBase> theElementType) {
288                validateInitialized();
289                BaseRuntimeElementDefinition<?> retVal = myClassToElementDefinition.get(theElementType);
290                if (retVal == null) {
291                        retVal = scanDatatype((Class<? extends IElement>) theElementType);
292                }
293                return retVal;
294        }
295
296        /**
297         * Returns the scanned runtime model for the given type. This is an advanced feature which is generally only needed
298         * for extending the core library.
299         * <p>
300         * Note that this method is case insensitive!
301         * </p>
302         */
303        @Nullable
304        public BaseRuntimeElementDefinition<?> getElementDefinition(final String theElementName) {
305                validateInitialized();
306                return myNameToElementDefinition.get(theElementName.toLowerCase());
307        }
308
309        /**
310         * Returns all element definitions (resources, datatypes, etc.)
311         */
312        public Collection<BaseRuntimeElementDefinition<?>> getElementDefinitions() {
313                validateInitialized();
314                return Collections.unmodifiableCollection(myClassToElementDefinition.values());
315        }
316
317        /**
318         * This feature is not yet in its final state and should be considered an internal part of HAPI for now - use with
319         * caution
320         */
321        public HapiLocalizer getLocalizer() {
322                if (myLocalizer == null) {
323                        myLocalizer = new HapiLocalizer();
324                }
325                return myLocalizer;
326        }
327
328        /**
329         * This feature is not yet in its final state and should be considered an internal part of HAPI for now - use with
330         * caution
331         */
332        public void setLocalizer(final HapiLocalizer theMessages) {
333                myLocalizer = theMessages;
334        }
335
336        public INarrativeGenerator getNarrativeGenerator() {
337                return myNarrativeGenerator;
338        }
339
340        public void setNarrativeGenerator(final INarrativeGenerator theNarrativeGenerator) {
341                myNarrativeGenerator = theNarrativeGenerator;
342        }
343
344        /**
345         * Returns the parser options object which will be used to supply default
346         * options to newly created parsers
347         *
348         * @return The parser options - Will not return <code>null</code>
349         */
350        public ParserOptions getParserOptions() {
351                return myParserOptions;
352        }
353
354        /**
355         * Sets the parser options object which will be used to supply default
356         * options to newly created parsers
357         *
358         * @param theParserOptions The parser options object - Must not be <code>null</code>
359         */
360        public void setParserOptions(final ParserOptions theParserOptions) {
361                Validate.notNull(theParserOptions, "theParserOptions must not be null");
362                myParserOptions = theParserOptions;
363        }
364
365        /**
366         * Get the configured performance options
367         */
368        public Set<PerformanceOptionsEnum> getPerformanceOptions() {
369                return myPerformanceOptions;
370        }
371
372        // /**
373        // * Return an unmodifiable collection containing all known resource definitions
374        // */
375        // public Collection<RuntimeResourceDefinition> getResourceDefinitions() {
376        //
377        // Set<Class<? extends IBase>> datatypes = Collections.emptySet();
378        // Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> existing = Collections.emptyMap();
379        // HashMap<String, Class<? extends IBaseResource>> types = new HashMap<String, Class<? extends IBaseResource>>();
380        // ModelScanner.scanVersionPropertyFile(datatypes, types, myVersion.getVersion(), existing);
381        // for (int next : types.)
382        //
383        // return Collections.unmodifiableCollection(myIdToResourceDefinition.values());
384        // }
385
386        /**
387         * Sets the configured performance options
388         *
389         * @see PerformanceOptionsEnum for a list of available options
390         */
391        public void setPerformanceOptions(final Collection<PerformanceOptionsEnum> theOptions) {
392                myPerformanceOptions.clear();
393                if (theOptions != null) {
394                        myPerformanceOptions.addAll(theOptions);
395                }
396        }
397
398        /**
399         * Sets the configured performance options
400         *
401         * @see PerformanceOptionsEnum for a list of available options
402         */
403        public void setPerformanceOptions(final PerformanceOptionsEnum... thePerformanceOptions) {
404                Collection<PerformanceOptionsEnum> asList = null;
405                if (thePerformanceOptions != null) {
406                        asList = Arrays.asList(thePerformanceOptions);
407                }
408                setPerformanceOptions(asList);
409        }
410
411        /**
412         * Returns the scanned runtime model for the given type. This is an advanced feature which is generally only needed
413         * for extending the core library.
414         */
415        public RuntimeResourceDefinition getResourceDefinition(final Class<? extends IBaseResource> theResourceType) {
416                validateInitialized();
417                Validate.notNull(theResourceType, "theResourceType can not be null");
418
419                if (Modifier.isAbstract(theResourceType.getModifiers())) {
420                        throw new IllegalArgumentException("Can not scan abstract or interface class (resource definitions must be concrete classes): " + theResourceType.getName());
421                }
422
423                RuntimeResourceDefinition retVal = (RuntimeResourceDefinition) myClassToElementDefinition.get(theResourceType);
424                if (retVal == null) {
425                        retVal = scanResourceType(theResourceType);
426                }
427                return retVal;
428        }
429
430        public RuntimeResourceDefinition getResourceDefinition(final FhirVersionEnum theVersion, final String theResourceName) {
431                Validate.notNull(theVersion, "theVersion can not be null");
432                validateInitialized();
433
434                if (theVersion.equals(myVersion.getVersion())) {
435                        return getResourceDefinition(theResourceName);
436                }
437
438                Map<String, Class<? extends IBaseResource>> nameToType = myVersionToNameToResourceType.get(theVersion);
439                if (nameToType == null) {
440                        nameToType = new HashMap<>();
441                        Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> existing = new HashMap<>();
442                        ModelScanner.scanVersionPropertyFile(null, nameToType, theVersion, existing);
443
444                        Map<FhirVersionEnum, Map<String, Class<? extends IBaseResource>>> newVersionToNameToResourceType = new HashMap<>();
445                        newVersionToNameToResourceType.putAll(myVersionToNameToResourceType);
446                        newVersionToNameToResourceType.put(theVersion, nameToType);
447                        myVersionToNameToResourceType = newVersionToNameToResourceType;
448                }
449
450                Class<? extends IBaseResource> resourceType = nameToType.get(theResourceName.toLowerCase());
451                if (resourceType == null) {
452                        throw new DataFormatException(createUnknownResourceNameError(theResourceName, theVersion));
453                }
454
455                return getResourceDefinition(resourceType);
456        }
457
458        /**
459         * Returns the scanned runtime model for the given type. This is an advanced feature which is generally only needed
460         * for extending the core library.
461         */
462        public RuntimeResourceDefinition getResourceDefinition(final IBaseResource theResource) {
463                validateInitialized();
464                Validate.notNull(theResource, "theResource must not be null");
465                return getResourceDefinition(theResource.getClass());
466        }
467
468        /**
469         * Returns the name of a given resource class.
470         *
471         * @param theResourceType
472         * @return
473         */
474        public String getResourceType(final Class<? extends IBaseResource> theResourceType) {
475                return getResourceDefinition(theResourceType).getName();
476        }
477
478        /**
479         * Returns the name of the scanned runtime model for the given type. This is an advanced feature which is generally only needed
480         * for extending the core library.
481         */
482        public String getResourceType(final IBaseResource theResource) {
483                return getResourceDefinition(theResource).getName();
484        }
485
486        /*
487         * Returns the type of the scanned runtime model for the given type. This is an advanced feature which is generally only needed
488         * for extending the core library.
489         * <p>
490         * Note that this method is case insensitive!
491         * </p>
492         *
493         * @throws DataFormatException If the resource name is not known
494         */
495        public String getResourceType(final String theResourceName) throws DataFormatException {
496                return getResourceDefinition(theResourceName).getName();
497        }
498
499        /*
500         * Returns the scanned runtime model for the given type. This is an advanced feature which is generally only needed
501         * for extending the core library.
502         * <p>
503         * Note that this method is case insensitive!
504         * </p>
505         *
506         * @throws DataFormatException If the resource name is not known
507         */
508        public RuntimeResourceDefinition getResourceDefinition(final String theResourceName) throws DataFormatException {
509                validateInitialized();
510                Validate.notBlank(theResourceName, "theResourceName must not be blank");
511
512                String resourceName = theResourceName.toLowerCase();
513                RuntimeResourceDefinition retVal = myNameToResourceDefinition.get(resourceName);
514
515                if (retVal == null) {
516                        Class<? extends IBaseResource> clazz = myNameToResourceType.get(resourceName.toLowerCase());
517                        if (clazz == null) {
518                                // ***********************************************************************
519                                // Multiple spots in HAPI FHIR and Smile CDR depend on DataFormatException
520                                // being thrown by this method, don't change that.
521                                // ***********************************************************************
522                                throw new DataFormatException(createUnknownResourceNameError(theResourceName, myVersion.getVersion()));
523                        }
524                        if (IBaseResource.class.isAssignableFrom(clazz)) {
525                                retVal = scanResourceType(clazz);
526                        }
527                }
528                return retVal;
529        }
530
531        /**
532         * Returns the scanned runtime model for the given type. This is an advanced feature which is generally only needed
533         * for extending the core library.
534         */
535        public RuntimeResourceDefinition getResourceDefinitionById(final String theId) {
536                validateInitialized();
537                return myIdToResourceDefinition.get(theId);
538        }
539
540        /**
541         * Returns the scanned runtime models. This is an advanced feature which is generally only needed for extending the
542         * core library.
543         */
544        public Collection<RuntimeResourceDefinition> getResourceDefinitionsWithExplicitId() {
545                validateInitialized();
546                return myIdToResourceDefinition.values();
547        }
548
549        /**
550         * Returns an unmodifiable set containing all resource names known to this
551         * context
552         *
553         * @since 5.1.0
554         */
555        public Set<String> getResourceTypes() {
556                Set<String> resourceNames = new HashSet<>();
557
558                if (myNameToResourceDefinition.isEmpty()) {
559                        Properties props = new Properties();
560                        try {
561                                props.load(myVersion.getFhirVersionPropertiesFile());
562                        } catch (IOException theE) {
563                                throw new ConfigurationException("Failed to load version properties file");
564                        }
565                        Enumeration<?> propNames = props.propertyNames();
566                        while (propNames.hasMoreElements()) {
567                                String next = (String) propNames.nextElement();
568                                if (next.startsWith("resource.")) {
569                                        resourceNames.add(next.substring("resource.".length()).trim());
570                                }
571                        }
572                }
573
574                for (RuntimeResourceDefinition next : myNameToResourceDefinition.values()) {
575                        resourceNames.add(next.getName());
576                }
577
578                return Collections.unmodifiableSet(resourceNames);
579        }
580
581        /**
582         * Get the restful client factory. If no factory has been set, this will be initialized with
583         * a new ApacheRestfulClientFactory.
584         *
585         * @return the factory used to create the restful clients
586         */
587        public IRestfulClientFactory getRestfulClientFactory() {
588                if (myRestfulClientFactory == null) {
589                        try {
590                                myRestfulClientFactory = (IRestfulClientFactory) ReflectionUtil.newInstance(Class.forName("ca.uhn.fhir.rest.client.apache.ApacheRestfulClientFactory"), FhirContext.class, this);
591                        } catch (ClassNotFoundException e) {
592                                throw new ConfigurationException("hapi-fhir-client does not appear to be on the classpath");
593                        }
594                }
595                return myRestfulClientFactory;
596        }
597
598        /**
599         * Set the restful client factory
600         *
601         * @param theRestfulClientFactory
602         */
603        public void setRestfulClientFactory(final IRestfulClientFactory theRestfulClientFactory) {
604                Validate.notNull(theRestfulClientFactory, "theRestfulClientFactory must not be null");
605                this.myRestfulClientFactory = theRestfulClientFactory;
606        }
607
608        public RuntimeChildUndeclaredExtensionDefinition getRuntimeChildUndeclaredExtensionDefinition() {
609                validateInitialized();
610                return myRuntimeChildUndeclaredExtensionDefinition;
611        }
612
613        /**
614         * Returns the validation support module configured for this context, creating a default
615         * implementation if no module has been passed in via the {@link #setValidationSupport(IValidationSupport)}
616         * method
617         *
618         * @see #setValidationSupport(IValidationSupport)
619         */
620        public IValidationSupport getValidationSupport() {
621                IValidationSupport retVal = myValidationSupport;
622                if (retVal == null) {
623                        retVal = new DefaultProfileValidationSupport(this);
624
625                        /*
626                         * If hapi-fhir-validation is on the classpath, we can create a much more robust
627                         * validation chain using the classes found in that package
628                         */
629                        String inMemoryTermSvcType = "org.hl7.fhir.common.hapi.validation.support.InMemoryTerminologyServerValidationSupport";
630                        String commonCodeSystemsSupportType = "org.hl7.fhir.common.hapi.validation.support.CommonCodeSystemsTerminologyService";
631                        if (ReflectionUtil.typeExists(inMemoryTermSvcType)) {
632                                IValidationSupport inMemoryTermSvc = ReflectionUtil.newInstanceOrReturnNull(inMemoryTermSvcType, IValidationSupport.class, new Class<?>[]{FhirContext.class}, new Object[]{this});
633                                IValidationSupport commonCodeSystemsSupport = ReflectionUtil.newInstanceOrReturnNull(commonCodeSystemsSupportType, IValidationSupport.class, new Class<?>[]{FhirContext.class}, new Object[]{this});
634                                retVal = ReflectionUtil.newInstanceOrReturnNull("org.hl7.fhir.common.hapi.validation.support.ValidationSupportChain", IValidationSupport.class, new Class<?>[]{IValidationSupport[].class}, new Object[]{new IValidationSupport[]{
635                                        retVal,
636                                        inMemoryTermSvc,
637                                        commonCodeSystemsSupport
638                                }});
639                                assert retVal != null : "Failed to instantiate " + "org.hl7.fhir.common.hapi.validation.support.ValidationSupportChain";
640                        }
641
642
643                        myValidationSupport = retVal;
644                }
645                return retVal;
646        }
647
648        /**
649         * Sets the validation support module to use for this context. The validation support module
650         * is used to supply underlying infrastructure such as conformance resources (StructureDefinition, ValueSet, etc)
651         * as well as to provide terminology services to modules such as the validator and FluentPath executor
652         */
653        public void setValidationSupport(IValidationSupport theValidationSupport) {
654                myValidationSupport = theValidationSupport;
655        }
656
657        public IFhirVersion getVersion() {
658                return myVersion;
659        }
660
661        /**
662         * Returns <code>true</code> if any default types for specific profiles have been defined
663         * within this context.
664         *
665         * @see #setDefaultTypeForProfile(String, Class)
666         * @see #getDefaultTypeForProfile(String)
667         */
668        public boolean hasDefaultTypeForProfile() {
669                validateInitialized();
670                return !myDefaultTypeForProfile.isEmpty();
671        }
672
673        public IVersionSpecificBundleFactory newBundleFactory() {
674                return myVersion.newBundleFactory(this);
675        }
676
677        /**
678         * @since 2.2
679         * @deprecated Deprecated in HAPI FHIR 5.0.0. Use {@link #newFhirPath()} instead.
680         */
681        @Deprecated
682        public IFhirPath newFluentPath() {
683                return newFhirPath();
684        }
685
686        /**
687         * Creates a new FhirPath engine which can be used to evaluate
688         * path expressions over FHIR resources. Note that this engine will use the
689         * {@link IValidationSupport context validation support} module which is
690         * configured on the context at the time this method is called.
691         * <p>
692         * In other words, you may wish to call {@link #setValidationSupport(IValidationSupport)} before
693         * calling {@link #newFluentPath()}
694         * </p>
695         * <p>
696         * Note that this feature was added for FHIR DSTU3 and is not available
697         * for contexts configured to use an older version of FHIR. Calling this method
698         * on a context for a previous version of fhir will result in an
699         * {@link UnsupportedOperationException}
700         * </p>
701         *
702         * @since 5.0.0
703         */
704        public IFhirPath newFhirPath() {
705                return myVersion.createFhirPathExecutor(this);
706        }
707
708        /**
709         * Create and return a new JSON parser.
710         *
711         * <p>
712         * Thread safety: <b>Parsers are not guaranteed to be thread safe</b>. Create a new parser instance for every thread
713         * or every message being parsed/encoded.
714         * </p>
715         * <p>
716         * Performance Note: <b>This method is cheap</b> to call, and may be called once for every message being processed
717         * without incurring any performance penalty
718         * </p>
719         */
720        public IParser newJsonParser() {
721                return new JsonParser(this, myParserErrorHandler);
722        }
723
724        /**
725         * Create and return a new RDF parser.
726         *
727         * <p>
728         * Thread safety: <b>Parsers are not guaranteed to be thread safe</b>. Create a new parser instance for every thread
729         * or every message being parsed/encoded.
730         * </p>
731         * <p>
732         * Performance Note: <b>This method is cheap</b> to call, and may be called once for every message being processed
733         * without incurring any performance penalty
734         * </p>
735         *
736         * @deprecated THIS FEATURE IS NOT YET COMPLETE
737         */
738        @Deprecated
739        public IParser newRDFParser() {
740                return new RDFParser(this, myParserErrorHandler, Lang.TURTLE);
741        }
742
743        /**
744         * Instantiates a new client instance. This method requires an interface which is defined specifically for your use
745         * cases to contain methods for each of the RESTful operations you wish to implement (e.g. "read ImagingStudy",
746         * "search Patient by identifier", etc.). This interface must extend {@link IRestfulClient} (or commonly its
747         * sub-interface {@link IBasicClient}). See the <a
748         * href="https://hapifhir.io/hapi-fhir/docs/client/introduction.html">RESTful Client</a> documentation for more
749         * information on how to define this interface.
750         *
751         * <p>
752         * Performance Note: <b>This method is cheap</b> to call, and may be called once for every operation invocation
753         * without incurring any performance penalty
754         * </p>
755         *
756         * @param theClientType The client type, which is an interface type to be instantiated
757         * @param theServerBase The URL of the base for the restful FHIR server to connect to
758         * @return A newly created client
759         * @throws ConfigurationException If the interface type is not an interface
760         */
761        public <T extends IRestfulClient> T newRestfulClient(final Class<T> theClientType, final String theServerBase) {
762                return getRestfulClientFactory().newClient(theClientType, theServerBase);
763        }
764
765        /**
766         * Instantiates a new generic client. A generic client is able to perform any of the FHIR RESTful operations against
767         * a compliant server, but does not have methods defining the specific functionality required (as is the case with
768         * {@link #newRestfulClient(Class, String) non-generic clients}).
769         *
770         * <p>
771         * Performance Note: <b>This method is cheap</b> to call, and may be called once for every operation invocation
772         * without incurring any performance penalty
773         * </p>
774         *
775         * @param theServerBase The URL of the base for the restful FHIR server to connect to
776         */
777        public IGenericClient newRestfulGenericClient(final String theServerBase) {
778                return getRestfulClientFactory().newGenericClient(theServerBase);
779        }
780
781        public FhirTerser newTerser() {
782                return new FhirTerser(this);
783        }
784
785        /**
786         * Create a new validator instance.
787         * <p>
788         * Note on thread safety: Validators are thread safe, you may use a single validator
789         * in multiple threads. (This is in contrast to parsers)
790         * </p>
791         */
792        public FhirValidator newValidator() {
793                return new FhirValidator(this);
794        }
795
796        public ViewGenerator newViewGenerator() {
797                return new ViewGenerator(this);
798        }
799
800        /**
801         * Create and return a new XML parser.
802         *
803         * <p>
804         * Thread safety: <b>Parsers are not guaranteed to be thread safe</b>. Create a new parser instance for every thread
805         * or every message being parsed/encoded.
806         * </p>
807         * <p>
808         * Performance Note: <b>This method is cheap</b> to call, and may be called once for every message being processed
809         * without incurring any performance penalty
810         * </p>
811         */
812        public IParser newXmlParser() {
813                return new XmlParser(this, myParserErrorHandler);
814        }
815
816        /**
817         * This method may be used to register a custom resource or datatype. Note that by using
818         * custom types, you are creating a system that will not interoperate with other systems that
819         * do not know about your custom type. There are valid reasons however for wanting to create
820         * custom types and this method can be used to enable them.
821         * <p>
822         * <b>THREAD SAFETY WARNING:</b> This method is not thread safe. It should be called before any
823         * threads are able to call any methods on this context.
824         * </p>
825         *
826         * @param theType The custom type to add (must not be <code>null</code>)
827         */
828        public void registerCustomType(final Class<? extends IBase> theType) {
829                Validate.notNull(theType, "theType must not be null");
830
831                ensureCustomTypeList();
832                myCustomTypes.add(theType);
833        }
834
835        /**
836         * This method may be used to register a custom resource or datatype. Note that by using
837         * custom types, you are creating a system that will not interoperate with other systems that
838         * do not know about your custom type. There are valid reasons however for wanting to create
839         * custom types and this method can be used to enable them.
840         * <p>
841         * <b>THREAD SAFETY WARNING:</b> This method is not thread safe. It should be called before any
842         * threads are able to call any methods on this context.
843         * </p>
844         *
845         * @param theTypes The custom types to add (must not be <code>null</code> or contain null elements in the collection)
846         */
847        public void registerCustomTypes(final Collection<Class<? extends IBase>> theTypes) {
848                Validate.notNull(theTypes, "theTypes must not be null");
849                Validate.noNullElements(theTypes.toArray(), "theTypes must not contain any null elements");
850
851                ensureCustomTypeList();
852
853                myCustomTypes.addAll(theTypes);
854        }
855
856        private BaseRuntimeElementDefinition<?> scanDatatype(final Class<? extends IElement> theResourceType) {
857                ArrayList<Class<? extends IElement>> resourceTypes = new ArrayList<Class<? extends IElement>>();
858                resourceTypes.add(theResourceType);
859                Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> defs = scanResourceTypes(resourceTypes);
860                return defs.get(theResourceType);
861        }
862
863        private RuntimeResourceDefinition scanResourceType(final Class<? extends IBaseResource> theResourceType) {
864                ArrayList<Class<? extends IElement>> resourceTypes = new ArrayList<Class<? extends IElement>>();
865                resourceTypes.add(theResourceType);
866                Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> defs = scanResourceTypes(resourceTypes);
867                return (RuntimeResourceDefinition) defs.get(theResourceType);
868        }
869
870        private synchronized Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> scanResourceTypes(final Collection<Class<? extends IElement>> theResourceTypes) {
871                List<Class<? extends IBase>> typesToScan = new ArrayList<Class<? extends IBase>>();
872                if (theResourceTypes != null) {
873                        typesToScan.addAll(theResourceTypes);
874                }
875                if (myCustomTypes != null) {
876                        typesToScan.addAll(myCustomTypes);
877                        myCustomTypes = null;
878                }
879
880                ModelScanner scanner = new ModelScanner(this, myVersion.getVersion(), myClassToElementDefinition, typesToScan);
881                if (myRuntimeChildUndeclaredExtensionDefinition == null) {
882                        myRuntimeChildUndeclaredExtensionDefinition = scanner.getRuntimeChildUndeclaredExtensionDefinition();
883                }
884
885                Map<String, BaseRuntimeElementDefinition<?>> nameToElementDefinition = new HashMap<>();
886                nameToElementDefinition.putAll(myNameToElementDefinition);
887                for (Entry<String, BaseRuntimeElementDefinition<?>> next : scanner.getNameToElementDefinitions().entrySet()) {
888                        if (!nameToElementDefinition.containsKey(next.getKey())) {
889                                nameToElementDefinition.put(next.getKey().toLowerCase(), next.getValue());
890                        }
891                }
892
893                Map<String, RuntimeResourceDefinition> nameToResourceDefinition = new HashMap<>();
894                nameToResourceDefinition.putAll(myNameToResourceDefinition);
895                for (Entry<String, RuntimeResourceDefinition> next : scanner.getNameToResourceDefinition().entrySet()) {
896                        if (!nameToResourceDefinition.containsKey(next.getKey())) {
897                                nameToResourceDefinition.put(next.getKey(), next.getValue());
898                        }
899                }
900
901                Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> classToElementDefinition = new HashMap<>();
902                classToElementDefinition.putAll(myClassToElementDefinition);
903                classToElementDefinition.putAll(scanner.getClassToElementDefinitions());
904                for (BaseRuntimeElementDefinition<?> next : classToElementDefinition.values()) {
905                        if (next instanceof RuntimeResourceDefinition) {
906                                if ("Bundle".equals(next.getName())) {
907                                        if (!IBaseBundle.class.isAssignableFrom(next.getImplementingClass())) {
908                                                throw new ConfigurationException("Resource type declares resource name Bundle but does not implement IBaseBundle");
909                                        }
910                                }
911                        }
912                }
913
914                Map<String, RuntimeResourceDefinition> idToElementDefinition = new HashMap<>();
915                idToElementDefinition.putAll(myIdToResourceDefinition);
916                idToElementDefinition.putAll(scanner.getIdToResourceDefinition());
917
918                myNameToElementDefinition = nameToElementDefinition;
919                myClassToElementDefinition = classToElementDefinition;
920                myIdToResourceDefinition = idToElementDefinition;
921                myNameToResourceDefinition = nameToResourceDefinition;
922
923                myNameToResourceType = scanner.getNameToResourceType();
924
925                myInitialized = true;
926                return classToElementDefinition;
927        }
928
929        /**
930         * Sets the default type which will be used when parsing a resource that is found to be
931         * of the given profile.
932         * <p>
933         * For example, this method is invoked with the profile string of
934         * <code>"http://example.com/some_patient_profile"</code> and the type of <code>MyPatient.class</code>,
935         * if the parser is parsing a resource and finds that it declares that it conforms to that profile,
936         * the <code>MyPatient</code> type will be used unless otherwise specified.
937         * </p>
938         *
939         * @param theProfile The profile string, e.g. <code>"http://example.com/some_patient_profile"</code>. Must not be
940         *                   <code>null</code> or empty.
941         * @param theClass   The resource type, or <code>null</code> to clear any existing type
942         */
943        public void setDefaultTypeForProfile(final String theProfile, final Class<? extends IBaseResource> theClass) {
944                Validate.notBlank(theProfile, "theProfile must not be null or empty");
945                if (theClass == null) {
946                        myDefaultTypeForProfile.remove(theProfile);
947                } else {
948                        myDefaultTypeForProfile.put(theProfile, theClass);
949                }
950        }
951
952        /**
953         * Sets a parser error handler to use by default on all parsers
954         *
955         * @param theParserErrorHandler The error handler
956         */
957        public void setParserErrorHandler(final IParserErrorHandler theParserErrorHandler) {
958                Validate.notNull(theParserErrorHandler, "theParserErrorHandler must not be null");
959                myParserErrorHandler = theParserErrorHandler;
960        }
961
962        @SuppressWarnings({"cast"})
963        private List<Class<? extends IElement>> toElementList(final Collection<Class<? extends IBaseResource>> theResourceTypes) {
964                if (theResourceTypes == null) {
965                        return null;
966                }
967                List<Class<? extends IElement>> resTypes = new ArrayList<>();
968                for (Class<? extends IBaseResource> next : theResourceTypes) {
969                        resTypes.add(next);
970                }
971                return resTypes;
972        }
973
974        private void validateInitialized() {
975                // See #610
976                if (!myInitialized) {
977                        synchronized (this) {
978                                if (!myInitialized && !myInitializing) {
979                                        myInitializing = true;
980                                        scanResourceTypes(toElementList(myResourceTypesToScan));
981                                }
982                        }
983                }
984        }
985
986        @Override
987        public String toString() {
988                return "FhirContext[" + myVersion.getVersion().name() + "]";
989        }
990
991        /**
992         * Creates and returns a new FhirContext with version {@link FhirVersionEnum#DSTU2 DSTU2}
993         */
994        public static FhirContext forDstu2() {
995                return new FhirContext(FhirVersionEnum.DSTU2);
996        }
997
998        /**
999         * Creates and returns a new FhirContext with version {@link FhirVersionEnum#DSTU2_HL7ORG DSTU2} (using the Reference
1000         * Implementation Structures)
1001         */
1002        public static FhirContext forDstu2Hl7Org() {
1003                return new FhirContext(FhirVersionEnum.DSTU2_HL7ORG);
1004        }
1005
1006        /**
1007         * Creates and returns a new FhirContext with version {@link FhirVersionEnum#DSTU2 DSTU2} (2016 May DSTU3 Snapshot)
1008         */
1009        public static FhirContext forDstu2_1() {
1010                return new FhirContext(FhirVersionEnum.DSTU2_1);
1011        }
1012
1013        /**
1014         * Creates and returns a new FhirContext with version {@link FhirVersionEnum#DSTU3 DSTU3}
1015         *
1016         * @since 1.4
1017         */
1018        public static FhirContext forDstu3() {
1019                return new FhirContext(FhirVersionEnum.DSTU3);
1020        }
1021
1022        /**
1023         * Creates and returns a new FhirContext with version {@link FhirVersionEnum#R4 R4}
1024         *
1025         * @since 3.0.0
1026         */
1027        public static FhirContext forR4() {
1028                return new FhirContext(FhirVersionEnum.R4);
1029        }
1030
1031        /**
1032         * Creates and returns a new FhirContext with version {@link FhirVersionEnum#R5 R5}
1033         *
1034         * @since 4.0.0
1035         */
1036        public static FhirContext forR5() {
1037                return new FhirContext(FhirVersionEnum.R5);
1038        }
1039
1040        /**
1041         * Returns a statically cached {@literal FhirContext} instance for the given version, creating one if none exists in the
1042         * cache. One FhirContext will be kept in the cache for each FHIR version that is requested (by calling
1043         * this method for that version), and the cache will never be expired.
1044         *
1045         * @since 5.1.0
1046         */
1047        public static FhirContext forCached(FhirVersionEnum theFhirVersionEnum) {
1048                return ourStaticContexts.computeIfAbsent(theFhirVersionEnum, v -> new FhirContext(v));
1049        }
1050
1051        private static Collection<Class<? extends IBaseResource>> toCollection(Class<? extends IBaseResource> theResourceType) {
1052                ArrayList<Class<? extends IBaseResource>> retVal = new ArrayList<>(1);
1053                retVal.add(theResourceType);
1054                return retVal;
1055        }
1056
1057        @SuppressWarnings("unchecked")
1058        private static List<Class<? extends IBaseResource>> toCollection(final Class<?>[] theResourceTypes) {
1059                ArrayList<Class<? extends IBaseResource>> retVal = new ArrayList<Class<? extends IBaseResource>>(1);
1060                for (Class<?> clazz : theResourceTypes) {
1061                        if (!IResource.class.isAssignableFrom(clazz)) {
1062                                throw new IllegalArgumentException(clazz.getCanonicalName() + " is not an instance of " + IResource.class.getSimpleName());
1063                        }
1064                        retVal.add((Class<? extends IResource>) clazz);
1065                }
1066                return retVal;
1067        }
1068
1069}