001package org.hl7.fhir.dstu3.hapi.ctx;
002
003import ca.uhn.fhir.context.FhirContext;
004import ca.uhn.fhir.rest.api.Constants;
005import ca.uhn.fhir.rest.server.exceptions.InternalErrorException;
006import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;
007import ca.uhn.fhir.util.CoverageIgnore;
008import com.github.benmanes.caffeine.cache.Cache;
009import com.github.benmanes.caffeine.cache.Caffeine;
010import org.apache.commons.lang3.Validate;
011import org.apache.commons.lang3.time.DateUtils;
012import org.hl7.fhir.dstu3.context.IWorkerContext;
013import org.hl7.fhir.dstu3.formats.IParser;
014import org.hl7.fhir.dstu3.formats.ParserType;
015import org.hl7.fhir.dstu3.model.*;
016import org.hl7.fhir.dstu3.model.CodeSystem.ConceptDefinitionComponent;
017import org.hl7.fhir.dstu3.model.ValueSet.ConceptReferenceComponent;
018import org.hl7.fhir.dstu3.model.ValueSet.ConceptSetComponent;
019import org.hl7.fhir.dstu3.model.ValueSet.ValueSetExpansionComponent;
020import org.hl7.fhir.dstu3.model.ValueSet.ValueSetExpansionContainsComponent;
021import org.hl7.fhir.dstu3.terminologies.ValueSetExpander;
022import org.hl7.fhir.dstu3.terminologies.ValueSetExpanderFactory;
023import org.hl7.fhir.dstu3.terminologies.ValueSetExpanderSimple;
024import org.hl7.fhir.dstu3.utils.INarrativeGenerator;
025import org.hl7.fhir.exceptions.FHIRException;
026import org.hl7.fhir.exceptions.TerminologyServiceException;
027import org.hl7.fhir.utilities.validation.ValidationMessage.IssueSeverity;
028
029import java.util.*;
030import java.util.concurrent.TimeUnit;
031
032import static org.apache.commons.lang3.StringUtils.isBlank;
033import static org.apache.commons.lang3.StringUtils.isNotBlank;
034
035public final class HapiWorkerContext implements IWorkerContext, ValueSetExpander, ValueSetExpanderFactory {
036  private final FhirContext myCtx;
037  private final Cache<String, Resource> myFetchedResourceCache;
038
039  private IValidationSupport myValidationSupport;
040  private ExpansionProfile myExpansionProfile;
041
042  public HapiWorkerContext(FhirContext theCtx, IValidationSupport theValidationSupport) {
043    Validate.notNull(theCtx, "theCtx must not be null");
044    Validate.notNull(theValidationSupport, "theValidationSupport must not be null");
045    myCtx = theCtx;
046    myValidationSupport = theValidationSupport;
047
048    long timeoutMillis = 10 * DateUtils.MILLIS_PER_SECOND;
049    if (System.getProperties().containsKey(Constants.TEST_SYSTEM_PROP_VALIDATION_RESOURCE_CACHES_MS)) {
050      timeoutMillis = Long.parseLong(System.getProperty(Constants.TEST_SYSTEM_PROP_VALIDATION_RESOURCE_CACHES_MS));
051    }
052    myFetchedResourceCache = Caffeine.newBuilder().expireAfterWrite(timeoutMillis, TimeUnit.MILLISECONDS).build();
053  }
054
055  @Override
056  @CoverageIgnore
057  public List<MetadataResource> allConformanceResources() {
058    throw new UnsupportedOperationException();
059  }
060
061  @Override
062  public List<StructureDefinition> allStructures() {
063    return myValidationSupport.fetchAllStructureDefinitions(myCtx);
064  }
065
066  @Override
067  public ValueSetExpansionOutcome expand(ValueSet theSource, ExpansionProfile theProfile) {
068    ValueSetExpansionOutcome vso;
069    try {
070      vso = getExpander().expand(theSource, theProfile);
071    } catch (InvalidRequestException e) {
072      throw e;
073    } catch (TerminologyServiceException e) {
074      throw new InvalidRequestException(e.getMessage(), e);
075    } catch (Exception e) {
076      throw new InternalErrorException(e);
077    }
078    if (vso.getError() != null) {
079      throw new InvalidRequestException(vso.getError());
080    } else {
081      return vso;
082    }
083  }
084
085  @Override
086  public ValueSetExpansionOutcome expandVS(ValueSet theSource, boolean theCacheOk, boolean theHeiarchical) {
087    throw new UnsupportedOperationException();
088  }
089
090  @Override
091  public ValueSetExpansionComponent expandVS(ConceptSetComponent theInc, boolean theHeiarchical) {
092    return myValidationSupport.expandValueSet(myCtx, theInc);
093  }
094
095  @Override
096  public StructureDefinition fetchTypeDefinition(String theCode) {
097    throw new UnsupportedOperationException();
098  }
099
100  @Override
101  public CodeSystem fetchCodeSystem(String theSystem) {
102    if (myValidationSupport == null) {
103      return null;
104    } else {
105      return myValidationSupport.fetchCodeSystem(myCtx, theSystem);
106    }
107  }
108
109  @Override
110  public <T extends Resource> T fetchResource(Class<T> theClass, String theUri) {
111    if (myValidationSupport == null) {
112      return null;
113    } else {
114      @SuppressWarnings("unchecked")
115      T retVal = (T) myFetchedResourceCache.get(theUri, t->{
116        return myValidationSupport.fetchResource(myCtx, theClass, theUri);
117      });
118      return retVal;
119    }
120  }
121
122  @Override
123  public <T extends Resource> T fetchResourceWithException(Class<T> theClass_, String theUri) throws FHIRException {
124    T retVal = fetchResource(theClass_, theUri);
125    if (retVal == null) {
126      throw new FHIRException("Unable to fetch " + theUri);
127    }
128    return retVal;
129  }
130
131  @Override
132  public List<ConceptMap> findMapsForSource(String theUrl) {
133    throw new UnsupportedOperationException();
134  }
135
136  @Override
137  public String getAbbreviation(String theName) {
138    throw new UnsupportedOperationException();
139  }
140
141  @Override
142  public ValueSetExpander getExpander() {
143    ValueSetExpanderSimple retVal = new ValueSetExpanderSimple(this, this);
144    retVal.setMaxExpansionSize(Integer.MAX_VALUE);
145    return retVal;
146  }
147
148  @Override
149  public ExpansionProfile getExpansionProfile() {
150    return myExpansionProfile;
151  }
152
153  @Override
154  public void setExpansionProfile(ExpansionProfile theExpProfile) {
155    myExpansionProfile = theExpProfile;
156  }
157
158  @Override
159  public INarrativeGenerator getNarrativeGenerator(String thePrefix, String theBasePath) {
160    throw new UnsupportedOperationException();
161  }
162
163  @Override
164  public IParser getParser(ParserType theType) {
165    throw new UnsupportedOperationException();
166  }
167
168  @Override
169  public IParser getParser(String theType) {
170    throw new UnsupportedOperationException();
171  }
172
173  @Override
174  public List<String> getResourceNames() {
175    List<String> result = new ArrayList<String>();
176    for (ResourceType next : ResourceType.values()) {
177      result.add(next.name());
178    }
179    Collections.sort(result);
180    return result;
181  }
182
183  @Override
184  public List<String> getTypeNames() {
185    throw new UnsupportedOperationException();
186  }
187
188  @Override
189  public String getVersion() {
190    return myCtx.getVersion().getVersion().getFhirVersionString();
191  }
192
193  @Override
194  @CoverageIgnore
195  public boolean hasCache() {
196    throw new UnsupportedOperationException();
197  }
198
199  @Override
200  public <T extends Resource> boolean hasResource(Class<T> theClass_, String theUri) {
201    throw new UnsupportedOperationException();
202  }
203
204  @Override
205  public boolean isNoTerminologyServer() {
206    return false;
207  }
208
209  @Override
210  public IParser newJsonParser() {
211    throw new UnsupportedOperationException();
212  }
213
214  @Override
215  public IParser newXmlParser() {
216    throw new UnsupportedOperationException();
217  }
218
219  @Override
220  public String oid2Uri(String theCode) {
221    throw new UnsupportedOperationException();
222  }
223
224  @Override
225  public void setLogger(ILoggingService theLogger) {
226    throw new UnsupportedOperationException();
227  }
228
229  @Override
230  public boolean supportsSystem(String theSystem) {
231    if (myValidationSupport == null) {
232      return false;
233    } else {
234      return myValidationSupport.isCodeSystemSupported(myCtx, theSystem);
235    }
236  }
237
238  @Override
239  public Set<String> typeTails() {
240    return new HashSet<String>(Arrays.asList("Integer", "UnsignedInt", "PositiveInt", "Decimal", "DateTime", "Date", "Time", "Instant", "String", "Uri", "Oid", "Uuid", "Id", "Boolean", "Code",
241      "Markdown", "Base64Binary", "Coding", "CodeableConcept", "Attachment", "Identifier", "Quantity", "SampledData", "Range", "Period", "Ratio", "HumanName", "Address", "ContactPoint",
242      "Timing", "Reference", "Annotation", "Signature", "Meta"));
243  }
244
245  @Override
246  public ValidationResult validateCode(CodeableConcept theCode, ValueSet theVs) {
247    for (Coding next : theCode.getCoding()) {
248      ValidationResult retVal = validateCode(next, theVs);
249      if (retVal != null && retVal.isOk()) {
250        return retVal;
251      }
252    }
253
254    return new ValidationResult(IssueSeverity.ERROR, null);
255  }
256
257  @Override
258  public ValidationResult validateCode(Coding theCode, ValueSet theVs) {
259    String system = theCode.getSystem();
260    String code = theCode.getCode();
261    String display = theCode.getDisplay();
262    return validateCode(system, code, display, theVs);
263  }
264
265  @Override
266  public ValidationResult validateCode(String theSystem, String theCode, String theDisplay) {
267    IValidationSupport.CodeValidationResult result = myValidationSupport.validateCode(myCtx, theSystem, theCode, theDisplay);
268    if (result == null) {
269      return null;
270    }
271    return new ValidationResult(result.getSeverity(), result.getMessage(), result.asConceptDefinition());
272  }
273
274  @Override
275  public ValidationResult validateCode(String theSystem, String theCode, String theDisplay, ConceptSetComponent theVsi) {
276    throw new UnsupportedOperationException();
277  }
278
279  @Override
280  public ValidationResult validateCode(String theSystem, String theCode, String theDisplay, ValueSet theVs) {
281
282    if (theVs != null && isNotBlank(theCode)) {
283      for (ConceptSetComponent next : theVs.getCompose().getInclude()) {
284        if (isBlank(theSystem) || theSystem.equals(next.getSystem())) {
285          for (ConceptReferenceComponent nextCode : next.getConcept()) {
286            if (theCode.equals(nextCode.getCode())) {
287              CodeType code = new CodeType(theCode);
288              return new ValidationResult(new ConceptDefinitionComponent(code));
289            }
290          }
291        }
292      }
293    }
294
295
296    boolean caseSensitive = true;
297    if (isNotBlank(theSystem)) {
298      CodeSystem system = fetchCodeSystem(theSystem);
299      if (system == null) {
300        return new ValidationResult(IssueSeverity.INFORMATION, "Code " + theSystem + "/" + theCode + " was not validated because the code system is not present");
301      }
302
303      if (system.hasCaseSensitive()) {
304        caseSensitive = system.getCaseSensitive();
305      }
306    }
307
308    String wantCode = theCode;
309    if (!caseSensitive) {
310      wantCode = wantCode.toUpperCase();
311    }
312
313    ValueSetExpansionOutcome expandedValueSet = null;
314
315    /*
316     * The following valueset is a special case, since the BCP codesystem is very difficult to expand
317     */
318    if (theVs != null && "http://hl7.org/fhir/ValueSet/languages".equals(theVs.getId())) {
319      ValueSet expansion = new ValueSet();
320      for (ConceptSetComponent nextInclude : theVs.getCompose().getInclude()) {
321        for (ConceptReferenceComponent nextConcept : nextInclude.getConcept()) {
322          expansion.getExpansion().addContains().setCode(nextConcept.getCode()).setDisplay(nextConcept.getDisplay());
323        }
324      }
325      expandedValueSet = new ValueSetExpansionOutcome(expansion);
326    }
327
328    if (expandedValueSet == null) {
329      expandedValueSet = expand(theVs, null);
330    }
331
332    for (ValueSetExpansionContainsComponent next : expandedValueSet.getValueset().getExpansion().getContains()) {
333      String nextCode = next.getCode();
334      if (!caseSensitive) {
335        nextCode = nextCode.toUpperCase();
336      }
337
338      if (nextCode.equals(wantCode)) {
339        if (theSystem == null || next.getSystem().equals(theSystem)) {
340          ConceptDefinitionComponent definition = new ConceptDefinitionComponent();
341          definition.setCode(next.getCode());
342          definition.setDisplay(next.getDisplay());
343          ValidationResult retVal = new ValidationResult(definition);
344          return retVal;
345        }
346      }
347    }
348
349    return new ValidationResult(IssueSeverity.ERROR, "Unknown code[" + theCode + "] in system[" + theSystem + "]");
350  }
351
352}