001package org.hl7.fhir.r5.context;
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
023import java.io.FileNotFoundException;
024import java.io.IOException;
025import java.util.ArrayList;
026import java.util.Collections;
027import java.util.Comparator;
028import java.util.Date;
029import java.util.HashMap;
030import java.util.HashSet;
031import java.util.List;
032import java.util.Map;
033import java.util.Set;
034
035import org.apache.commons.lang3.StringUtils;
036import org.fhir.ucum.UcumService;
037import org.hl7.fhir.exceptions.DefinitionException;
038import org.hl7.fhir.exceptions.FHIRException;
039import org.hl7.fhir.exceptions.TerminologyServiceException;
040import org.hl7.fhir.r5.conformance.ProfileUtilities;
041import org.hl7.fhir.r5.context.BaseWorkerContext.MetadataResourceVersionComparator;
042import org.hl7.fhir.r5.context.IWorkerContext.ILoggingService.LogCategory;
043import org.hl7.fhir.r5.context.TerminologyCache.CacheToken;
044import org.hl7.fhir.r5.model.BooleanType;
045import org.hl7.fhir.r5.model.CapabilityStatement;
046import org.hl7.fhir.r5.model.CodeSystem;
047import org.hl7.fhir.r5.model.CodeSystem.CodeSystemContentMode;
048import org.hl7.fhir.r5.model.CodeSystem.ConceptDefinitionComponent;
049import org.hl7.fhir.r5.model.CodeableConcept;
050import org.hl7.fhir.r5.model.Coding;
051import org.hl7.fhir.r5.model.ConceptMap;
052import org.hl7.fhir.r5.model.Constants;
053import org.hl7.fhir.r5.model.ElementDefinition.ElementDefinitionBindingComponent;
054import org.hl7.fhir.r5.model.ImplementationGuide;
055import org.hl7.fhir.r5.model.MetadataResource;
056import org.hl7.fhir.r5.model.NamingSystem;
057import org.hl7.fhir.r5.model.NamingSystem.NamingSystemIdentifierType;
058import org.hl7.fhir.r5.model.NamingSystem.NamingSystemUniqueIdComponent;
059import org.hl7.fhir.r5.model.OperationDefinition;
060import org.hl7.fhir.r5.model.Parameters;
061import org.hl7.fhir.r5.model.Parameters.ParametersParameterComponent;
062import org.hl7.fhir.r5.model.PlanDefinition;
063import org.hl7.fhir.r5.model.Questionnaire;
064import org.hl7.fhir.r5.model.Reference;
065import org.hl7.fhir.r5.model.Resource;
066import org.hl7.fhir.r5.model.SearchParameter;
067import org.hl7.fhir.r5.model.StringType;
068import org.hl7.fhir.r5.model.StructureDefinition;
069import org.hl7.fhir.r5.model.StructureMap;
070import org.hl7.fhir.r5.model.TerminologyCapabilities;
071import org.hl7.fhir.r5.model.TerminologyCapabilities.TerminologyCapabilitiesCodeSystemComponent;
072import org.hl7.fhir.r5.model.ValueSet;
073import org.hl7.fhir.r5.model.ValueSet.ConceptSetComponent;
074import org.hl7.fhir.r5.model.ValueSet.ValueSetComposeComponent;
075import org.hl7.fhir.r5.terminologies.TerminologyClient;
076import org.hl7.fhir.r5.terminologies.ValueSetCheckerSimple;
077import org.hl7.fhir.r5.terminologies.ValueSetExpander.TerminologyServiceErrorClass;
078import org.hl7.fhir.r5.terminologies.ValueSetExpander.ValueSetExpansionOutcome;
079import org.hl7.fhir.r5.terminologies.ValueSetExpanderSimple;
080import org.hl7.fhir.r5.utils.ToolingExtensions;
081import org.hl7.fhir.utilities.OIDUtils;
082import org.hl7.fhir.utilities.TerminologyServiceOptions;
083import org.hl7.fhir.utilities.TranslationServices;
084import org.hl7.fhir.utilities.Utilities;
085import org.hl7.fhir.utilities.VersionUtilities;
086import org.hl7.fhir.utilities.validation.ValidationMessage.IssueSeverity;
087import org.hl7.fhir.utilities.validation.ValidationMessage.IssueType;
088
089import com.google.gson.JsonObject;
090
091public abstract class BaseWorkerContext implements IWorkerContext {
092
093  public class MetadataResourceVersionComparator<T extends MetadataResource> implements Comparator<T> {
094
095    private List<T> list;
096
097    public MetadataResourceVersionComparator(List<T> list) {
098      this.list = list;
099    }
100
101    @Override
102    public int compare(T arg1, T arg2) {
103      String v1 = arg1.getVersion();
104      String v2 = arg2.getVersion();
105      if (v1 == null && v2 == null) {
106        return Integer.compare(list.indexOf(arg1), list.indexOf(arg2)); // retain original order
107      } else if (v1 == null) {
108        return -1;
109      } else if (v2 == null) {
110        return 1;
111      } else {
112        String mm1 = VersionUtilities.getMajMin(v1);
113        String mm2 = VersionUtilities.getMajMin(v2);
114        if (mm1 == null || mm2 == null) {
115          return v1.compareTo(v2);
116        } else {
117          return mm1.compareTo(mm2);
118        }
119      }
120    }
121  }
122
123  private Object lock = new Object(); // used as a lock for the data that follows
124  
125  private Map<String, Map<String, Resource>> allResourcesById = new HashMap<String, Map<String, Resource>>();
126  // all maps are to the full URI
127  private MetadataResourceManager<CodeSystem> codeSystems = new MetadataResourceManager<CodeSystem>();
128  private Set<String> supportedCodeSystems = new HashSet<String>();
129  private MetadataResourceManager<ValueSet> valueSets = new MetadataResourceManager<ValueSet>();
130  private MetadataResourceManager<ConceptMap> maps = new MetadataResourceManager<ConceptMap>();
131  protected MetadataResourceManager<StructureMap> transforms = new MetadataResourceManager<StructureMap>();
132  private MetadataResourceManager<StructureDefinition> structures = new MetadataResourceManager<StructureDefinition>();
133  private MetadataResourceManager<ImplementationGuide> guides = new MetadataResourceManager<ImplementationGuide>();
134  private MetadataResourceManager<CapabilityStatement> capstmts = new MetadataResourceManager<CapabilityStatement>();
135  private MetadataResourceManager<SearchParameter> searchParameters = new MetadataResourceManager<SearchParameter>();
136  private MetadataResourceManager<Questionnaire> questionnaires = new MetadataResourceManager<Questionnaire>();
137  private MetadataResourceManager<OperationDefinition> operations = new MetadataResourceManager<OperationDefinition>();
138  private MetadataResourceManager<PlanDefinition> plans = new MetadataResourceManager<PlanDefinition>();
139  private List<NamingSystem> systems = new ArrayList<NamingSystem>();
140  private UcumService ucumService;
141  
142  protected Map<String, Map<String, ValidationResult>> validationCache = new HashMap<String, Map<String,ValidationResult>>();
143  protected String tsServer;
144  protected String name;
145  private boolean allowLoadingDuplicates;
146
147  protected TerminologyClient txClient;
148  protected HTMLClientLogger txLog;
149  private TerminologyCapabilities txcaps;
150  private boolean canRunWithoutTerminology;
151  protected boolean noTerminologyServer;
152  private int expandCodesLimit = 1000;
153  protected ILoggingService logger;
154  protected Parameters expParameters;
155  private TranslationServices translator = new NullTranslator();
156  protected TerminologyCache txCache;
157
158  private boolean tlogging = true;
159  
160  public BaseWorkerContext() throws FileNotFoundException, IOException, FHIRException {
161    super();
162    txCache = new TerminologyCache(lock, null);
163  }
164
165  public BaseWorkerContext(MetadataResourceManager<CodeSystem> codeSystems, MetadataResourceManager<ValueSet> valueSets, MetadataResourceManager<ConceptMap> maps, MetadataResourceManager<StructureDefinition> profiles, 
166      MetadataResourceManager<ImplementationGuide> guides) throws FileNotFoundException, IOException, FHIRException {
167    super();
168    this.codeSystems = codeSystems;
169    this.valueSets = valueSets;
170    this.maps = maps;
171    this.structures = profiles;
172    this.guides = guides;
173    txCache = new TerminologyCache(lock, null);
174  }
175
176  protected void copy(BaseWorkerContext other) {
177    synchronized (other.lock) { // tricky, because you need to lock this as well, but it's really not in use yet 
178      allResourcesById.putAll(other.allResourcesById);
179      translator = other.translator;
180      codeSystems.copy(other.codeSystems);
181      txcaps = other.txcaps;
182      valueSets.copy(other.valueSets);
183      maps.copy(other.maps);
184      transforms.copy(other.transforms);
185      structures.copy(other.structures);
186      searchParameters.copy(other.searchParameters);
187      plans.copy(other.plans);
188      questionnaires.copy(other.questionnaires);
189      operations.copy(other.operations);
190      systems.addAll(other.systems);
191      guides.copy(other.guides);
192      capstmts.copy(other.capstmts);
193
194      allowLoadingDuplicates = other.allowLoadingDuplicates;
195      tsServer = other.tsServer;
196      name = other.name;
197      txClient = other.txClient;
198      txLog = other.txLog;
199      txcaps = other.txcaps;
200      canRunWithoutTerminology = other.canRunWithoutTerminology;
201      noTerminologyServer = other.noTerminologyServer;
202      if (other.txCache != null)
203        txCache = other.txCache.copy();
204      expandCodesLimit = other.expandCodesLimit;
205      logger = other.logger;
206      expParameters = other.expParameters;
207    }
208  }
209  
210  public void cacheResource(Resource r) throws FHIRException {
211    synchronized (lock) {
212      Map<String, Resource> map = allResourcesById.get(r.fhirType());
213      if (map == null) {
214        map = new HashMap<String, Resource>();
215        allResourcesById.put(r.fhirType(), map);
216      }
217      map.put(r.getId(), r);
218
219      if (r instanceof MetadataResource) {
220        MetadataResource m = (MetadataResource) r;
221        String url = m.getUrl();
222        if (!allowLoadingDuplicates && hasResource(r.getClass(), url))
223          throw new DefinitionException("Duplicate Resource " + url);
224        if (r instanceof StructureDefinition)
225          structures.see((StructureDefinition) m);
226        else if (r instanceof ValueSet)
227          valueSets.see((ValueSet) m);
228        else if (r instanceof CodeSystem)
229          codeSystems.see((CodeSystem) m);
230        else if (r instanceof ImplementationGuide)
231          guides.see((ImplementationGuide) m);
232        else if (r instanceof CapabilityStatement)
233          capstmts.see((CapabilityStatement) m);
234        else if (r instanceof SearchParameter)
235          searchParameters.see((SearchParameter) m);
236        else if (r instanceof PlanDefinition)
237          plans.see((PlanDefinition) m);
238        else if (r instanceof OperationDefinition)
239          operations.see((OperationDefinition) m);
240        else if (r instanceof Questionnaire)
241          questionnaires.see((Questionnaire) m);
242        else if (r instanceof ConceptMap)
243          maps.see((ConceptMap) m);
244        else if (r instanceof StructureMap)
245          transforms.see((StructureMap) m);
246        else if (r instanceof NamingSystem)
247          systems.add((NamingSystem) r);
248      }
249    }
250  }
251
252  /*
253   *  Compare business versions, returning "true" if the candidate newer version is in fact newer than the oldVersion
254   *  Comparison will work for strictly numeric versions as well as multi-level versions separated by ., -, _, : or space
255   *  Failing that, it will do unicode-based character ordering.
256   *  E.g. 1.5.3 < 1.14.3
257   *       2017-3-10 < 2017-12-7
258   *       A3 < T2
259   */
260  private boolean laterVersion(String newVersion, String oldVersion) {
261    // Compare business versions, retur
262    newVersion = newVersion.trim();
263    oldVersion = oldVersion.trim();
264    if (StringUtils.isNumeric(newVersion) && StringUtils.isNumeric(oldVersion))
265      return Double.parseDouble(newVersion) > Double.parseDouble(oldVersion);
266    else if (hasDelimiter(newVersion, oldVersion, "."))
267      return laterDelimitedVersion(newVersion, oldVersion, "\\.");
268    else if (hasDelimiter(newVersion, oldVersion, "-"))
269      return laterDelimitedVersion(newVersion, oldVersion, "\\-");
270    else if (hasDelimiter(newVersion, oldVersion, "_"))
271      return laterDelimitedVersion(newVersion, oldVersion, "\\_");
272    else if (hasDelimiter(newVersion, oldVersion, ":"))
273      return laterDelimitedVersion(newVersion, oldVersion, "\\:");
274    else if (hasDelimiter(newVersion, oldVersion, " "))
275      return laterDelimitedVersion(newVersion, oldVersion, "\\ ");
276    else {
277      return newVersion.compareTo(oldVersion) > 0;
278    }
279  }
280  
281  /*
282   * Returns true if both strings include the delimiter and have the same number of occurrences of it
283   */
284  private boolean hasDelimiter(String s1, String s2, String delimiter) {
285    return s1.contains(delimiter) && s2.contains(delimiter) && s1.split(delimiter).length == s2.split(delimiter).length;
286  }
287
288  private boolean laterDelimitedVersion(String newVersion, String oldVersion, String delimiter) {
289    String[] newParts = newVersion.split(delimiter);
290    String[] oldParts = oldVersion.split(delimiter);
291    for (int i = 0; i < newParts.length; i++) {
292      if (!newParts[i].equals(oldParts[i]))
293        return laterVersion(newParts[i], oldParts[i]);
294    }
295    // This should never happen
296    throw new Error("Delimited versions have exact match for delimiter '"+delimiter+"' : "+newParts+" vs "+oldParts);
297  }
298  
299  protected <T extends MetadataResource> void seeMetadataResource(T r, Map<String, T> map, List<T> list, boolean addId) throws FHIRException {
300//    if (addId)
301    //      map.put(r.getId(), r); // todo: why?
302    list.add(r);
303    if (r.hasUrl()) {
304      // first, this is the correct reosurce for this version (if it has a version)
305      if (r.hasVersion()) {
306        map.put(r.getUrl()+"|"+r.getVersion(), r);
307      }
308      // if we haven't get anything for this url, it's the correct version
309      if (!map.containsKey(r.getUrl()))
310        map.put(r.getUrl(), r);
311      else {
312        List<T> rl = new ArrayList<T>();
313        for (T t : list) {
314          if (t.getUrl().equals(r.getUrl()) && !rl.contains(t)) {
315            rl.add(t);
316          }
317        }
318        Collections.sort(rl, new MetadataResourceVersionComparator<T>(list));
319        map.put(r.getUrl(), rl.get(rl.size()-1));
320        T latest = null;
321        for (T t : rl) {
322          if (VersionUtilities.versionsCompatible(t.getVersion(), r.getVersion())) {
323            latest = t;
324          }
325        }
326        if (latest != null) { // might be null if it's not using semver
327          map.put(r.getUrl()+"|"+VersionUtilities.getMajMin(latest.getVersion()), rl.get(rl.size()-1));
328        }
329      }
330    }
331  }  
332
333  @Override
334  public CodeSystem fetchCodeSystem(String system) {
335    synchronized (lock) {
336      return codeSystems.get(system);
337    }
338  } 
339
340  @Override
341  public boolean supportsSystem(String system) throws TerminologyServiceException {
342    synchronized (lock) {
343      if (codeSystems.has(system) && codeSystems.get(system).getContent() != CodeSystemContentMode.NOTPRESENT)
344        return true;
345      else if (supportedCodeSystems.contains(system))
346        return true;
347      else if (system.startsWith("http://example.org") || system.startsWith("http://acme.com") || system.startsWith("http://hl7.org/fhir/valueset-") || system.startsWith("urn:oid:"))
348        return false;
349      else {
350        if (noTerminologyServer)
351          return false;
352        if (txcaps == null) {
353          try {
354            log("Terminology server: Check for supported code systems for "+system);
355            txcaps = txClient.getTerminologyCapabilities();
356          } catch (Exception e) {
357            if (canRunWithoutTerminology) {
358              noTerminologyServer = true;
359              log("==============!! Running without terminology server !! ==============");
360              if (txClient!=null) {
361                log("txServer = "+txClient.getAddress());
362                log("Error = "+e.getMessage()+"");
363              }
364              log("=====================================================================");
365              return false;
366            } else
367              throw new TerminologyServiceException(e);
368          }
369          if (txcaps != null) {
370            for (TerminologyCapabilitiesCodeSystemComponent tccs : txcaps.getCodeSystem()) {
371              supportedCodeSystems.add(tccs.getUri());
372            }
373          }
374          if (supportedCodeSystems.contains(system))
375            return true;
376        }
377      }
378      return false;
379    }
380  }
381
382  private void log(String message) {
383    if (logger != null)
384      logger.logMessage(message);
385    else
386      System.out.println(message);
387  }
388
389
390  protected void tlog(String msg) {
391    if (tlogging )
392      if (logger != null)
393        logger.logDebugMessage(LogCategory.TX, msg);
394      else 
395        System.out.println("-tx: "+msg);
396  }
397
398  // --- expansion support ------------------------------------------------------------------------------------------------------------
399
400  public int getExpandCodesLimit() {
401    return expandCodesLimit;
402  }
403
404  public void setExpandCodesLimit(int expandCodesLimit) {
405    this.expandCodesLimit = expandCodesLimit;
406  }
407
408  @Override
409  public ValueSetExpansionOutcome expandVS(ElementDefinitionBindingComponent binding, boolean cacheOk, boolean heirarchical) throws FHIRException {
410    ValueSet vs = null;
411    vs = fetchResource(ValueSet.class, binding.getValueSet());
412    if (vs == null)
413      throw new FHIRException("Unable to resolve value Set "+binding.getValueSet());
414    return expandVS(vs, cacheOk, heirarchical);
415  }
416  
417  @Override
418  public ValueSetExpansionOutcome expandVS(ConceptSetComponent inc, boolean heirachical) throws TerminologyServiceException {
419    ValueSet vs = new ValueSet();
420    vs.setCompose(new ValueSetComposeComponent());
421    vs.getCompose().getInclude().add(inc);
422    CacheToken cacheToken = txCache.generateExpandToken(vs, heirachical);
423    ValueSetExpansionOutcome res;
424    res = txCache.getExpansion(cacheToken);
425    if (res != null)
426      return res;
427    Parameters p = expParameters.copy(); 
428    p.setParameter("includeDefinition", false);
429    p.setParameter("excludeNested", !heirachical);
430    
431    if (noTerminologyServer)
432      return new ValueSetExpansionOutcome("Error expanding ValueSet: running without terminology services", TerminologyServiceErrorClass.NOSERVICE);
433    Map<String, String> params = new HashMap<String, String>();
434    params.put("_limit", Integer.toString(expandCodesLimit ));
435    params.put("_incomplete", "true");
436    tlog("$expand on "+txCache.summary(vs));
437    try {
438      ValueSet result = txClient.expandValueset(vs, p, params);
439      res = new ValueSetExpansionOutcome(result).setTxLink(txLog.getLastId());  
440    } catch (Exception e) {
441      res = new ValueSetExpansionOutcome(e.getMessage() == null ? e.getClass().getName() : e.getMessage(), TerminologyServiceErrorClass.UNKNOWN);
442      if (txLog != null)
443        res.setTxLink(txLog.getLastId());
444    }
445    txCache.cacheExpansion(cacheToken, res, TerminologyCache.PERMANENT);
446    return res;
447  }
448
449  @Override
450  public ValueSetExpansionOutcome expandVS(ValueSet vs, boolean cacheOk, boolean heirarchical) {
451    if (expParameters == null)
452      throw new Error("No Expansion Parameters provided");
453    Parameters p = expParameters.copy(); 
454    return expandVS(vs, cacheOk, heirarchical, p);
455  }
456  
457  public ValueSetExpansionOutcome expandVS(ValueSet vs, boolean cacheOk, boolean heirarchical, Parameters p)  {
458    if (p == null)
459      throw new Error("No Parameters provided to expandVS");
460    if (vs.hasExpansion()) {
461      return new ValueSetExpansionOutcome(vs.copy());
462    }
463    if (!vs.hasUrl())
464      throw new Error("no value set");
465    
466      CacheToken cacheToken = txCache.generateExpandToken(vs, heirarchical);
467      ValueSetExpansionOutcome res;
468      if (cacheOk) {
469        res = txCache.getExpansion(cacheToken);
470        if (res != null)
471          return res;
472      }
473      p.setParameter("includeDefinition", false);
474      p.setParameter("excludeNested", !heirarchical);
475      
476      // ok, first we try to expand locally
477      try {
478        ValueSetExpanderSimple vse = new ValueSetExpanderSimple(this);
479        res = vse.doExpand(vs, p);
480        if (!res.getValueset().hasUrl())
481          throw new Error("no url in expand value set");
482        txCache.cacheExpansion(cacheToken, res, TerminologyCache.TRANSIENT);
483        return res;
484      } catch (Exception e) {
485      }
486      
487      // if that failed, we try to expand on the server
488      if (noTerminologyServer)
489        return new ValueSetExpansionOutcome("Error expanding ValueSet: running without terminology services", TerminologyServiceErrorClass.NOSERVICE);
490      Map<String, String> params = new HashMap<String, String>();
491      params.put("_limit", Integer.toString(expandCodesLimit ));
492      params.put("_incomplete", "true");
493      tlog("$expand on "+txCache.summary(vs));
494      try {
495        ValueSet result = txClient.expandValueset(vs, p, params);
496        if (!result.hasUrl())
497          result.setUrl(vs.getUrl());
498        if (!result.hasUrl())
499          throw new Error("no url in expand value set 2");
500        res = new ValueSetExpansionOutcome(result).setTxLink(txLog.getLastId());  
501      } catch (Exception e) {
502        res = new ValueSetExpansionOutcome(e.getMessage() == null ? e.getClass().getName() : e.getMessage(), TerminologyServiceErrorClass.UNKNOWN).setTxLink(txLog == null ? null : txLog.getLastId());
503      }
504      txCache.cacheExpansion(cacheToken, res, TerminologyCache.PERMANENT);
505      return res;
506  }
507
508
509  private boolean hasTooCostlyExpansion(ValueSet valueset) {
510    return valueset != null && valueset.hasExpansion() && ToolingExtensions.hasExtension(valueset.getExpansion(), "http://hl7.org/fhir/StructureDefinition/valueset-toocostly");
511  }
512  // --- validate code -------------------------------------------------------------------------------
513  
514  @Override
515  public ValidationResult validateCode(TerminologyServiceOptions options, String system, String code, String display) {
516    Coding c = new Coding(system, code, display);
517    return validateCode(options, c, null);
518  }
519
520  @Override
521  public ValidationResult validateCode(TerminologyServiceOptions options, String system, String code, String display, ValueSet vs) {
522    Coding c = new Coding(system, code, display);
523    return validateCode(options, c, vs);
524  }
525
526  @Override
527  public ValidationResult validateCode(TerminologyServiceOptions options, String code, ValueSet vs) {
528    Coding c = new Coding(null, code, null);
529    return doValidateCode(options, c, vs, true);
530  }
531
532  @Override
533  public ValidationResult validateCode(TerminologyServiceOptions options, String system, String code, String display, ConceptSetComponent vsi) {
534    Coding c = new Coding(system, code, display);
535    ValueSet vs = new ValueSet();
536    vs.setUrl(Utilities.makeUuidUrn());
537    vs.getCompose().addInclude(vsi);
538    return validateCode(options, c, vs);
539  }
540
541  @Override
542  public ValidationResult validateCode(TerminologyServiceOptions options, Coding code, ValueSet vs) {
543    return doValidateCode(options, code, vs, false);
544  }
545  
546  public ValidationResult doValidateCode(TerminologyServiceOptions options, Coding code, ValueSet vs, boolean implySystem) {
547    CacheToken cacheToken = txCache != null ? txCache.generateValidationToken(options, code, vs) : null;
548    ValidationResult res = null;
549    if (txCache != null) 
550      res = txCache.getValidation(cacheToken);
551    if (res != null)
552      return res;
553
554    // ok, first we try to validate locally
555    try {
556      ValueSetCheckerSimple vsc = new ValueSetCheckerSimple(options, vs, this); 
557      res = vsc.validateCode(code);
558      if (txCache != null)
559        txCache.cacheValidation(cacheToken, res, TerminologyCache.TRANSIENT);
560      return res;
561    } catch (Exception e) {
562    }
563    
564    // if that failed, we try to validate on the server
565    if (noTerminologyServer)
566      return new ValidationResult(IssueSeverity.ERROR,  "Error validating code: running without terminology services", TerminologyServiceErrorClass.NOSERVICE);
567    String csumm =  txCache != null ? txCache.summary(code) : null;
568    if (txCache != null)
569      tlog("$validate "+csumm+" for "+ txCache.summary(vs));
570    else
571      tlog("$validate "+csumm+" before cache exists");
572    try {
573      Parameters pIn = new Parameters();
574      pIn.addParameter().setName("coding").setValue(code);
575      if (implySystem)
576        pIn.addParameter().setName("implySystem").setValue(new BooleanType(true));
577      if (options != null)
578        setTerminologyOptions(options, pIn);
579      res = validateOnServer(vs, pIn);
580    } catch (Exception e) {
581      res = new ValidationResult(IssueSeverity.ERROR, e.getMessage() == null ? e.getClass().getName() : e.getMessage()).setTxLink(txLog == null ? null : txLog.getLastId());
582    }
583    if (txCache != null)
584      txCache.cacheValidation(cacheToken, res, TerminologyCache.PERMANENT);
585    return res;
586  }
587
588  private void setTerminologyOptions(TerminologyServiceOptions options, Parameters pIn) {
589    if (options != null) {
590      if (!Utilities.noString(options.getLanguage()))
591        pIn.addParameter("displayLanguage", options.getLanguage());
592     } 
593  }
594
595  @Override
596  public ValidationResult validateCode(TerminologyServiceOptions options, CodeableConcept code, ValueSet vs) {
597    CacheToken cacheToken = txCache.generateValidationToken(options, code, vs);
598    ValidationResult res = txCache.getValidation(cacheToken);
599    if (res != null)
600      return res;
601
602    // ok, first we try to validate locally
603    try {
604      ValueSetCheckerSimple vsc = new ValueSetCheckerSimple(options, vs, this); 
605      res = vsc.validateCode(code);
606      txCache.cacheValidation(cacheToken, res, TerminologyCache.TRANSIENT);
607      return res;
608    } catch (Exception e) {
609    }
610
611    // if that failed, we try to validate on the server
612    if (noTerminologyServer)
613      return new ValidationResult(IssueSeverity.ERROR, "Error validating code: running without terminology services", TerminologyServiceErrorClass.NOSERVICE);
614    tlog("$validate "+txCache.summary(code)+" for "+ txCache.summary(vs));
615    try {
616      Parameters pIn = new Parameters();
617      pIn.addParameter().setName("codeableConcept").setValue(code);
618      if (options != null)
619        setTerminologyOptions(options, pIn);
620      res = validateOnServer(vs, pIn);
621    } catch (Exception e) {
622      res = new ValidationResult(IssueSeverity.ERROR, e.getMessage() == null ? e.getClass().getName() : e.getMessage()).setTxLink(txLog.getLastId());
623    }
624    txCache.cacheValidation(cacheToken, res, TerminologyCache.PERMANENT);
625    return res;
626  }
627
628  private ValidationResult validateOnServer(ValueSet vs, Parameters pin) throws FHIRException {
629    if (vs != null)
630      pin.addParameter().setName("valueSet").setResource(vs);
631    for (ParametersParameterComponent pp : pin.getParameter())
632      if (pp.getName().equals("profile"))
633        throw new Error("Can only specify profile in the context");
634    if (expParameters == null)
635      throw new Error("No ExpansionProfile provided");
636    pin.addParameter().setName("profile").setResource(expParameters);
637    txLog.clearLastId();
638    Parameters pOut;
639    if (vs == null)
640      pOut = txClient.validateCS(pin);
641    else
642      pOut = txClient.validateVS(pin);
643    boolean ok = false;
644    String message = "No Message returned";
645    String display = null;
646    TerminologyServiceErrorClass err = TerminologyServiceErrorClass.UNKNOWN;
647    for (ParametersParameterComponent p : pOut.getParameter()) {
648      if (p.getName().equals("result"))
649        ok = ((BooleanType) p.getValue()).getValue().booleanValue();
650      else if (p.getName().equals("message"))
651        message = ((StringType) p.getValue()).getValue();
652      else if (p.getName().equals("display"))
653        display = ((StringType) p.getValue()).getValue();
654      else if (p.getName().equals("cause")) {
655        try {
656          IssueType it = IssueType.fromCode(((StringType) p.getValue()).getValue());
657          if (it == IssueType.UNKNOWN)
658            err = TerminologyServiceErrorClass.UNKNOWN;
659          else if (it == IssueType.NOTSUPPORTED)
660            err = TerminologyServiceErrorClass.VALUESET_UNSUPPORTED;
661        } catch (FHIRException e) {
662        }
663      }
664    }
665    if (!ok)
666      return new ValidationResult(IssueSeverity.ERROR, message, err).setTxLink(txLog.getLastId()).setTxLink(txLog.getLastId());
667    else if (message != null && !message.equals("No Message returned")) 
668      return new ValidationResult(IssueSeverity.WARNING, message, new ConceptDefinitionComponent().setDisplay(display)).setTxLink(txLog.getLastId()).setTxLink(txLog.getLastId());
669    else if (display != null)
670      return new ValidationResult(new ConceptDefinitionComponent().setDisplay(display)).setTxLink(txLog.getLastId()).setTxLink(txLog.getLastId());
671    else
672      return new ValidationResult(new ConceptDefinitionComponent()).setTxLink(txLog.getLastId()).setTxLink(txLog.getLastId());
673  }
674
675  // --------------------------------------------------------------------------------------------------------------------------------------------------------
676  
677  public void initTS(String cachePath) throws Exception {
678    txCache = new TerminologyCache(lock, cachePath);
679  }
680
681  @Override
682  public List<ConceptMap> findMapsForSource(String url) throws FHIRException {
683    synchronized (lock) {
684      List<ConceptMap> res = new ArrayList<ConceptMap>();
685      for (ConceptMap map : maps.getList())
686        if (((Reference) map.getSource()).getReference().equals(url)) 
687          res.add(map);
688      return res;
689    }
690  }
691
692  public boolean isCanRunWithoutTerminology() {
693    return canRunWithoutTerminology;
694  }
695
696  public void setCanRunWithoutTerminology(boolean canRunWithoutTerminology) {
697    this.canRunWithoutTerminology = canRunWithoutTerminology;
698  }
699
700  public void setLogger(ILoggingService logger) {
701    this.logger = logger;
702  }
703
704  public Parameters getExpansionParameters() {
705    return expParameters;
706  }
707
708  public void setExpansionProfile(Parameters expParameters) {
709    this.expParameters = expParameters;
710  }
711
712  @Override
713  public boolean isNoTerminologyServer() {
714    return noTerminologyServer;
715  }
716
717  public String getName() {
718    return name;
719  }
720
721  public void setName(String name) {
722    this.name = name;
723  }
724
725  @Override
726  public Set<String> getResourceNamesAsSet() {
727    Set<String> res = new HashSet<String>();
728    res.addAll(getResourceNames());
729    return res;
730  }
731
732  public boolean isAllowLoadingDuplicates() {
733    return allowLoadingDuplicates;
734  }
735
736  public void setAllowLoadingDuplicates(boolean allowLoadingDuplicates) {
737    this.allowLoadingDuplicates = allowLoadingDuplicates;
738  }
739
740  @SuppressWarnings("unchecked")
741  @Override
742  public <T extends Resource> T fetchResourceWithException(Class<T> class_, String uri) throws FHIRException {
743       if (class_ == StructureDefinition.class)
744      uri = ProfileUtilities.sdNs(uri, getOverrideVersionNs());
745    synchronized (lock) {
746
747      if (uri.startsWith("http:") || uri.startsWith("https:")) {
748        String version = null;
749        if (uri.contains("|")) {
750          version = uri.substring(uri.lastIndexOf("|")+1);
751          uri = uri.substring(0, uri.lastIndexOf("|"));
752        }
753        if (uri.contains("#"))
754          uri = uri.substring(0, uri.indexOf("#"));
755        if (class_ == Resource.class || class_ == null) {
756          if (structures.has(uri))
757            return (T) structures.get(uri);
758          if (guides.has(uri))
759            return (T) guides.get(uri);
760          if (capstmts.has(uri))
761            return (T) capstmts.get(uri);
762          if (valueSets.has(uri))
763            return (T) valueSets.get(uri);
764          if (codeSystems.has(uri))
765            return (T) codeSystems.get(uri);
766          if (operations.has(uri))
767            return (T) operations.get(uri);
768          if (searchParameters.has(uri))
769            return (T) searchParameters.get(uri);
770          if (plans.has(uri))
771            return (T) plans.get(uri);
772          if (maps.has(uri))
773            return (T) maps.get(uri);
774          if (transforms.has(uri))
775            return (T) transforms.get(uri);
776          if (questionnaires.has(uri))
777            return (T) questionnaires.get(uri);
778          for (Map<String, Resource> rt : allResourcesById.values()) {
779            for (Resource r : rt.values()) {
780              if (r instanceof MetadataResource) {
781                MetadataResource mr = (MetadataResource) r;
782                if (uri.equals(mr.getUrl()))
783                  return (T) mr;
784              }
785            }            
786          }
787          return null;      
788        } else if (class_ == ImplementationGuide.class) {
789          return (T) guides.get(uri);
790        } else if (class_ == CapabilityStatement.class) {
791          return (T) capstmts.get(uri);
792        } else if (class_ == StructureDefinition.class) {
793          return (T) structures.get(uri);
794        } else if (class_ == StructureMap.class) {
795          return (T) transforms.get(uri);
796        } else if (class_ == ValueSet.class) {
797          if (valueSets.has(uri, version))
798            return (T) valueSets.get(uri, version);
799          else
800            return (T) valueSets.get(uri);
801        } else if (class_ == CodeSystem.class) {
802          if (codeSystems.has(uri, version))
803            return (T) codeSystems.get(uri, version);
804          else
805          return (T) codeSystems.get(uri);
806        } else if (class_ == ConceptMap.class) {
807          return (T) maps.get(uri);
808        } else if (class_ == PlanDefinition.class) {
809          return (T) plans.get(uri);
810        } else if (class_ == OperationDefinition.class) {
811          OperationDefinition od = operations.get(uri);
812          return (T) od;
813        } else if (class_ == SearchParameter.class) {
814          SearchParameter res = searchParameters.get(uri);
815          return (T) res;
816        }
817      }
818      if (class_ == CodeSystem.class && codeSystems.has(uri))
819        return (T) codeSystems.get(uri);
820      
821      if (class_ == Questionnaire.class)
822        return (T) questionnaires.get(uri);
823      if (class_ == null) {
824        if (uri.matches(Constants.URI_REGEX) && !uri.contains("ValueSet"))
825          return null;
826
827        // it might be a special URL.
828        if (Utilities.isAbsoluteUrl(uri) || uri.startsWith("ValueSet/")) {
829          Resource res = null; // findTxValueSet(uri);
830          if (res != null)
831            return (T) res;
832        }
833        return null;      
834      }    
835      if (supportedCodeSystems.contains(uri))
836        return null;
837      throw new FHIRException("not done yet: can't fetch "+uri);
838    }
839  }
840
841  private Set<String> notCanonical = new HashSet<String>();
842
843  private String overrideVersionNs;
844  
845//  private MetadataResource findTxValueSet(String uri) {
846//    MetadataResource res = expansionCache.getStoredResource(uri);
847//    if (res != null)
848//      return res;
849//    synchronized (lock) {
850//      if (notCanonical.contains(uri))
851//        return null;
852//    }
853//    try {
854//      tlog("get canonical "+uri);
855//      res = txServer.getCanonical(ValueSet.class, uri);
856//    } catch (Exception e) {
857//      synchronized (lock) {
858//        notCanonical.add(uri);
859//      }
860//      return null;
861//    }
862//    if (res != null)
863//      try {
864//        expansionCache.storeResource(res);
865//      } catch (IOException e) {
866//      }
867//    return res;
868//  }
869
870  @Override
871  public Resource fetchResourceById(String type, String uri) {
872    synchronized (lock) {
873      String[] parts = uri.split("\\/");
874      if (!Utilities.noString(type) && parts.length == 1) {
875        if (allResourcesById.containsKey(type))
876          return allResourcesById.get(type).get(parts[0]);
877        else
878          return null;
879      }
880      if (parts.length >= 2) {
881        if (!Utilities.noString(type))
882          if (!type.equals(parts[parts.length-2])) 
883            throw new Error("Resource type mismatch for "+type+" / "+uri);
884        return allResourcesById.get(parts[parts.length-2]).get(parts[parts.length-1]);
885      } else
886        throw new Error("Unable to process request for resource for "+type+" / "+uri);
887    }
888  }
889
890  public <T extends Resource> T fetchResource(Class<T> class_, String uri) {
891    try {
892      return fetchResourceWithException(class_, uri);
893    } catch (FHIRException e) {
894      throw new Error(e);
895    }
896  }
897  
898  @Override
899  public <T extends Resource> boolean hasResource(Class<T> class_, String uri) {
900    try {
901      return fetchResourceWithException(class_, uri) != null;
902    } catch (Exception e) {
903      return false;
904    }
905  }
906
907
908  public TranslationServices translator() {
909    return translator;
910  }
911
912  public void setTranslator(TranslationServices translator) {
913    this.translator = translator;
914  }
915  
916  public class NullTranslator implements TranslationServices {
917
918    @Override
919    public String translate(String context, String value, String targetLang) {
920      return value;
921    }
922
923    @Override
924    public String translate(String context, String value) {
925      return value;
926    }
927
928    @Override
929    public String toStr(float value) {
930      return null;
931    }
932
933    @Override
934    public String toStr(Date value) {
935      return null;
936    }
937
938    @Override
939    public String translateAndFormat(String contest, String lang, String value, Object... args) {
940      return String.format(value, args);
941    }
942
943    @Override
944    public Map<String, String> translations(String value) {
945      // TODO Auto-generated method stub
946      return null;
947    }
948
949    @Override
950    public Set<String> listTranslations(String category) {
951      // TODO Auto-generated method stub
952      return null;
953    }
954
955  }
956  
957  public void reportStatus(JsonObject json) {
958    synchronized (lock) {
959      json.addProperty("codeystem-count", codeSystems.size());
960      json.addProperty("valueset-count", valueSets.size());
961      json.addProperty("conceptmap-count", maps.size());
962      json.addProperty("transforms-count", transforms.size());
963      json.addProperty("structures-count", structures.size());
964      json.addProperty("guides-count", guides.size());
965      json.addProperty("statements-count", capstmts.size());
966    }
967  }
968
969
970  public void dropResource(Resource r) throws FHIRException {
971    dropResource(r.fhirType(), r.getId());   
972  }
973
974  public void dropResource(String fhirType, String id) {
975    synchronized (lock) {
976
977      Map<String, Resource> map = allResourcesById.get(fhirType);
978      if (map == null) {
979        map = new HashMap<String, Resource>();
980        allResourcesById.put(fhirType, map);
981      }
982      if (map.containsKey(id))
983        map.remove(id);
984
985      if (fhirType.equals("StructureDefinition"))
986        structures.drop(id);
987      else if (fhirType.equals("ImplementationGuide"))
988        guides.drop(id);
989      else if (fhirType.equals("CapabilityStatement"))
990        capstmts.drop(id);
991      else if (fhirType.equals("ValueSet"))
992        valueSets.drop(id);
993      else if (fhirType.equals("CodeSystem"))
994        codeSystems.drop(id);
995      else if (fhirType.equals("OperationDefinition"))
996        operations.drop(id);
997      else if (fhirType.equals("Questionnaire"))
998        questionnaires.drop(id);
999      else if (fhirType.equals("ConceptMap"))
1000        maps.drop(id);
1001      else if (fhirType.equals("StructureMap"))
1002        transforms.drop(id);
1003      else if (fhirType.equals("NamingSystem"))
1004        for (int i = systems.size()-1; i >= 0; i--) {
1005          if (systems.get(i).getId().equals(id))
1006            systems.remove(i);
1007        }
1008    }
1009  }
1010
1011  private <T extends MetadataResource> void dropMetadataResource(Map<String, T> map, String id) {
1012    T res = map.get(id);
1013    if (res != null) {
1014      map.remove(id);
1015      if (map.containsKey(res.getUrl()))
1016        map.remove(res.getUrl());
1017      if (res.getVersion() != null)
1018        if (map.containsKey(res.getUrl()+"|"+res.getVersion()))
1019          map.remove(res.getUrl()+"|"+res.getVersion());
1020    }
1021  }
1022
1023  @Override
1024  public List<MetadataResource> allConformanceResources() {
1025    synchronized (lock) {
1026      List<MetadataResource> result = new ArrayList<MetadataResource>();
1027      structures.listAllM(result);
1028      guides.listAllM(result);
1029      capstmts.listAllM(result);
1030      codeSystems.listAllM(result);
1031      valueSets.listAllM(result);
1032      maps.listAllM(result);
1033      transforms.listAllM(result);
1034      plans.listAllM(result);
1035      questionnaires.listAllM(result);
1036      return result;
1037    }
1038  }
1039  
1040  public String listSupportedSystems() {
1041    synchronized (lock) {
1042      String sl = null;
1043      for (String s : supportedCodeSystems)
1044        sl = sl == null ? s : sl + "\r\n" + s;
1045      return sl;
1046    }
1047  }
1048
1049
1050  public int totalCount() {
1051    synchronized (lock) {
1052      return valueSets.size() +  maps.size() + structures.size() + transforms.size();
1053    }
1054  }
1055  
1056  public List<ConceptMap> listMaps() {
1057    List<ConceptMap> m = new ArrayList<ConceptMap>();
1058    synchronized (lock) {
1059      maps.listAll(m);
1060    }
1061    return m;
1062  }
1063  
1064  public List<StructureMap> listTransforms() {
1065    List<StructureMap> m = new ArrayList<StructureMap>();
1066    synchronized (lock) {
1067      transforms.listAll(m);    
1068    }
1069    return m;
1070  }
1071  
1072  public StructureMap getTransform(String code) {
1073    synchronized (lock) {
1074      return transforms.get(code);
1075    }
1076  }
1077
1078  public List<StructureDefinition> listStructures() {
1079    List<StructureDefinition> m = new ArrayList<StructureDefinition>();
1080    synchronized (lock) {
1081      structures.listAll(m);    
1082    }
1083    return m;
1084  }
1085
1086  public StructureDefinition getStructure(String code) {
1087    synchronized (lock) {
1088      return structures.get(code);
1089    }
1090  }
1091
1092  @Override
1093  public String oid2Uri(String oid) {
1094    synchronized (lock) {
1095      String uri = OIDUtils.getUriForOid(oid);
1096      if (uri != null)
1097        return uri;
1098      for (NamingSystem ns : systems) {
1099        if (hasOid(ns, oid)) {
1100          uri = getUri(ns);
1101          if (uri != null)
1102            return null;
1103        }
1104      }
1105    }
1106    return null;
1107  }
1108  
1109
1110  private String getUri(NamingSystem ns) {
1111    for (NamingSystemUniqueIdComponent id : ns.getUniqueId()) {
1112      if (id.getType() == NamingSystemIdentifierType.URI)
1113        return id.getValue();
1114    }
1115    return null;
1116  }
1117
1118  private boolean hasOid(NamingSystem ns, String oid) {
1119    for (NamingSystemUniqueIdComponent id : ns.getUniqueId()) {
1120      if (id.getType() == NamingSystemIdentifierType.OID && id.getValue().equals(oid))
1121        return true;
1122    }
1123    return false;
1124  }
1125
1126  public void cacheVS(JsonObject json, Map<String, ValidationResult> t) {
1127    synchronized (lock) {
1128      validationCache.put(json.get("url").getAsString(), t);
1129    }
1130  }
1131
1132  public SearchParameter getSearchParameter(String code) {
1133    synchronized (lock) {
1134      return searchParameters.get(code);
1135    }
1136  }
1137
1138  @Override
1139  public String getOverrideVersionNs() {
1140    return overrideVersionNs;
1141  }
1142
1143  @Override
1144  public void setOverrideVersionNs(String value) {
1145    overrideVersionNs = value;
1146  }
1147
1148  @Override
1149  public ILoggingService getLogger() {
1150    return logger;
1151  }
1152
1153  @Override
1154  public StructureDefinition fetchTypeDefinition(String typeName) {
1155    if (Utilities.isAbsoluteUrl(typeName))
1156      return fetchResource(StructureDefinition.class, typeName);
1157    else
1158      return fetchResource(StructureDefinition.class, "http://hl7.org/fhir/StructureDefinition/"+typeName);
1159  }
1160
1161  public boolean isTlogging() {
1162    return tlogging;
1163  }
1164
1165  public void setTlogging(boolean tlogging) {
1166    this.tlogging = tlogging;
1167  }
1168
1169  public UcumService getUcumService() {
1170    return ucumService;
1171  }
1172
1173  public void setUcumService(UcumService ucumService) {
1174    this.ucumService = ucumService;
1175  }
1176
1177  @Override
1178  public List<StructureDefinition> getStructures() {
1179    List<StructureDefinition> res = new ArrayList<>();
1180    synchronized (lock) { // tricky, because you need to lock this as well, but it's really not in use yet
1181      structures.listAll(res);
1182    }
1183    return res;
1184  }
1185  
1186  public String getLinkForUrl(String corePath, String url) {
1187    if (codeSystems.has(url))
1188      return codeSystems.get(url).getUserString("path");
1189
1190    if (valueSets.has(url))
1191      return valueSets.get(url).getUserString("path");
1192
1193    if (maps.has(url))
1194      return maps.get(url).getUserString("path");
1195    
1196    if (transforms.has(url))
1197      return transforms.get(url).getUserString("path");
1198    
1199    if (structures.has(url))
1200      return structures.get(url).getUserString("path");
1201    
1202    if (guides.has(url))
1203      return guides.get(url).getUserString("path");
1204    
1205    if (capstmts.has(url))
1206      return capstmts.get(url).getUserString("path");
1207
1208    if (searchParameters.has(url))
1209      return searchParameters.get(url).getUserString("path");
1210        
1211    if (questionnaires.has(url))
1212      return questionnaires.get(url).getUserString("path");
1213
1214    if (operations.has(url))
1215      return operations.get(url).getUserString("path");
1216    
1217    if (plans.has(url))
1218      return plans.get(url).getUserString("path");
1219
1220    if (url.equals("http://loinc.org"))
1221      return corePath+"loinc.html";
1222    if (url.equals("http://unitsofmeasure.org"))
1223      return corePath+"ucum.html";
1224    if (url.equals("http://snomed.info/sct"))
1225      return corePath+"snomed.html";
1226    return null;
1227  }
1228
1229  
1230
1231  public List<ImplementationGuide> allImplementationGuides() {
1232    List<ImplementationGuide> res = new ArrayList<>();
1233    guides.listAll(res);
1234    return res;
1235  }
1236  
1237}