001package org.hl7.fhir.r5.terminologies;
002
003/*-
004 * #%L
005 * org.hl7.fhir.r5
006 * %%
007 * Copyright (C) 2014 - 2019 Health Level 7
008 * %%
009 * Licensed under the Apache License, Version 2.0 (the "License");
010 * you may not use this file except in compliance with the License.
011 * You may obtain a copy of the License at
012 * 
013 *      http://www.apache.org/licenses/LICENSE-2.0
014 * 
015 * Unless required by applicable law or agreed to in writing, software
016 * distributed under the License is distributed on an "AS IS" BASIS,
017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
018 * See the License for the specific language governing permissions and
019 * limitations under the License.
020 * #L%
021 */
022
023
024import java.util.ArrayList;
025import java.util.HashMap;
026import java.util.List;
027import java.util.Map;
028
029import org.hl7.fhir.exceptions.FHIRException;
030import org.hl7.fhir.r5.context.IWorkerContext;
031import org.hl7.fhir.r5.context.IWorkerContext.ValidationResult;
032import org.hl7.fhir.r5.model.CanonicalType;
033import org.hl7.fhir.r5.model.CodeSystem;
034import org.hl7.fhir.r5.model.CodeSystem.CodeSystemContentMode;
035import org.hl7.fhir.r5.model.CodeSystem.ConceptDefinitionComponent;
036import org.hl7.fhir.r5.model.CodeSystem.ConceptDefinitionDesignationComponent;
037import org.hl7.fhir.r5.model.CodeableConcept;
038import org.hl7.fhir.r5.model.Coding;
039import org.hl7.fhir.r5.model.UriType;
040import org.hl7.fhir.r5.model.ValueSet;
041import org.hl7.fhir.r5.model.ValueSet.ConceptReferenceComponent;
042import org.hl7.fhir.r5.model.ValueSet.ConceptReferenceDesignationComponent;
043import org.hl7.fhir.r5.model.ValueSet.ConceptSetComponent;
044import org.hl7.fhir.r5.model.ValueSet.ConceptSetFilterComponent;
045import org.hl7.fhir.r5.model.ValueSet.ValueSetExpansionContainsComponent;
046import org.hl7.fhir.utilities.CommaSeparatedStringBuilder;
047import org.hl7.fhir.utilities.TerminologyServiceOptions;
048import org.hl7.fhir.utilities.validation.ValidationMessage.IssueSeverity;
049
050public class ValueSetCheckerSimple implements ValueSetChecker {
051
052  private ValueSet valueset;
053  private IWorkerContext context;
054  private Map<String, ValueSetCheckerSimple> inner = new HashMap<>();
055  private TerminologyServiceOptions options;
056
057  public ValueSetCheckerSimple(TerminologyServiceOptions options, ValueSet source, IWorkerContext context) {
058    this.valueset = source;
059    this.context = context;
060    this.options = options;
061  }
062
063  public ValidationResult validateCode(CodeableConcept code) throws FHIRException {
064    // first, we validate the codings themselves
065    List<String> errors = new ArrayList<String>();
066    List<String> warnings = new ArrayList<String>();
067    for (Coding c : code.getCoding()) {
068      if (!c.hasSystem())
069        warnings.add("Coding has no system");
070      CodeSystem cs = context.fetchCodeSystem(c.getSystem());
071      if (cs == null)
072        warnings.add("Unsupported system "+c.getSystem()+" - system is not specified or implicit");
073      else if (cs.getContent() != CodeSystemContentMode.COMPLETE)
074        warnings.add("Unable to resolve system "+c.getSystem()+" - system is not complete");
075      else {
076        ValidationResult res = validateCode(c, cs);
077        if (!res.isOk())
078          errors.add(res.getMessage());
079        else if (res.getMessage() != null)
080          warnings.add(res.getMessage());
081      }
082    }
083    if (valueset != null) {
084      boolean ok = false;
085      for (Coding c : code.getCoding()) {
086        ok = ok || codeInValueSet(c.getSystem(), c.getCode());
087      }
088      if (!ok)
089        errors.add(0, "None of the provided codes are in the value set "+valueset.getUrl());
090    }
091    if (errors.size() > 0)
092      return new ValidationResult(IssueSeverity.ERROR, errors.toString());
093    else if (warnings.size() > 0)
094      return new ValidationResult(IssueSeverity.WARNING, warnings.toString());
095    else 
096      return new ValidationResult(IssueSeverity.INFORMATION, null);
097  }
098
099  public ValidationResult validateCode(Coding code) throws FHIRException {
100    String warningMessage = null;
101    // first, we validate the concept itself
102    
103    String system = code.hasSystem() ? code.getSystem() : getValueSetSystem();
104    if (system == null && !code.hasDisplay()) { // dealing with just a plain code (enum)
105      system = systemForCodeInValueSet(code.getCode());
106    }
107    if (!code.hasSystem())
108      code.setSystem(system);
109    boolean inExpansion = checkExpansion(code);
110    CodeSystem cs = context.fetchCodeSystem(system);
111    if (cs == null) {
112      warningMessage = "Unable to resolve system "+system+" - system is not specified or implicit";
113      if (!inExpansion)
114        throw new FHIRException(warningMessage);
115    }
116    if (cs!=null && cs.getContent() != CodeSystemContentMode.COMPLETE) {
117      warningMessage = "Unable to resolve system "+system+" - system is not complete";
118      if (!inExpansion)
119        throw new FHIRException(warningMessage);
120    }
121    
122    ValidationResult res =null;
123    if (cs!=null)
124      res = validateCode(code, cs);
125      
126    // then, if we have a value set, we check it's in the value set
127    if ((res==null || res.isOk()) && valueset != null && !codeInValueSet(system, code.getCode())) {
128      if (!inExpansion)
129        res.setMessage("Not in value set "+valueset.getUrl()).setSeverity(IssueSeverity.ERROR);
130      else if (warningMessage!=null)
131        res = new ValidationResult(IssueSeverity.WARNING, "Code found in expansion, however: " + warningMessage);
132      else
133        res.setMessage("Code found in expansion, however: " + res.getMessage());
134    }
135    return res;
136  }
137
138  boolean checkExpansion(Coding code) {
139    if (valueset==null || !valueset.hasExpansion())
140      return false;
141    return checkExpansion(code, valueset.getExpansion().getContains());
142  }
143
144  boolean checkExpansion(Coding code, List<ValueSetExpansionContainsComponent> contains) {
145    for (ValueSetExpansionContainsComponent containsComponent: contains) {
146      if (containsComponent.getSystem().equals(code.getSystem()) && containsComponent.getCode().equals(code.getCode()))
147        return true;
148      if (containsComponent.hasContains() && checkExpansion(code, containsComponent.getContains()))
149        return true;
150    }
151    return false;
152  }
153
154  private ValidationResult validateCode(Coding code, CodeSystem cs) {
155    ConceptDefinitionComponent cc = findCodeInConcept(cs.getConcept(), code.getCode());
156    if (cc == null)
157      return new ValidationResult(IssueSeverity.ERROR, "Unknown Code "+gen(code)+" in "+cs.getUrl());
158    if (code.getDisplay() == null)
159      return new ValidationResult(cc);
160    CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder();
161    if (cc.hasDisplay()) {
162      b.append(cc.getDisplay());
163      if (code.getDisplay().equalsIgnoreCase(cc.getDisplay()))
164        return new ValidationResult(cc);
165    }
166    for (ConceptDefinitionDesignationComponent ds : cc.getDesignation()) {
167      b.append(ds.getValue());
168      if (code.getDisplay().equalsIgnoreCase(ds.getValue()))
169        return new ValidationResult(cc);
170    }
171    // also check to see if the value set has another display
172    ConceptReferenceComponent vs = findValueSetRef(code.getSystem(), code.getCode());
173    if (vs != null && (vs.hasDisplay() ||vs.hasDesignation())) {
174      if (vs.hasDisplay()) {
175        b.append(vs.getDisplay());
176        if (code.getDisplay().equalsIgnoreCase(vs.getDisplay()))
177          return new ValidationResult(cc);
178      }
179      for (ConceptReferenceDesignationComponent ds : vs.getDesignation()) {
180        b.append(ds.getValue());
181        if (code.getDisplay().equalsIgnoreCase(ds.getValue()))
182          return new ValidationResult(cc);
183      }
184    }
185    return new ValidationResult(IssueSeverity.WARNING, "Display Name for "+code.getSystem()+"#"+code.getCode()+" should be one of '"+b.toString()+"'", cc);
186  }
187
188  private ConceptReferenceComponent findValueSetRef(String system, String code) {
189    if (valueset == null)
190      return null;
191    // if it has an expansion
192    for (ValueSetExpansionContainsComponent exp : valueset.getExpansion().getContains()) {
193      if (system.equals(exp.getSystem()) && code.equals(exp.getCode())) {
194        ConceptReferenceComponent cc = new ConceptReferenceComponent();
195        cc.setDisplay(exp.getDisplay());
196        cc.setDesignation(exp.getDesignation());
197        return cc;
198      }
199    }
200    for (ConceptSetComponent inc : valueset.getCompose().getInclude()) {
201      if (system.equals(inc.getSystem())) {
202        for (ConceptReferenceComponent cc : inc.getConcept()) {
203          if (cc.getCode().equals(code))
204            return cc;
205        }
206      }
207      for (CanonicalType url : inc.getValueSet()) {
208        ConceptReferenceComponent cc = getVs(url.asStringValue()).findValueSetRef(system, code);
209        if (cc != null)
210          return cc;
211      }
212    }
213    return null;
214  }
215
216  private String gen(Coding code) {
217    if (code.hasSystem())
218      return code.getSystem()+"#"+code.getCode();
219    else
220      return null;
221  }
222
223  private String getValueSetSystem() throws FHIRException {
224    if (valueset == null)
225      throw new FHIRException("Unable to resolve system - no value set");
226    if (valueset.getCompose().hasExclude())
227      throw new FHIRException("Unable to resolve system - value set has excludes");
228    if (valueset.getCompose().getInclude().size() == 0) {
229      if (!valueset.hasExpansion() || valueset.getExpansion().getContains().size() == 0)
230        throw new FHIRException("Unable to resolve system - value set has no includes or expansion");
231      else {
232        String cs = valueset.getExpansion().getContains().get(0).getSystem();
233        if (cs != null && checkSystem(valueset.getExpansion().getContains(), cs))
234          return cs;
235        else
236          throw new FHIRException("Unable to resolve system - value set expansion has multiple systems");
237      }
238    }
239    for (ConceptSetComponent inc : valueset.getCompose().getInclude()) {
240      if (inc.hasValueSet())
241        throw new FHIRException("Unable to resolve system - value set has imports");
242      if (!inc.hasSystem())
243        throw new FHIRException("Unable to resolve system - value set has include with no system");
244    }
245    if (valueset.getCompose().getInclude().size() == 1)
246      return valueset.getCompose().getInclude().get(0).getSystem();
247    
248    return null;
249  }
250
251  /*
252   * Check that all system values within an expansion correspond to the specified system value
253   */
254  private boolean checkSystem(List<ValueSetExpansionContainsComponent> containsList, String system) {
255    for (ValueSetExpansionContainsComponent contains : containsList) {
256      if (!contains.getSystem().equals(system) || (contains.hasContains() && !checkSystem(contains.getContains(), system)))
257        return false;
258    }
259    return true;
260  }
261  private ConceptDefinitionComponent findCodeInConcept(List<ConceptDefinitionComponent> concept, String code) {
262    for (ConceptDefinitionComponent cc : concept) {
263      if (code.equals(cc.getCode()))
264        return cc;
265      ConceptDefinitionComponent c = findCodeInConcept(cc.getConcept(), code);
266      if (c != null)
267        return c;
268    }
269    return null;
270  }
271
272  
273  private String systemForCodeInValueSet(String code) {
274    String sys = null;
275    if (valueset.hasCompose()) {
276      if (valueset.getCompose().hasExclude())
277        return null;
278      for (ConceptSetComponent vsi : valueset.getCompose().getInclude()) {
279        if (vsi.hasValueSet())
280          return null;
281        if (!vsi.hasSystem()) 
282          return null;
283        if (vsi.hasFilter())
284          return null;
285        CodeSystem cs = context.fetchCodeSystem(vsi.getSystem());
286        if (cs == null)
287          return null;
288        if (vsi.hasConcept()) {
289          for (ConceptReferenceComponent cc : vsi.getConcept()) {
290            boolean match = cs.getCaseSensitive() ? cc.getCode().equals(code) : cc.getCode().equalsIgnoreCase(code);
291            if (match) {
292              if (sys == null)
293                sys = vsi.getSystem();
294              else if (!sys.equals(vsi.getSystem()))
295                return null;
296            }
297          }
298        } else {
299          ConceptDefinitionComponent cc = findCodeInConcept(cs.getConcept(), code);
300          if (cc != null) {
301            if (sys == null)
302              sys = vsi.getSystem();
303            else if (!sys.equals(vsi.getSystem()))
304              return null;
305          }
306        }
307      }
308    }
309    
310    return sys;  
311  }
312  
313  @Override
314  public boolean codeInValueSet(String system, String code) throws FHIRException {
315    if (valueset.hasExpansion()) {
316      return checkExpansion(new Coding(system, code, null));
317    } else if (valueset.hasCompose()) {
318      boolean ok = false;
319      for (ConceptSetComponent vsi : valueset.getCompose().getInclude()) {
320        ok = ok || inComponent(vsi, system, code, valueset.getCompose().getInclude().size() == 1);
321      }
322      for (ConceptSetComponent vsi : valueset.getCompose().getExclude()) {
323        ok = ok && !inComponent(vsi, system, code, valueset.getCompose().getInclude().size() == 1);
324      }
325      return ok;
326    } 
327    
328    return false;
329  }
330
331  private boolean inComponent(ConceptSetComponent vsi, String system, String code, boolean only) throws FHIRException {
332    for (UriType uri : vsi.getValueSet()) {
333      if (inImport(uri.getValue(), system, code))
334        return true;
335    }
336
337    if (!vsi.hasSystem())
338      return false;
339    
340    if (only && system == null) {
341      // whether we know the system or not, we'll accept the stated codes at face value
342      for (ConceptReferenceComponent cc : vsi.getConcept())
343        if (cc.getCode().equals(code)) 
344          return true;
345    }
346    
347    if (!system.equals(vsi.getSystem()))
348      return false;
349    if (vsi.hasFilter()) {
350      boolean ok = true;
351      for (ConceptSetFilterComponent f : vsi.getFilter())
352        if (!codeInFilter(system, f, code)) {
353          ok = false;
354          break;
355        }
356      if (ok)
357        return true;
358    }
359
360    CodeSystem def = context.fetchCodeSystem(system);
361    if (def.getContent() != CodeSystemContentMode.COMPLETE) 
362      throw new FHIRException("Unable to resolve system "+vsi.getSystem()+" - system is not complete");
363    
364    List<ConceptDefinitionComponent> list = def.getConcept();
365    boolean ok = validateCodeInConceptList(code, def, list);
366    if (ok && vsi.hasConcept()) {
367      for (ConceptReferenceComponent cc : vsi.getConcept())
368        if (cc.getCode().equals(code)) 
369          return true;
370      return false;
371    } else
372      return ok;
373  }
374
375  private boolean codeInFilter(String system, ConceptSetFilterComponent f, String code) throws FHIRException {
376    CodeSystem cs = context.fetchCodeSystem(system);
377    if (cs == null)
378      throw new FHIRException("Unable to evaluate filters on unknown code system '"+system+"'");
379    if ("concept".equals(f.getProperty()))
380      return codeInConceptFilter(cs, f, code);
381    else {
382      System.out.println("todo: handle filters with property = "+f.getProperty()); 
383      throw new FHIRException("Unable to handle system "+cs.getUrl()+" filter with property = "+f.getProperty());
384    }
385  }
386
387  private boolean codeInConceptFilter(CodeSystem cs, ConceptSetFilterComponent f, String code) throws FHIRException {
388    switch (f.getOp()) {
389    case ISA: return codeInConceptIsAFilter(cs, f, code);
390    case ISNOTA: return !codeInConceptIsAFilter(cs, f, code);
391    default:
392      System.out.println("todo: handle concept filters with op = "+f.getOp()); 
393      throw new FHIRException("Unable to handle system "+cs.getUrl()+" concept filter with op = "+f.getOp());
394    }
395  }
396
397  private boolean codeInConceptIsAFilter(CodeSystem cs, ConceptSetFilterComponent f, String code) {
398    if (code.equals(f.getProperty()))
399      return true;
400   ConceptDefinitionComponent cc = findCodeInConcept(cs.getConcept(), f.getValue());
401   if (cc == null)
402     return false;
403   cc = findCodeInConcept(cc.getConcept(), code);
404   return cc != null;
405  }
406
407  public boolean validateCodeInConceptList(String code, CodeSystem def, List<ConceptDefinitionComponent> list) {
408    if (def.getCaseSensitive()) {
409      for (ConceptDefinitionComponent cc : list) {
410        if (cc.getCode().equals(code)) 
411          return true;
412        if (cc.hasConcept() && validateCodeInConceptList(code, def, cc.getConcept()))
413          return true;
414      }
415    } else {
416      for (ConceptDefinitionComponent cc : list) {
417        if (cc.getCode().equalsIgnoreCase(code)) 
418          return true;
419        if (cc.hasConcept() && validateCodeInConceptList(code, def, cc.getConcept()))
420          return true;
421      }
422    }
423    return false;
424  }
425
426  private ValueSetCheckerSimple getVs(String url) {
427    if (inner.containsKey(url)) {
428      return inner.get(url);
429    }
430    ValueSet vs = context.fetchResource(ValueSet.class, url);
431    ValueSetCheckerSimple vsc = new ValueSetCheckerSimple(options, vs, context);
432    inner.put(url, vsc);
433    return vsc;
434  }
435  
436  private boolean inImport(String uri, String system, String code) throws FHIRException {
437    return getVs(uri).codeInValueSet(system, code);
438  }
439
440}