View Javadoc
1   package ca.uhn.fhir.context;
2   
3   import ca.uhn.fhir.context.api.AddProfileTagEnum;
4   import ca.uhn.fhir.context.support.IContextValidationSupport;
5   import ca.uhn.fhir.fluentpath.IFluentPath;
6   import ca.uhn.fhir.i18n.HapiLocalizer;
7   import ca.uhn.fhir.model.api.IElement;
8   import ca.uhn.fhir.model.api.IFhirVersion;
9   import ca.uhn.fhir.model.api.IResource;
10  import ca.uhn.fhir.model.view.ViewGenerator;
11  import ca.uhn.fhir.narrative.INarrativeGenerator;
12  import ca.uhn.fhir.parser.*;
13  import ca.uhn.fhir.rest.api.IVersionSpecificBundleFactory;
14  import ca.uhn.fhir.rest.client.api.IBasicClient;
15  import ca.uhn.fhir.rest.client.api.IGenericClient;
16  import ca.uhn.fhir.rest.client.api.IRestfulClient;
17  import ca.uhn.fhir.rest.client.api.IRestfulClientFactory;
18  import ca.uhn.fhir.util.FhirTerser;
19  import ca.uhn.fhir.util.ReflectionUtil;
20  import ca.uhn.fhir.util.VersionUtil;
21  import ca.uhn.fhir.validation.FhirValidator;
22  import org.apache.commons.lang3.Validate;
23  import org.hl7.fhir.instance.model.api.IBase;
24  import org.hl7.fhir.instance.model.api.IBaseBundle;
25  import org.hl7.fhir.instance.model.api.IBaseResource;
26  
27  import java.io.IOException;
28  import java.lang.reflect.Method;
29  import java.lang.reflect.Modifier;
30  import java.util.*;
31  import java.util.Map.Entry;
32  
33  /*
34   * #%L
35   * HAPI FHIR - Core Library
36   * %%
37   * Copyright (C) 2014 - 2018 University Health Network
38   * %%
39   * Licensed under the Apache License, Version 2.0 (the "License");
40   * you may not use this file except in compliance with the License.
41   * You may obtain a copy of the License at
42   * 
43   * http://www.apache.org/licenses/LICENSE-2.0
44   * 
45   * Unless required by applicable law or agreed to in writing, software
46   * distributed under the License is distributed on an "AS IS" BASIS,
47   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
48   * See the License for the specific language governing permissions and
49   * limitations under the License.
50   * #L%
51   */
52  
53  /**
54   * The FHIR context is the central starting point for the use of the HAPI FHIR API. It should be created once, and then
55   * used as a factory for various other types of objects (parsers, clients, etc.).
56   *
57   * <p>
58   * Important usage notes:
59   * </p>
60   * <ul>
61   * <li>
62   * Thread safety: <b>This class is thread safe</b> and may be shared between multiple processing
63   * threads, except for the {@link #registerCustomType} and {@link #registerCustomTypes} methods.
64   * </li>
65   * <li>
66   * Performance: <b>This class is expensive</b> to create, as it scans every resource class it needs to parse or encode
67   * to build up an internal model of those classes. For that reason, you should try to create one FhirContext instance
68   * which remains for the life of your application and reuse that instance. Note that it will not cause problems to
69   * create multiple instances (ie. resources originating from one FhirContext may be passed to parsers originating from
70   * another) but you will incur a performance penalty if a new FhirContext is created for every message you parse/encode.
71   * </li>
72   * </ul>
73   */
74  public class FhirContext {
75  
76  	private static final List<Class<? extends IBaseResource>> EMPTY_LIST = Collections.emptyList();
77  	private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(FhirContext.class);
78  	private final IFhirVersion myVersion;
79  	private AddProfileTagEnum myAddProfileTagWhenEncoding = AddProfileTagEnum.ONLY_FOR_CUSTOM;
80  	private volatile Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> myClassToElementDefinition = Collections.emptyMap();
81  	private ArrayList<Class<? extends IBase>> myCustomTypes;
82  	private Map<String, Class<? extends IBaseResource>> myDefaultTypeForProfile = new HashMap<String, Class<? extends IBaseResource>>();
83  	private volatile Map<String, RuntimeResourceDefinition> myIdToResourceDefinition = Collections.emptyMap();
84  	private volatile boolean myInitialized;
85  	private volatile boolean myInitializing = false;
86  	private HapiLocalizer myLocalizer = new HapiLocalizer();
87  	private volatile Map<String, BaseRuntimeElementDefinition<?>> myNameToElementDefinition = Collections.emptyMap();
88  	private volatile Map<String, RuntimeResourceDefinition> myNameToResourceDefinition = Collections.emptyMap();
89  	private volatile Map<String, Class<? extends IBaseResource>> myNameToResourceType;
90  	private volatile INarrativeGenerator myNarrativeGenerator;
91  	private volatile IParserErrorHandler myParserErrorHandler = new LenientErrorHandler();
92  	private ParserOptions myParserOptions = new ParserOptions();
93  	private Set<PerformanceOptionsEnum> myPerformanceOptions = new HashSet<PerformanceOptionsEnum>();
94  	private Collection<Class<? extends IBaseResource>> myResourceTypesToScan;
95  	private volatile IRestfulClientFactory myRestfulClientFactory;
96  	private volatile RuntimeChildUndeclaredExtensionDefinition myRuntimeChildUndeclaredExtensionDefinition;
97  	private IContextValidationSupport<?, ?, ?, ?, ?, ?> myValidationSupport;
98  	private Map<FhirVersionEnum, Map<String, Class<? extends IBaseResource>>> myVersionToNameToResourceType = Collections.emptyMap();
99  
100 	/**
101 	 * @deprecated It is recommended that you use one of the static initializer methods instead
102 	 * of this method, e.g. {@link #forDstu2()} or {@link #forDstu3()} or {@link #forR4()}
103 	 */
104 	@Deprecated
105 	public FhirContext() {
106 		this(EMPTY_LIST);
107 	}
108 
109 	/**
110 	 * @deprecated It is recommended that you use one of the static initializer methods instead
111 	 * of this method, e.g. {@link #forDstu2()} or {@link #forDstu3()} or {@link #forR4()}
112 	 */
113 	@Deprecated
114 	public FhirContext(Class<? extends IBaseResource> theResourceType) {
115 		this(toCollection(theResourceType));
116 	}
117 
118 	/**
119 	 * @deprecated It is recommended that you use one of the static initializer methods instead
120 	 * of this method, e.g. {@link #forDstu2()} or {@link #forDstu3()} or {@link #forR4()}
121 	 */
122 	@Deprecated
123 	public FhirContext(Class<?>... theResourceTypes) {
124 		this(toCollection(theResourceTypes));
125 	}
126 
127 	/**
128 	 * @deprecated It is recommended that you use one of the static initializer methods instead
129 	 * of this method, e.g. {@link #forDstu2()} or {@link #forDstu3()} or {@link #forR4()}
130 	 */
131 	@Deprecated
132 	public FhirContext(Collection<Class<? extends IBaseResource>> theResourceTypes) {
133 		this(null, theResourceTypes);
134 	}
135 
136 	/**
137 	 * In most cases it is recommended that you use one of the static initializer methods instead
138 	 * of this method, e.g. {@link #forDstu2()} or {@link #forDstu3()} or {@link #forR4()}, but
139 	 * this method can also be used if you wish to supply the version programmatically.
140 	 */
141 	public FhirContext(FhirVersionEnum theVersion) {
142 		this(theVersion, null);
143 	}
144 
145 	private FhirContext(FhirVersionEnum theVersion, Collection<Class<? extends IBaseResource>> theResourceTypes) {
146 		VersionUtil.getVersion();
147 
148 		if (theVersion != null) {
149 			if (!theVersion.isPresentOnClasspath()) {
150 				throw new IllegalStateException(getLocalizer().getMessage(FhirContext.class, "noStructuresForSpecifiedVersion", theVersion.name()));
151 			}
152 			myVersion = theVersion.getVersionImplementation();
153 		} else if (FhirVersionEnum.DSTU2.isPresentOnClasspath()) {
154 			myVersion = FhirVersionEnum.DSTU2.getVersionImplementation();
155 		} else if (FhirVersionEnum.DSTU2_HL7ORG.isPresentOnClasspath()) {
156 			myVersion = FhirVersionEnum.DSTU2_HL7ORG.getVersionImplementation();
157 		} else if (FhirVersionEnum.DSTU2_1.isPresentOnClasspath()) {
158 			myVersion = FhirVersionEnum.DSTU2_1.getVersionImplementation();
159 		} else if (FhirVersionEnum.DSTU3.isPresentOnClasspath()) {
160 			myVersion = FhirVersionEnum.DSTU3.getVersionImplementation();
161 		} else if (FhirVersionEnum.R4.isPresentOnClasspath()) {
162 			myVersion = FhirVersionEnum.R4.getVersionImplementation();
163 		} else {
164 			throw new IllegalStateException(getLocalizer().getMessage(FhirContext.class, "noStructures"));
165 		}
166 
167 		if (theVersion == null) {
168 			ourLog.info("Creating new FhirContext with auto-detected version [{}]. It is recommended to explicitly select a version for future compatibility by invoking FhirContext.forDstuX()",
169 				myVersion.getVersion().name());
170 		} else {
171 			ourLog.info("Creating new FHIR context for FHIR version [{}]", myVersion.getVersion().name());
172 		}
173 
174 		myResourceTypesToScan = theResourceTypes;
175 
176 		/*
177 		 * Check if we're running in Android mode and configure the context appropriately if so
178 		 */
179 		try {
180 			Class<?> clazz = Class.forName("ca.uhn.fhir.android.AndroidMarker");
181 			ourLog.info("Android mode detected, configuring FhirContext for Android operation");
182 			try {
183 				Method method = clazz.getMethod("configureContext", FhirContext.class);
184 				method.invoke(null, this);
185 			} catch (Throwable e) {
186 				ourLog.warn("Failed to configure context for Android operation", e);
187 			}
188 		} catch (ClassNotFoundException e) {
189 			ourLog.trace("Android mode not detected");
190 		}
191 
192 	}
193 
194 	private String createUnknownResourceNameError(String theResourceName, FhirVersionEnum theVersion) {
195 		return getLocalizer().getMessage(FhirContext.class, "unknownResourceName", theResourceName, theVersion);
196 	}
197 
198 	private void ensureCustomTypeList() {
199 		myClassToElementDefinition.clear();
200 		if (myCustomTypes == null) {
201 			myCustomTypes = new ArrayList<Class<? extends IBase>>();
202 		}
203 	}
204 
205 	/**
206 	 * When encoding resources, this setting configures the parser to include
207 	 * an entry in the resource's metadata section which indicates which profile(s) the
208 	 * resource claims to conform to. The default is {@link AddProfileTagEnum#ONLY_FOR_CUSTOM}.
209 	 *
210 	 * @see #setAddProfileTagWhenEncoding(AddProfileTagEnum) for more information
211 	 */
212 	public AddProfileTagEnum getAddProfileTagWhenEncoding() {
213 		return myAddProfileTagWhenEncoding;
214 	}
215 
216 	/**
217 	 * When encoding resources, this setting configures the parser to include
218 	 * an entry in the resource's metadata section which indicates which profile(s) the
219 	 * resource claims to conform to. The default is {@link AddProfileTagEnum#ONLY_FOR_CUSTOM}.
220 	 * <p>
221 	 * This feature is intended for situations where custom resource types are being used,
222 	 * avoiding the need to manually add profile declarations for these custom types.
223 	 * </p>
224 	 * <p>
225 	 * See <a href="http://jamesagnew.gihhub.io/hapi-fhir/doc_extensions.html">Profiling and Extensions</a>
226 	 * for more information on using custom types.
227 	 * </p>
228 	 * <p>
229 	 * Note that this feature automatically adds the profile, but leaves any profile tags
230 	 * which have been manually added in place as well.
231 	 * </p>
232 	 *
233 	 * @param theAddProfileTagWhenEncoding The add profile mode (must not be <code>null</code>)
234 	 */
235 	public void setAddProfileTagWhenEncoding(AddProfileTagEnum theAddProfileTagWhenEncoding) {
236 		Validate.notNull(theAddProfileTagWhenEncoding, "theAddProfileTagWhenEncoding must not be null");
237 		myAddProfileTagWhenEncoding = theAddProfileTagWhenEncoding;
238 	}
239 
240 	Collection<RuntimeResourceDefinition> getAllResourceDefinitions() {
241 		validateInitialized();
242 		return myNameToResourceDefinition.values();
243 	}
244 
245 	/**
246 	 * Returns the default resource type for the given profile
247 	 *
248 	 * @see #setDefaultTypeForProfile(String, Class)
249 	 */
250 	public Class<? extends IBaseResource> getDefaultTypeForProfile(String theProfile) {
251 		validateInitialized();
252 		return myDefaultTypeForProfile.get(theProfile);
253 	}
254 
255 	/**
256 	 * Returns the scanned runtime model for the given type. This is an advanced feature which is generally only needed
257 	 * for extending the core library.
258 	 */
259 	@SuppressWarnings("unchecked")
260 	public BaseRuntimeElementDefinition<?> getElementDefinition(Class<? extends IBase> theElementType) {
261 		validateInitialized();
262 		BaseRuntimeElementDefinition<?> retVal = myClassToElementDefinition.get(theElementType);
263 		if (retVal == null) {
264 			retVal = scanDatatype((Class<? extends IElement>) theElementType);
265 		}
266 		return retVal;
267 	}
268 
269 	/**
270 	 * Returns the scanned runtime model for the given type. This is an advanced feature which is generally only needed
271 	 * for extending the core library.
272 	 * <p>
273 	 * Note that this method is case insensitive!
274 	 * </p>
275 	 */
276 	public BaseRuntimeElementDefinition<?> getElementDefinition(String theElementName) {
277 		validateInitialized();
278 		return myNameToElementDefinition.get(theElementName.toLowerCase());
279 	}
280 
281 	/**
282 	 * For unit tests only
283 	 */
284 	int getElementDefinitionCount() {
285 		validateInitialized();
286 		return myClassToElementDefinition.size();
287 	}
288 
289 	/**
290 	 * Returns all element definitions (resources, datatypes, etc.)
291 	 */
292 	public Collection<BaseRuntimeElementDefinition<?>> getElementDefinitions() {
293 		validateInitialized();
294 		return Collections.unmodifiableCollection(myClassToElementDefinition.values());
295 	}
296 
297 	/**
298 	 * This feature is not yet in its final state and should be considered an internal part of HAPI for now - use with
299 	 * caution
300 	 */
301 	public HapiLocalizer getLocalizer() {
302 		if (myLocalizer == null) {
303 			myLocalizer = new HapiLocalizer();
304 		}
305 		return myLocalizer;
306 	}
307 
308 	/**
309 	 * This feature is not yet in its final state and should be considered an internal part of HAPI for now - use with
310 	 * caution
311 	 */
312 	public void setLocalizer(HapiLocalizer theMessages) {
313 		myLocalizer = theMessages;
314 	}
315 
316 	public INarrativeGenerator getNarrativeGenerator() {
317 		return myNarrativeGenerator;
318 	}
319 
320 	public void setNarrativeGenerator(INarrativeGenerator theNarrativeGenerator) {
321 		myNarrativeGenerator = theNarrativeGenerator;
322 	}
323 
324 	/**
325 	 * Returns the parser options object which will be used to supply default
326 	 * options to newly created parsers
327 	 *
328 	 * @return The parser options - Will not return <code>null</code>
329 	 */
330 	public ParserOptions getParserOptions() {
331 		return myParserOptions;
332 	}
333 
334 	/**
335 	 * Sets the parser options object which will be used to supply default
336 	 * options to newly created parsers
337 	 *
338 	 * @param theParserOptions The parser options object - Must not be <code>null</code>
339 	 */
340 	public void setParserOptions(ParserOptions theParserOptions) {
341 		Validate.notNull(theParserOptions, "theParserOptions must not be null");
342 		myParserOptions = theParserOptions;
343 	}
344 
345 	/**
346 	 * Get the configured performance options
347 	 */
348 	public Set<PerformanceOptionsEnum> getPerformanceOptions() {
349 		return myPerformanceOptions;
350 	}
351 
352 	// /**
353 	// * Return an unmodifiable collection containing all known resource definitions
354 	// */
355 	// public Collection<RuntimeResourceDefinition> getResourceDefinitions() {
356 	//
357 	// Set<Class<? extends IBase>> datatypes = Collections.emptySet();
358 	// Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> existing = Collections.emptyMap();
359 	// HashMap<String, Class<? extends IBaseResource>> types = new HashMap<String, Class<? extends IBaseResource>>();
360 	// ModelScanner.scanVersionPropertyFile(datatypes, types, myVersion.getVersion(), existing);
361 	// for (int next : types.)
362 	//
363 	// return Collections.unmodifiableCollection(myIdToResourceDefinition.values());
364 	// }
365 
366 	/**
367 	 * Sets the configured performance options
368 	 *
369 	 * @see PerformanceOptionsEnum for a list of available options
370 	 */
371 	public void setPerformanceOptions(Collection<PerformanceOptionsEnum> theOptions) {
372 		myPerformanceOptions.clear();
373 		if (theOptions != null) {
374 			myPerformanceOptions.addAll(theOptions);
375 		}
376 	}
377 
378 	/**
379 	 * Returns the scanned runtime model for the given type. This is an advanced feature which is generally only needed
380 	 * for extending the core library.
381 	 */
382 	public RuntimeResourceDefinition getResourceDefinition(Class<? extends IBaseResource> theResourceType) {
383 		validateInitialized();
384 		if (theResourceType == null) {
385 			throw new NullPointerException("theResourceType can not be null");
386 		}
387 		if (Modifier.isAbstract(theResourceType.getModifiers())) {
388 			throw new IllegalArgumentException("Can not scan abstract or interface class (resource definitions must be concrete classes): " + theResourceType.getName());
389 		}
390 
391 		RuntimeResourceDefinition retVal = (RuntimeResourceDefinition) myClassToElementDefinition.get(theResourceType);
392 		if (retVal == null) {
393 			retVal = scanResourceType(theResourceType);
394 		}
395 		return retVal;
396 	}
397 
398 	public RuntimeResourceDefinition getResourceDefinition(FhirVersionEnum theVersion, String theResourceName) {
399 		Validate.notNull(theVersion, "theVersion can not be null");
400 		validateInitialized();
401 
402 		if (theVersion.equals(myVersion.getVersion())) {
403 			return getResourceDefinition(theResourceName);
404 		}
405 
406 		Map<String, Class<? extends IBaseResource>> nameToType = myVersionToNameToResourceType.get(theVersion);
407 		if (nameToType == null) {
408 			nameToType = new HashMap<>();
409 			Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> existing = new HashMap<>();
410 			ModelScanner.scanVersionPropertyFile(null, nameToType, theVersion, existing);
411 
412 			Map<FhirVersionEnum, Map<String, Class<? extends IBaseResource>>> newVersionToNameToResourceType = new HashMap<>();
413 			newVersionToNameToResourceType.putAll(myVersionToNameToResourceType);
414 			newVersionToNameToResourceType.put(theVersion, nameToType);
415 			myVersionToNameToResourceType = newVersionToNameToResourceType;
416 		}
417 
418 		Class<? extends IBaseResource> resourceType = nameToType.get(theResourceName.toLowerCase());
419 		if (resourceType == null) {
420 			throw new DataFormatException(createUnknownResourceNameError(theResourceName, theVersion));
421 		}
422 
423 		return getResourceDefinition(resourceType);
424 	}
425 
426 	/**
427 	 * Returns the scanned runtime model for the given type. This is an advanced feature which is generally only needed
428 	 * for extending the core library.
429 	 */
430 	public RuntimeResourceDefinition getResourceDefinition(IBaseResource theResource) {
431 		validateInitialized();
432 		Validate.notNull(theResource, "theResource must not be null");
433 		return getResourceDefinition(theResource.getClass());
434 	}
435 
436 	/**
437 	 * Returns the scanned runtime model for the given type. This is an advanced feature which is generally only needed
438 	 * for extending the core library.
439 	 * <p>
440 	 * Note that this method is case insensitive!
441 	 * </p>
442 	 *
443 	 * @throws DataFormatException If the resource name is not known
444 	 */
445 	// Multiple spots in HAPI FHIR and Smile CDR depend on DataFormatException being
446 	// thrown by this method, don't change that.
447 	public RuntimeResourceDefinition getResourceDefinition(String theResourceName) throws DataFormatException {
448 		validateInitialized();
449 		Validate.notBlank(theResourceName, "theResourceName must not be blank");
450 
451 		String resourceName = theResourceName.toLowerCase();
452 		RuntimeResourceDefinition retVal = myNameToResourceDefinition.get(resourceName);
453 
454 		if (retVal == null) {
455 			Class<? extends IBaseResource> clazz = myNameToResourceType.get(resourceName.toLowerCase());
456 			if (clazz == null) {
457 				throw new DataFormatException(createUnknownResourceNameError(theResourceName, myVersion.getVersion()));
458 			}
459 			if (IBaseResource.class.isAssignableFrom(clazz)) {
460 				retVal = scanResourceType(clazz);
461 			}
462 		}
463 
464 		return retVal;
465 	}
466 
467 	/**
468 	 * Returns the scanned runtime model for the given type. This is an advanced feature which is generally only needed
469 	 * for extending the core library.
470 	 */
471 	public RuntimeResourceDefinition getResourceDefinitionById(String theId) {
472 		validateInitialized();
473 		return myIdToResourceDefinition.get(theId);
474 	}
475 
476 	/**
477 	 * Returns the scanned runtime models. This is an advanced feature which is generally only needed for extending the
478 	 * core library.
479 	 */
480 	public Collection<RuntimeResourceDefinition> getResourceDefinitionsWithExplicitId() {
481 		validateInitialized();
482 		return myIdToResourceDefinition.values();
483 	}
484 
485 	/**
486 	 * Returns an unmodifiable set containing all resource names known to this
487 	 * context
488 	 */
489 	public Set<String> getResourceNames() {
490 		Set<String> resourceNames = new HashSet<>();
491 
492 		if (myNameToResourceDefinition.isEmpty()) {
493 			Properties props = new Properties();
494 			try {
495 				props.load(myVersion.getFhirVersionPropertiesFile());
496 			} catch (IOException theE) {
497 				throw new ConfigurationException("Failed to load version properties file");
498 			}
499 			Enumeration<?> propNames = props.propertyNames();
500 			while (propNames.hasMoreElements()) {
501 				String next = (String) propNames.nextElement();
502 				if (next.startsWith("resource.")) {
503 					resourceNames.add(next.substring("resource.".length()).trim());
504 				}
505 			}
506 		}
507 
508 		for (RuntimeResourceDefinition next : myNameToResourceDefinition.values()) {
509 			resourceNames.add(next.getName());
510 		}
511 
512 		return Collections.unmodifiableSet(resourceNames);
513 	}
514 
515 	/**
516 	 * Get the restful client factory. If no factory has been set, this will be initialized with
517 	 * a new ApacheRestfulClientFactory.
518 	 *
519 	 * @return the factory used to create the restful clients
520 	 */
521 	public IRestfulClientFactory getRestfulClientFactory() {
522 		if (myRestfulClientFactory == null) {
523 			try {
524 				myRestfulClientFactory = (IRestfulClientFactory) ReflectionUtil.newInstance(Class.forName("ca.uhn.fhir.rest.client.apache.ApacheRestfulClientFactory"), FhirContext.class, this);
525 			} catch (ClassNotFoundException e) {
526 				throw new ConfigurationException("hapi-fhir-client does not appear to be on the classpath");
527 			}
528 		}
529 		return myRestfulClientFactory;
530 	}
531 
532 	/**
533 	 * Set the restful client factory
534 	 *
535 	 * @param theRestfulClientFactory
536 	 */
537 	public void setRestfulClientFactory(IRestfulClientFactory theRestfulClientFactory) {
538 		Validate.notNull(theRestfulClientFactory, "theRestfulClientFactory must not be null");
539 		this.myRestfulClientFactory = theRestfulClientFactory;
540 	}
541 
542 	public RuntimeChildUndeclaredExtensionDefinition getRuntimeChildUndeclaredExtensionDefinition() {
543 		validateInitialized();
544 		return myRuntimeChildUndeclaredExtensionDefinition;
545 	}
546 
547 	/**
548 	 * Returns the validation support module configured for this context, creating a default
549 	 * implementation if no module has been passed in via the {@link #setValidationSupport(IContextValidationSupport)}
550 	 * method
551 	 *
552 	 * @see #setValidationSupport(IContextValidationSupport)
553 	 */
554 	public IContextValidationSupport<?, ?, ?, ?, ?, ?> getValidationSupport() {
555 		if (myValidationSupport == null) {
556 			myValidationSupport = myVersion.createValidationSupport();
557 		}
558 		return myValidationSupport;
559 	}
560 
561 	/**
562 	 * Sets the validation support module to use for this context. The validation support module
563 	 * is used to supply underlying infrastructure such as conformance resources (StructureDefinition, ValueSet, etc)
564 	 * as well as to provide terminology services to modules such as the validator and FluentPath executor
565 	 */
566 	public void setValidationSupport(IContextValidationSupport<?, ?, ?, ?, ?, ?> theValidationSupport) {
567 		myValidationSupport = theValidationSupport;
568 	}
569 
570 	public IFhirVersion getVersion() {
571 		return myVersion;
572 	}
573 
574 	/**
575 	 * Returns <code>true</code> if any default types for specific profiles have been defined
576 	 * within this context.
577 	 *
578 	 * @see #setDefaultTypeForProfile(String, Class)
579 	 * @see #getDefaultTypeForProfile(String)
580 	 */
581 	public boolean hasDefaultTypeForProfile() {
582 		validateInitialized();
583 		return !myDefaultTypeForProfile.isEmpty();
584 	}
585 
586 	public IVersionSpecificBundleFactory newBundleFactory() {
587 		return myVersion.newBundleFactory(this);
588 	}
589 
590 	/**
591 	 * Creates a new FluentPath engine which can be used to exvaluate
592 	 * path expressions over FHIR resources. Note that this engine will use the
593 	 * {@link IContextValidationSupport context validation support} module which is
594 	 * configured on the context at the time this method is called.
595 	 * <p>
596 	 * In other words, call {@link #setValidationSupport(IContextValidationSupport)} before
597 	 * calling {@link #newFluentPath()}
598 	 * </p>
599 	 * <p>
600 	 * Note that this feature was added for FHIR DSTU3 and is not available
601 	 * for contexts configured to use an older version of FHIR. Calling this method
602 	 * on a context for a previous version of fhir will result in an
603 	 * {@link UnsupportedOperationException}
604 	 * </p>
605 	 *
606 	 * @since 2.2
607 	 */
608 	public IFluentPath newFluentPath() {
609 		return myVersion.createFluentPathExecutor(this);
610 	}
611 
612 	/**
613 	 * Create and return a new JSON parser.
614 	 *
615 	 * <p>
616 	 * Thread safety: <b>Parsers are not guaranteed to be thread safe</b>. Create a new parser instance for every thread
617 	 * or every message being parsed/encoded.
618 	 * </p>
619 	 * <p>
620 	 * Performance Note: <b>This method is cheap</b> to call, and may be called once for every message being processed
621 	 * without incurring any performance penalty
622 	 * </p>
623 	 */
624 	public IParser newJsonParser() {
625 		return new JsonParser(this, myParserErrorHandler);
626 	}
627 
628 	/**
629 	 * Instantiates a new client instance. This method requires an interface which is defined specifically for your use
630 	 * cases to contain methods for each of the RESTful operations you wish to implement (e.g. "read ImagingStudy",
631 	 * "search Patient by identifier", etc.). This interface must extend {@link IRestfulClient} (or commonly its
632 	 * sub-interface {@link IBasicClient}). See the <a
633 	 * href="http://jamesagnew.github.io/hapi-fhir/doc_rest_client.html">RESTful Client</a> documentation for more
634 	 * information on how to define this interface.
635 	 *
636 	 * <p>
637 	 * Performance Note: <b>This method is cheap</b> to call, and may be called once for every operation invocation
638 	 * without incurring any performance penalty
639 	 * </p>
640 	 *
641 	 * @param theClientType The client type, which is an interface type to be instantiated
642 	 * @param theServerBase The URL of the base for the restful FHIR server to connect to
643 	 * @return A newly created client
644 	 * @throws ConfigurationException If the interface type is not an interface
645 	 */
646 	public <T extends IRestfulClient> T newRestfulClient(Class<T> theClientType, String theServerBase) {
647 		return getRestfulClientFactory().newClient(theClientType, theServerBase);
648 	}
649 
650 	/**
651 	 * Instantiates a new generic client. A generic client is able to perform any of the FHIR RESTful operations against
652 	 * a compliant server, but does not have methods defining the specific functionality required (as is the case with
653 	 * {@link #newRestfulClient(Class, String) non-generic clients}).
654 	 *
655 	 * <p>
656 	 * Performance Note: <b>This method is cheap</b> to call, and may be called once for every operation invocation
657 	 * without incurring any performance penalty
658 	 * </p>
659 	 *
660 	 * @param theServerBase The URL of the base for the restful FHIR server to connect to
661 	 */
662 	public IGenericClient newRestfulGenericClient(String theServerBase) {
663 		return getRestfulClientFactory().newGenericClient(theServerBase);
664 	}
665 
666 	public FhirTerser newTerser() {
667 		return new FhirTerser(this);
668 	}
669 
670 	/**
671 	 * Create a new validator instance.
672 	 * <p>
673 	 * Note on thread safety: Validators are thread safe, you may use a single validator
674 	 * in multiple threads. (This is in contrast to parsers)
675 	 * </p>
676 	 */
677 	public FhirValidator newValidator() {
678 		return new FhirValidator(this);
679 	}
680 
681 	public ViewGenerator newViewGenerator() {
682 		return new ViewGenerator(this);
683 	}
684 
685 	/**
686 	 * Create and return a new XML parser.
687 	 *
688 	 * <p>
689 	 * Thread safety: <b>Parsers are not guaranteed to be thread safe</b>. Create a new parser instance for every thread
690 	 * or every message being parsed/encoded.
691 	 * </p>
692 	 * <p>
693 	 * Performance Note: <b>This method is cheap</b> to call, and may be called once for every message being processed
694 	 * without incurring any performance penalty
695 	 * </p>
696 	 */
697 	public IParser newXmlParser() {
698 		return new XmlParser(this, myParserErrorHandler);
699 	}
700 
701 	/**
702 	 * This method may be used to register a custom resource or datatype. Note that by using
703 	 * custom types, you are creating a system that will not interoperate with other systems that
704 	 * do not know about your custom type. There are valid reasons however for wanting to create
705 	 * custom types and this method can be used to enable them.
706 	 * <p>
707 	 * <b>THREAD SAFETY WARNING:</b> This method is not thread safe. It should be called before any
708 	 * threads are able to call any methods on this context.
709 	 * </p>
710 	 *
711 	 * @param theType The custom type to add (must not be <code>null</code>)
712 	 */
713 	public void registerCustomType(Class<? extends IBase> theType) {
714 		Validate.notNull(theType, "theType must not be null");
715 
716 		ensureCustomTypeList();
717 		myCustomTypes.add(theType);
718 	}
719 
720 	/**
721 	 * This method may be used to register a custom resource or datatype. Note that by using
722 	 * custom types, you are creating a system that will not interoperate with other systems that
723 	 * do not know about your custom type. There are valid reasons however for wanting to create
724 	 * custom types and this method can be used to enable them.
725 	 * <p>
726 	 * <b>THREAD SAFETY WARNING:</b> This method is not thread safe. It should be called before any
727 	 * threads are able to call any methods on this context.
728 	 * </p>
729 	 *
730 	 * @param theTypes The custom types to add (must not be <code>null</code> or contain null elements in the collection)
731 	 */
732 	public void registerCustomTypes(Collection<Class<? extends IBase>> theTypes) {
733 		Validate.notNull(theTypes, "theTypes must not be null");
734 		Validate.noNullElements(theTypes.toArray(), "theTypes must not contain any null elements");
735 
736 		ensureCustomTypeList();
737 
738 		myCustomTypes.addAll(theTypes);
739 	}
740 
741 	private BaseRuntimeElementDefinition<?> scanDatatype(Class<? extends IElement> theResourceType) {
742 		ArrayList<Class<? extends IElement>> resourceTypes = new ArrayList<Class<? extends IElement>>();
743 		resourceTypes.add(theResourceType);
744 		Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> defs = scanResourceTypes(resourceTypes);
745 		return defs.get(theResourceType);
746 	}
747 
748 	private RuntimeResourceDefinition scanResourceType(Class<? extends IBaseResource> theResourceType) {
749 		ArrayList<Class<? extends IElement>> resourceTypes = new ArrayList<Class<? extends IElement>>();
750 		resourceTypes.add(theResourceType);
751 		Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> defs = scanResourceTypes(resourceTypes);
752 		return (RuntimeResourceDefinition) defs.get(theResourceType);
753 	}
754 
755 	private synchronized Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> scanResourceTypes(Collection<Class<? extends IElement>> theResourceTypes) {
756 		List<Class<? extends IBase>> typesToScan = new ArrayList<Class<? extends IBase>>();
757 		if (theResourceTypes != null) {
758 			typesToScan.addAll(theResourceTypes);
759 		}
760 		if (myCustomTypes != null) {
761 			typesToScan.addAll(myCustomTypes);
762 			myCustomTypes = null;
763 		}
764 
765 		ModelScanner scanner = new ModelScanner(this, myVersion.getVersion(), myClassToElementDefinition, typesToScan);
766 		if (myRuntimeChildUndeclaredExtensionDefinition == null) {
767 			myRuntimeChildUndeclaredExtensionDefinition = scanner.getRuntimeChildUndeclaredExtensionDefinition();
768 		}
769 
770 		Map<String, BaseRuntimeElementDefinition<?>> nameToElementDefinition = new HashMap<String, BaseRuntimeElementDefinition<?>>();
771 		nameToElementDefinition.putAll(myNameToElementDefinition);
772 		for (Entry<String, BaseRuntimeElementDefinition<?>> next : scanner.getNameToElementDefinitions().entrySet()) {
773 			if (!nameToElementDefinition.containsKey(next.getKey())) {
774 				nameToElementDefinition.put(next.getKey().toLowerCase(), next.getValue());
775 			}
776 		}
777 
778 		Map<String, RuntimeResourceDefinition> nameToResourceDefinition = new HashMap<String, RuntimeResourceDefinition>();
779 		nameToResourceDefinition.putAll(myNameToResourceDefinition);
780 		for (Entry<String, RuntimeResourceDefinition> next : scanner.getNameToResourceDefinition().entrySet()) {
781 			if (!nameToResourceDefinition.containsKey(next.getKey())) {
782 				nameToResourceDefinition.put(next.getKey(), next.getValue());
783 			}
784 		}
785 
786 		Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> classToElementDefinition = new HashMap<Class<? extends IBase>, BaseRuntimeElementDefinition<?>>();
787 		classToElementDefinition.putAll(myClassToElementDefinition);
788 		classToElementDefinition.putAll(scanner.getClassToElementDefinitions());
789 		for (BaseRuntimeElementDefinition<?> next : classToElementDefinition.values()) {
790 			if (next instanceof RuntimeResourceDefinition) {
791 				if ("Bundle".equals(next.getName())) {
792 					if (!IBaseBundle.class.isAssignableFrom(next.getImplementingClass())) {
793 						throw new ConfigurationException("Resource type declares resource name Bundle but does not implement IBaseBundle");
794 					}
795 				}
796 			}
797 		}
798 
799 		Map<String, RuntimeResourceDefinition> idToElementDefinition = new HashMap<String, RuntimeResourceDefinition>();
800 		idToElementDefinition.putAll(myIdToResourceDefinition);
801 		idToElementDefinition.putAll(scanner.getIdToResourceDefinition());
802 
803 		myNameToElementDefinition = nameToElementDefinition;
804 		myClassToElementDefinition = classToElementDefinition;
805 		myIdToResourceDefinition = idToElementDefinition;
806 		myNameToResourceDefinition = nameToResourceDefinition;
807 
808 		myNameToResourceType = scanner.getNameToResourceType();
809 
810 		myInitialized = true;
811 		return classToElementDefinition;
812 	}
813 
814 	/**
815 	 * Sets the default type which will be used when parsing a resource that is found to be
816 	 * of the given profile.
817 	 * <p>
818 	 * For example, this method is invoked with the profile string of
819 	 * <code>"http://example.com/some_patient_profile"</code> and the type of <code>MyPatient.class</code>,
820 	 * if the parser is parsing a resource and finds that it declares that it conforms to that profile,
821 	 * the <code>MyPatient</code> type will be used unless otherwise specified.
822 	 * </p>
823 	 *
824 	 * @param theProfile The profile string, e.g. <code>"http://example.com/some_patient_profile"</code>. Must not be
825 	 *                   <code>null</code> or empty.
826 	 * @param theClass   The resource type, or <code>null</code> to clear any existing type
827 	 */
828 	public void setDefaultTypeForProfile(String theProfile, Class<? extends IBaseResource> theClass) {
829 		Validate.notBlank(theProfile, "theProfile must not be null or empty");
830 		if (theClass == null) {
831 			myDefaultTypeForProfile.remove(theProfile);
832 		} else {
833 			myDefaultTypeForProfile.put(theProfile, theClass);
834 		}
835 	}
836 
837 	/**
838 	 * Sets a parser error handler to use by default on all parsers
839 	 *
840 	 * @param theParserErrorHandler The error handler
841 	 */
842 	public void setParserErrorHandler(IParserErrorHandler theParserErrorHandler) {
843 		Validate.notNull(theParserErrorHandler, "theParserErrorHandler must not be null");
844 		myParserErrorHandler = theParserErrorHandler;
845 	}
846 
847 	/**
848 	 * Sets the configured performance options
849 	 *
850 	 * @see PerformanceOptionsEnum for a list of available options
851 	 */
852 	public void setPerformanceOptions(PerformanceOptionsEnum... thePerformanceOptions) {
853 		Collection<PerformanceOptionsEnum> asList = null;
854 		if (thePerformanceOptions != null) {
855 			asList = Arrays.asList(thePerformanceOptions);
856 		}
857 		setPerformanceOptions(asList);
858 	}
859 
860 	@SuppressWarnings({"cast"})
861 	private List<Class<? extends IElement>> toElementList(Collection<Class<? extends IBaseResource>> theResourceTypes) {
862 		if (theResourceTypes == null) {
863 			return null;
864 		}
865 		List<Class<? extends IElement>> resTypes = new ArrayList<Class<? extends IElement>>();
866 		for (Class<? extends IBaseResource> next : theResourceTypes) {
867 			resTypes.add((Class<? extends IElement>) next);
868 		}
869 		return resTypes;
870 	}
871 
872 	private void validateInitialized() {
873 		// See #610
874 		if (!myInitialized) {
875 			synchronized (this) {
876 				if (!myInitialized && !myInitializing) {
877 					myInitializing = true;
878 					scanResourceTypes(toElementList(myResourceTypesToScan));
879 				}
880 			}
881 		}
882 	}
883 
884 	/**
885 	 * Creates and returns a new FhirContext with version {@link FhirVersionEnum#DSTU2 DSTU2}
886 	 */
887 	public static FhirContext forDstu2() {
888 		return new FhirContext(FhirVersionEnum.DSTU2);
889 	}
890 
891 	/**
892 	 * Creates and returns a new FhirContext with version {@link FhirVersionEnum#DSTU2_HL7ORG DSTU2} (using the Reference
893 	 * Implementation Structures)
894 	 */
895 	public static FhirContext forDstu2Hl7Org() {
896 		return new FhirContext(FhirVersionEnum.DSTU2_HL7ORG);
897 	}
898 
899 	/**
900 	 * Creates and returns a new FhirContext with version {@link FhirVersionEnum#DSTU2 DSTU2} (2016 May DSTU3 Snapshot)
901 	 */
902 	public static FhirContext forDstu2_1() {
903 		return new FhirContext(FhirVersionEnum.DSTU2_1);
904 	}
905 
906 	/**
907 	 * Creates and returns a new FhirContext with version {@link FhirVersionEnum#DSTU3 DSTU3}
908 	 *
909 	 * @since 1.4
910 	 */
911 	public static FhirContext forDstu3() {
912 		return new FhirContext(FhirVersionEnum.DSTU3);
913 	}
914 
915 	/**
916 	 * Creates and returns a new FhirContext with version {@link FhirVersionEnum#DSTU3 DSTU3}
917 	 *
918 	 * @since 3.0.0
919 	 */
920 	public static FhirContext forR4() {
921 		return new FhirContext(FhirVersionEnum.R4);
922 	}
923 
924 	private static Collection<Class<? extends IBaseResource>> toCollection(Class<? extends IBaseResource> theResourceType) {
925 		ArrayList<Class<? extends IBaseResource>> retVal = new ArrayList<Class<? extends IBaseResource>>(1);
926 		retVal.add(theResourceType);
927 		return retVal;
928 	}
929 
930 	@SuppressWarnings("unchecked")
931 	private static List<Class<? extends IBaseResource>> toCollection(Class<?>[] theResourceTypes) {
932 		ArrayList<Class<? extends IBaseResource>> retVal = new ArrayList<Class<? extends IBaseResource>>(1);
933 		for (Class<?> clazz : theResourceTypes) {
934 			if (!IResource.class.isAssignableFrom(clazz)) {
935 				throw new IllegalArgumentException(clazz.getCanonicalName() + " is not an instance of " + IResource.class.getSimpleName());
936 			}
937 			retVal.add((Class<? extends IResource>) clazz);
938 		}
939 		return retVal;
940 	}
941 }