001package org.hl7.fhir.r5.context;
002
003import java.util.EnumSet;
004
005/*-
006 * #%L
007 * org.hl7.fhir.r5
008 * %%
009 * Copyright (C) 2014 - 2019 Health Level 7
010 * %%
011 * Licensed under the Apache License, Version 2.0 (the "License");
012 * you may not use this file except in compliance with the License.
013 * You may obtain a copy of the License at
014 * 
015 *      http://www.apache.org/licenses/LICENSE-2.0
016 * 
017 * Unless required by applicable law or agreed to in writing, software
018 * distributed under the License is distributed on an "AS IS" BASIS,
019 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
020 * See the License for the specific language governing permissions and
021 * limitations under the License.
022 * #L%
023 */
024
025
026import java.util.List;
027import java.util.Map;
028import java.util.Set;
029
030import org.fhir.ucum.UcumService;
031import org.hl7.fhir.exceptions.DefinitionException;
032import org.hl7.fhir.exceptions.FHIRException;
033import org.hl7.fhir.exceptions.TerminologyServiceException;
034import org.hl7.fhir.r5.formats.IParser;
035import org.hl7.fhir.r5.formats.ParserType;
036import org.hl7.fhir.r5.model.CodeSystem;
037import org.hl7.fhir.r5.model.CodeSystem.ConceptDefinitionComponent;
038import org.hl7.fhir.r5.model.CodeableConcept;
039import org.hl7.fhir.r5.model.Coding;
040import org.hl7.fhir.r5.model.ConceptMap;
041import org.hl7.fhir.r5.model.ElementDefinition.ElementDefinitionBindingComponent;
042import org.hl7.fhir.r5.model.CanonicalResource;
043import org.hl7.fhir.r5.model.Parameters;
044import org.hl7.fhir.r5.model.Resource;
045import org.hl7.fhir.r5.model.StructureDefinition;
046import org.hl7.fhir.r5.model.StructureMap;
047import org.hl7.fhir.r5.model.ValueSet;
048import org.hl7.fhir.r5.model.ValueSet.ConceptSetComponent;
049import org.hl7.fhir.r5.terminologies.ValueSetExpander.TerminologyServiceErrorClass;
050import org.hl7.fhir.r5.terminologies.ValueSetExpander.ValueSetExpansionOutcome;
051import org.hl7.fhir.r5.utils.INarrativeGenerator;
052import org.hl7.fhir.r5.utils.IResourceValidator;
053import org.hl7.fhir.utilities.TerminologyServiceOptions;
054import org.hl7.fhir.utilities.TranslationServices;
055import org.hl7.fhir.utilities.validation.ValidationOptions;
056import org.hl7.fhir.utilities.validation.ValidationMessage.IssueSeverity;
057
058
059/**
060 * This is the standard interface used for access to underlying FHIR
061 * services through the tools and utilities provided by the reference
062 * implementation. 
063 * 
064 * The functionality it provides is 
065 *  - get access to parsers, validators, narrative builders etc
066 *    (you can't create these directly because they need access 
067 *    to the right context for their information)
068 *    
069 *  - find resources that the tools need to carry out their tasks
070 *  
071 *  - provide access to terminology services they need. 
072 *    (typically, these terminology service requests are just
073 *    passed through to the local implementation's terminology
074 *    service)    
075 *  
076 * @author Grahame
077 */
078public interface IWorkerContext {
079
080  /**
081   * Get the versions of the definitions loaded in context
082   * @return
083   */
084  public String getVersion();
085  
086  // get the UCUM service (might not be available)
087  public UcumService getUcumService();
088  
089  // -- Parsers (read and write instances) ----------------------------------------
090
091
092  /**
093   * Get a parser to read/write instances. Use the defined type (will be extended 
094   * as further types are added, though the only currently anticipate type is RDF)
095   * 
096   * XML/JSON - the standard renderers
097   * XHTML - render the narrative only (generate it if necessary)
098   * 
099   * @param type
100   * @return
101   */
102  public IParser getParser(ParserType type);
103
104  /**
105   * Get a parser to read/write instances. Determine the type 
106   * from the stated type. Supported value for type:
107   * - the recommended MIME types
108   * - variants of application/xml and application/json
109   * - _format values xml, json
110   * 
111   * @param type
112   * @return
113   */   
114  public IParser getParser(String type);
115
116  /**
117   * Get a JSON parser
118   * 
119   * @return
120   */
121  public IParser newJsonParser();
122
123  /**
124   * Get an XML parser
125   * 
126   * @return
127   */
128  public IParser newXmlParser();
129
130  /**
131   * Get a generator that can generate narrative for the instance
132   * 
133   * @return a prepared generator
134   */
135  public INarrativeGenerator getNarrativeGenerator(String prefix, String basePath);
136
137  /**
138   * Get a validator that can check whether a resource is valid 
139   * 
140   * @return a prepared generator
141   * @throws FHIRException 
142   * @
143   */
144  public IResourceValidator newValidator() throws FHIRException;
145
146  // -- resource fetchers ---------------------------------------------------
147
148  /**
149   * Find an identified resource. The most common use of this is to access the the 
150   * standard conformance resources that are part of the standard - structure 
151   * definitions, value sets, concept maps, etc.
152   * 
153   * Also, the narrative generator uses this, and may access any kind of resource
154   * 
155   * The URI is called speculatively for things that might exist, so not finding 
156   * a matching resouce, return null, not an error
157   * 
158   * The URI can have one of 3 formats:
159   *  - a full URL e.g. http://acme.org/fhir/ValueSet/[id]
160   *  - a relative URL e.g. ValueSet/[id]
161   *  - a logical id e.g. [id]
162   *  
163   * It's an error if the second form doesn't agree with class_. It's an 
164   * error if class_ is null for the last form
165   * 
166   * @param resource
167   * @param Reference
168   * @return
169   * @throws FHIRException 
170   * @throws Exception
171   */
172  public <T extends Resource> T fetchResource(Class<T> class_, String uri);
173  public <T extends Resource> T fetchResourceWithException(Class<T> class_, String uri) throws FHIRException;
174
175  /**
176   * Variation of fetchResource when you have a string type, and don't need the right class
177   * 
178   * The URI can have one of 3 formats:
179   *  - a full URL e.g. http://acme.org/fhir/ValueSet/[id]
180   *  - a relative URL e.g. ValueSet/[id]
181   *  - a logical id e.g. [id]
182   *  
183   * if type == null, the URI can't be a simple logical id
184   * 
185   * @param type
186   * @param uri
187   * @return
188   */
189  public Resource fetchResourceById(String type, String uri);
190  
191  /**
192   * find whether a resource is available. 
193   * 
194   * Implementations of the interface can assume that if hasResource ruturns 
195   * true, the resource will usually be fetched subsequently
196   * 
197   * @param class_
198   * @param uri
199   * @return
200   */
201  public <T extends Resource> boolean hasResource(Class<T> class_, String uri);
202
203  /**
204   * cache a resource for later retrieval using fetchResource.
205   * 
206   * Note that various context implementations will have their own ways of loading
207   * rseources, and not all need implement cacheResource 
208   * @param res
209   * @throws FHIRException 
210   */
211  public void cacheResource(Resource res) throws FHIRException;
212  
213  // -- profile services ---------------------------------------------------------
214  
215  /**
216   * @return a list of the resource names defined for this version
217   */
218  public List<String> getResourceNames();
219  /**
220   * @return a set of the resource names defined for this version
221   */
222  public Set<String> getResourceNamesAsSet();
223
224  /**
225   * @return a list of the resource and type names defined for this version
226   */
227  public List<String> getTypeNames();
228  
229  /**
230   * @return a list of all structure definitions, with snapshots generated (if possible)
231   */
232  public List<StructureDefinition> allStructures();
233  
234  /**
235   * @return a list of all structure definitions, without trying to generate snapshots
236   */
237  public List<StructureDefinition> getStructures();
238  
239  /**
240   * @return a list of all conformance resources
241   */
242  public List<CanonicalResource> allConformanceResources();
243  
244  /**
245   * Given a structure definition, generate a snapshot (or regenerate it)
246   * @param p
247   * @throws DefinitionException
248   * @throws FHIRException
249   */
250  public void generateSnapshot(StructureDefinition p) throws DefinitionException, FHIRException;
251  public void generateSnapshot(StructureDefinition mr, boolean ifLogical);
252  
253  // -- Terminology services ------------------------------------------------------
254
255  /**
256   * Set the expansion parameters passed through the terminology server when txServer calls are made
257   * 
258   * Note that the Validation Options override these when they are specified on validateCode
259   */
260  public Parameters getExpansionParameters();
261
262  /**
263   * Get the expansion parameters passed through the terminology server when txServer calls are made
264   * 
265   * Note that the Validation Options override these when they are specified on validateCode
266   */
267  public void setExpansionProfile(Parameters expParameters);
268
269  // these are the terminology services used internally by the tools
270  /**
271   * Find the code system definition for the nominated system uri. 
272   * return null if there isn't one (then the tool might try 
273   * supportsSystem)
274   * 
275   * @param system
276   * @return
277   */
278  public CodeSystem fetchCodeSystem(String system);
279
280  /**
281   * True if the underlying terminology service provider will do 
282   * expansion and code validation for the terminology. Corresponds
283   * to the extension 
284   * 
285   * http://hl7.org/fhir/StructureDefinition/capabilitystatement-supported-system
286   * 
287   * in the Conformance resource
288   * 
289   * @param system
290   * @return
291   * @throws Exception 
292   */
293  public boolean supportsSystem(String system) throws TerminologyServiceException;
294
295  /**
296   * find concept maps for a source
297   * @param url
298   * @return
299   * @throws FHIRException 
300   */
301  public List<ConceptMap> findMapsForSource(String url) throws FHIRException;  
302
303  /**
304   * ValueSet Expansion - see $expand
305   *  
306   * @param source
307   * @return
308   */
309  public ValueSetExpansionOutcome expandVS(ValueSet source, boolean cacheOk, boolean heiarchical);
310  
311  /**
312   * ValueSet Expansion - see $expand, but resolves the binding first
313   *  
314   * @param source
315   * @return
316   * @throws FHIRException 
317   */
318  public ValueSetExpansionOutcome expandVS(ElementDefinitionBindingComponent binding, boolean cacheOk, boolean heiarchical) throws FHIRException;
319  
320  /**
321   * Value set expanion inside the internal expansion engine - used 
322   * for references to supported system (see "supportsSystem") for
323   * which there is no value set. 
324   * 
325   * @param inc
326   * @return
327   * @throws FHIRException 
328   */
329  public ValueSetExpansionOutcome expandVS(ConceptSetComponent inc, boolean hierarchical) throws TerminologyServiceException;
330  
331  public class ValidationResult {
332    private ConceptDefinitionComponent definition;
333    private IssueSeverity severity;
334    private String message;
335    private TerminologyServiceErrorClass errorClass;
336    private String txLink;
337    
338    public ValidationResult(IssueSeverity severity, String message) {
339      this.severity = severity;
340      this.message = message;
341    }
342    
343    public ValidationResult(ConceptDefinitionComponent definition) {
344      this.definition = definition;
345    }
346
347    public ValidationResult(IssueSeverity severity, String message, ConceptDefinitionComponent definition) {
348      this.severity = severity;
349      this.message = message;
350      this.definition = definition;
351    }
352    
353    public ValidationResult(IssueSeverity severity, String message, TerminologyServiceErrorClass errorClass) {
354      this.severity = severity;
355      this.message = message;
356      this.errorClass = errorClass;
357    }
358
359    public boolean isOk() {
360      return severity == null || severity == IssueSeverity.INFORMATION || severity == IssueSeverity.WARNING;
361    }
362
363    public String getDisplay() {
364// We don't want to return question-marks because that prevents something more useful from being displayed (e.g. the code) if there's no display value
365//      return definition == null ? "??" : definition.getDisplay();
366      return definition == null ? null : definition.getDisplay();
367    }
368
369    public ConceptDefinitionComponent asConceptDefinition() {
370      return definition;
371    }
372
373    public IssueSeverity getSeverity() {
374      return severity;
375    }
376
377    public String getMessage() {
378      return message;
379    }
380
381    public boolean IsNoService() {
382      return errorClass == TerminologyServiceErrorClass.NOSERVICE;
383    }
384
385    public TerminologyServiceErrorClass getErrorClass() {
386      return errorClass;
387    }
388
389    public ValidationResult setSeverity(IssueSeverity severity) {
390      this.severity = severity;
391      return this;
392    }
393
394    public ValidationResult setMessage(String message) {
395      this.message = message;
396      return this;
397    }
398
399    public String getTxLink() {
400      return txLink;
401    }
402
403    public ValidationResult setTxLink(String txLink) {
404      this.txLink = txLink;
405      return this;
406    }
407    
408    
409  }
410
411  /**
412   * Validation of a code - consult the terminology infrstructure and/or service 
413   * to see whether it is known. If known, return a description of it
414   * 
415   * note: always return a result, with either an error or a code description
416   *  
417   * corresponds to 2 terminology service calls: $validate-code and $lookup
418   * 
419   * in this case, the system will be inferred from the value set. It's an error to call this one without the value set
420   * 
421   * @param options - validation options (required)
422   * @param code he code to validate (required)
423   * @param vs the applicable valueset (required)
424   * @return
425   */
426  public ValidationResult validateCode(ValidationOptions options, String code, ValueSet vs);
427  
428  /**
429   * Validation of a code - consult the terminology infrstructure and/or service 
430   * to see whether it is known. If known, return a description of it
431   * 
432   * note: always return a result, with either an error or a code description
433   *  
434   * corresponds to 2 terminology service calls: $validate-code and $lookup
435   * 
436   * @param options - validation options (required)
437   * @param system - equals Coding.system (required)
438   * @param code - equals Coding.code (required)
439   * @param display - equals Coding.display (optional)
440   * @return
441   */
442  public ValidationResult validateCode(ValidationOptions options, String system, String code, String display);
443  
444  /**
445   * Validation of a code - consult the terminology infrstructure and/or service 
446   * to see whether it is known. If known, return a description of it
447   * 
448   * note: always return a result, with either an error or a code description
449   *  
450   * corresponds to 2 terminology service calls: $validate-code and $lookup
451   * 
452   * @param options - validation options (required)
453   * @param system - equals Coding.system (required)
454   * @param code - equals Coding.code (required)
455   * @param display - equals Coding.display (optional)
456   * @param vs the applicable valueset (optional)
457   * @return
458   */
459  public ValidationResult validateCode(ValidationOptions options, String system, String code, String display, ValueSet vs);
460
461  /**
462   * Validation of a code - consult the terminology infrstructure and/or service 
463   * to see whether it is known. If known, return a description of it
464   * 
465   * note: always return a result, with either an error or a code description
466   *  
467   * corresponds to 2 terminology service calls: $validate-code and $lookup
468   * 
469   * Note that this doesn't validate binding strength (e.g. is just text allowed?)
470   * 
471   * @param options - validation options (required)
472   * @param code - CodeableConcept to validate
473   * @param vs the applicable valueset (optional)
474   * @return
475   */
476  public ValidationResult validateCode(ValidationOptions options, CodeableConcept code, ValueSet vs);
477
478  /**
479   * Validation of a code - consult the terminology infrstructure and/or service 
480   * to see whether it is known. If known, return a description of it
481   * 
482   * note: always return a result, with either an error or a code description
483   *  
484   * corresponds to 2 terminology service calls: $validate-code and $lookup
485   * 
486   * in this case, the system will be inferred from the value set. It's an error to call this one without the value set
487   * 
488   * @param options - validation options (required)
489   * @param code - Coding to validate
490   * @param vs the applicable valueset (optional)
491   * @return
492   */
493  public ValidationResult validateCode(ValidationOptions options, Coding code, ValueSet vs);
494  
495  /**
496   * returns the recommended tla for the type  (from the structure definitions)
497   * 
498   * @param name
499   * @return
500   */
501  public String getAbbreviation(String name);
502
503
504  /**
505   * translate an OID to a URI (look through known NamingSystems)
506   * @param code
507   * @return
508   */
509        public String oid2Uri(String code);
510
511        /** 
512         * @return true if the contxt has a terminology caching service internally
513         */
514  public boolean hasCache();
515
516  public interface ILoggingService {
517    public enum LogCategory {
518      INIT, 
519      PROGRESS,
520      TX, 
521      CONTEXT, 
522      GENERATE,
523      HTML 
524    }
525    public void logMessage(String message); // status messages, always display
526    public void logDebugMessage(LogCategory category, String message); // verbose; only when debugging 
527  }
528
529  public void setLogger(ILoggingService logger);
530  public ILoggingService getLogger();
531
532  public boolean isNoTerminologyServer();
533
534  public TranslationServices translator();
535  public List<StructureMap> listTransforms();
536  public StructureMap getTransform(String url);
537
538  public String getOverrideVersionNs();
539  public void setOverrideVersionNs(String value);
540
541  public StructureDefinition fetchTypeDefinition(String typeName);
542
543  public void setUcumService(UcumService ucumService);
544
545  public String getLinkForUrl(String corePath, String s);
546  public Map<String, byte[]> getBinaries();
547
548
549}