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 static org.apache.commons.lang3.StringUtils.isNotBlank;
025
026import java.io.FileNotFoundException;
027import java.io.IOException;
028
029/*
030 * Copyright (c) 2011+, HL7, Inc
031 * All rights reserved.
032 * 
033 * Redistribution and use in source and binary forms, with or without modification,
034 * are permitted provided that the following conditions are met:
035 * 
036 * Redistributions of source code must retain the above copyright notice, this
037 * list of conditions and the following disclaimer.
038 * Redistributions in binary form must reproduce the above copyright notice,
039 * this list of conditions and the following disclaimer in the documentation
040 * and/or other materials provided with the distribution.
041 * Neither the name of HL7 nor the names of its contributors may be used to
042 * endorse or promote products derived from this software without specific
043 * prior written permission.
044 * 
045 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
046 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
047 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
048 * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
049 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
050 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
051 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
052 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
053 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
054 * POSSIBILITY OF SUCH DAMAGE.
055 * 
056 */
057
058import java.util.ArrayList;
059import java.util.HashMap;
060import java.util.HashSet;
061import java.util.List;
062import java.util.Map;
063import java.util.Set;
064
065import org.apache.commons.lang3.NotImplementedException;
066import org.hl7.fhir.exceptions.FHIRException;
067import org.hl7.fhir.exceptions.FHIRFormatError;
068import org.hl7.fhir.exceptions.NoTerminologyServiceException;
069import org.hl7.fhir.exceptions.TerminologyServiceException;
070import org.hl7.fhir.r5.context.IWorkerContext;
071import org.hl7.fhir.r5.model.CodeSystem;
072import org.hl7.fhir.r5.model.CodeSystem.CodeSystemContentMode;
073import org.hl7.fhir.r5.model.CodeSystem.ConceptDefinitionComponent;
074import org.hl7.fhir.r5.model.CodeSystem.ConceptDefinitionDesignationComponent;
075import org.hl7.fhir.r5.model.DateTimeType;
076import org.hl7.fhir.r5.model.Extension;
077import org.hl7.fhir.r5.model.Factory;
078import org.hl7.fhir.r5.model.Parameters;
079import org.hl7.fhir.r5.model.Parameters.ParametersParameterComponent;
080import org.hl7.fhir.r5.model.PrimitiveType;
081import org.hl7.fhir.r5.model.DataType;
082import org.hl7.fhir.r5.model.UriType;
083import org.hl7.fhir.r5.model.ValueSet;
084import org.hl7.fhir.r5.model.ValueSet.ConceptReferenceComponent;
085import org.hl7.fhir.r5.model.ValueSet.ConceptReferenceDesignationComponent;
086import org.hl7.fhir.r5.model.ValueSet.ConceptSetComponent;
087import org.hl7.fhir.r5.model.ValueSet.ConceptSetFilterComponent;
088import org.hl7.fhir.r5.model.Enumerations.FilterOperator;
089import org.hl7.fhir.r5.model.ValueSet.ValueSetComposeComponent;
090import org.hl7.fhir.r5.model.ValueSet.ValueSetExpansionComponent;
091import org.hl7.fhir.r5.model.ValueSet.ValueSetExpansionContainsComponent;
092import org.hl7.fhir.r5.model.ValueSet.ValueSetExpansionParameterComponent;
093import org.hl7.fhir.r5.utils.ToolingExtensions;
094import org.hl7.fhir.utilities.Utilities;
095
096public class ValueSetExpanderSimple implements ValueSetExpander {
097
098  private List<ValueSetExpansionContainsComponent> codes = new ArrayList<ValueSet.ValueSetExpansionContainsComponent>();
099  private List<ValueSetExpansionContainsComponent> roots = new ArrayList<ValueSet.ValueSetExpansionContainsComponent>();
100  private Map<String, ValueSetExpansionContainsComponent> map = new HashMap<String, ValueSet.ValueSetExpansionContainsComponent>();
101  private IWorkerContext context;
102  private boolean canBeHeirarchy = true;
103  private Set<String> excludeKeys = new HashSet<String>();
104  private Set<String> excludeSystems = new HashSet<String>();
105  private ValueSet focus;
106  private int maxExpansionSize = 500;
107
108  private int total;
109
110  public ValueSetExpanderSimple(IWorkerContext context) {
111    super();
112    this.context = context;
113  }
114
115  public void setMaxExpansionSize(int theMaxExpansionSize) {
116    maxExpansionSize = theMaxExpansionSize;
117  }
118
119  private ValueSetExpansionContainsComponent addCode(String system, String code, String display, ValueSetExpansionContainsComponent parent, List<ConceptDefinitionDesignationComponent> designations, Parameters expParams, boolean isAbstract, boolean inactive, List<ValueSet> filters) {
120 
121    if (filters != null && !filters.isEmpty() && !filterContainsCode(filters, system, code))
122      return null;
123    ValueSetExpansionContainsComponent n = new ValueSet.ValueSetExpansionContainsComponent();
124    n.setSystem(system);
125    n.setCode(code);
126    if (isAbstract)
127      n.setAbstract(true);
128    if (inactive)
129      n.setInactive(true);
130
131    if (expParams.getParameterBool("includeDesignations") && designations != null) {
132      for (ConceptDefinitionDesignationComponent t : designations) {
133        ToolingExtensions.addLanguageTranslation(n, t.getLanguage(), t.getValue());
134      }
135    }
136    ConceptDefinitionDesignationComponent t = expParams.hasLanguage() ? getMatchingLang(designations, expParams.getLanguage()) : null;
137    if (t == null)
138      n.setDisplay(display);
139    else
140      n.setDisplay(t.getValue());
141
142    String s = key(n);
143    if (map.containsKey(s) || excludeKeys.contains(s)) {
144      canBeHeirarchy = false;
145    } else {
146      codes.add(n);
147      map.put(s, n);
148      total++;
149    }
150    if (canBeHeirarchy && parent != null) {
151      parent.getContains().add(n);
152    } else {
153      roots.add(n);
154    }
155    return n;
156  }
157
158  private boolean filterContainsCode(List<ValueSet> filters, String system, String code) {
159    for (ValueSet vse : filters)
160      if (expansionContainsCode(vse.getExpansion().getContains(), system, code))
161        return true;
162    return false;
163  }
164
165  private boolean expansionContainsCode(List<ValueSetExpansionContainsComponent> contains, String system, String code) {
166    for (ValueSetExpansionContainsComponent cc : contains) {
167      if (system.equals(cc.getSystem()) && code.equals(cc.getCode()))
168        return true;
169      if (expansionContainsCode(cc.getContains(), system, code))
170        return true;
171    }
172    return false;
173  }
174
175  private ConceptDefinitionDesignationComponent getMatchingLang(List<ConceptDefinitionDesignationComponent> list, String lang) {
176    for (ConceptDefinitionDesignationComponent t : list)
177      if (t.getLanguage().equals(lang))
178        return t;
179    for (ConceptDefinitionDesignationComponent t : list)
180      if (t.getLanguage().startsWith(lang))
181        return t;
182    return null;
183  }
184
185  private void addCodeAndDescendents(ValueSetExpansionContainsComponent focus, ValueSetExpansionContainsComponent parent, Parameters expParams, List<ValueSet> filters)  throws FHIRException {
186    focus.checkNoModifiers("Expansion.contains", "expanding");
187    ValueSetExpansionContainsComponent np = addCode(focus.getSystem(), focus.getCode(), focus.getDisplay(), parent, 
188         convert(focus.getDesignation()), expParams, focus.getAbstract(), focus.getInactive(), filters);
189    for (ValueSetExpansionContainsComponent c : focus.getContains())
190      addCodeAndDescendents(focus, np, expParams, filters);
191  }
192  
193  private List<ConceptDefinitionDesignationComponent> convert(List<ConceptReferenceDesignationComponent> designations) {
194    List<ConceptDefinitionDesignationComponent> list = new ArrayList<ConceptDefinitionDesignationComponent>();
195    for (ConceptReferenceDesignationComponent d : designations) {
196      ConceptDefinitionDesignationComponent n = new ConceptDefinitionDesignationComponent();
197      n.setLanguage(d.getLanguage());
198      n.setUse(d.getUse());
199      n.setValue(d.getValue());
200      list.add(n);
201    }
202    return list;
203  }
204
205  private void addCodeAndDescendents(CodeSystem cs, String system, ConceptDefinitionComponent def, ValueSetExpansionContainsComponent parent, Parameters expParams, List<ValueSet> filters, ConceptDefinitionComponent exclusion)  throws FHIRException {
206    def.checkNoModifiers("Code in Code System", "expanding");
207    if (exclusion != null) {
208      if (exclusion.getCode().equals(def.getCode()))
209        return; // excluded.
210    }
211    if (!CodeSystemUtilities.isDeprecated(cs, def)) {
212      ValueSetExpansionContainsComponent np = null;
213      boolean abs = CodeSystemUtilities.isNotSelectable(cs, def);
214      boolean inc = CodeSystemUtilities.isInactive(cs, def);
215      if (canBeHeirarchy || !abs)
216        np = addCode(system, def.getCode(), def.getDisplay(), parent, def.getDesignation(), expParams, abs, inc, filters);
217      for (ConceptDefinitionComponent c : def.getConcept())
218        addCodeAndDescendents(cs, system, c, np, expParams, filters, exclusion);
219    } else {
220      for (ConceptDefinitionComponent c : def.getConcept())
221        addCodeAndDescendents(cs, system, c, null, expParams, filters, exclusion);
222    }
223
224  }
225
226  private void addCodes(ValueSetExpansionComponent expand, List<ValueSetExpansionParameterComponent> params, Parameters expParams, List<ValueSet> filters) throws ETooCostly, FHIRException {
227    if (expand != null) {
228      if (expand.getContains().size() > maxExpansionSize)
229        throw new ETooCostly("Too many codes to display (>" + Integer.toString(expand.getContains().size()) + ")");
230      for (ValueSetExpansionParameterComponent p : expand.getParameter()) {
231        if (!existsInParams(params, p.getName(), p.getValue()))
232          params.add(p);
233      }
234
235      copyImportContains(expand.getContains(), null, expParams, filters);
236    }
237  }
238
239  private void excludeCode(String theSystem, String theCode) {
240    ValueSetExpansionContainsComponent n = new ValueSet.ValueSetExpansionContainsComponent();
241    n.setSystem(theSystem);
242    n.setCode(theCode);
243    String s = key(n);
244    excludeKeys.add(s);
245  }
246
247  private void excludeCodes(ConceptSetComponent exc, List<ValueSetExpansionParameterComponent> params, String ctxt) throws FHIRException {
248    exc.checkNoModifiers("Compose.exclude", "expanding");
249    if (exc.hasSystem() && exc.getConcept().size() == 0 && exc.getFilter().size() == 0) {
250      excludeSystems.add(exc.getSystem());
251    }
252
253    if (exc.hasValueSet())
254      throw new Error("Processing Value set references in exclude is not yet done in "+ctxt);
255    // importValueSet(imp.getValue(), params, expParams);
256
257    CodeSystem cs = context.fetchCodeSystem(exc.getSystem());
258    if ((cs == null || cs.getContent() != CodeSystemContentMode.COMPLETE) && context.supportsSystem(exc.getSystem())) {
259      ValueSetExpansionOutcome vse = context.expandVS(exc, false);
260      ValueSet valueset = vse.getValueset();
261      if (valueset == null)
262        throw new TerminologyServiceException("Error Expanding ValueSet: "+vse.getError());
263      excludeCodes(valueset.getExpansion(), params);
264      return;
265    }
266
267    for (ConceptReferenceComponent c : exc.getConcept()) {
268      excludeCode(exc.getSystem(), c.getCode());
269    }
270
271    if (exc.getFilter().size() > 0)
272      throw new NotImplementedException("not done yet");
273  }
274
275  private void excludeCodes(ValueSetExpansionComponent expand, List<ValueSetExpansionParameterComponent> params) {
276    for (ValueSetExpansionContainsComponent c : expand.getContains()) {
277      excludeCode(c.getSystem(), c.getCode());
278    }
279  }
280
281  private boolean existsInParams(List<ValueSetExpansionParameterComponent> params, String name, DataType value) {
282    for (ValueSetExpansionParameterComponent p : params) {
283      if (p.getName().equals(name) && PrimitiveType.compareDeep(p.getValue(), value, false))
284        return true;
285    }
286    return false;
287  }
288
289  @Override
290  public ValueSetExpansionOutcome expand(ValueSet source, Parameters expParams) {
291    try {
292      return doExpand(source, expParams);
293    } catch (NoTerminologyServiceException e) {
294      // well, we couldn't expand, so we'll return an interface to a checker that can check membership of the set
295      // that might fail too, but it might not, later.
296      return new ValueSetExpansionOutcome(e.getMessage(), TerminologyServiceErrorClass.NOSERVICE);
297    } catch (RuntimeException e) {
298      // TODO: we should put something more specific instead of just Exception below, since
299      // it swallows bugs.. what would be expected to be caught there?
300      throw e;
301    } catch (Exception e) {
302      // well, we couldn't expand, so we'll return an interface to a checker that can check membership of the set
303      // that might fail too, but it might not, later.
304      return new ValueSetExpansionOutcome(e.getMessage(), TerminologyServiceErrorClass.UNKNOWN);
305    }
306  }
307
308  public ValueSetExpansionOutcome doExpand(ValueSet source, Parameters expParams) throws FHIRException, ETooCostly, FileNotFoundException, IOException {
309    if (expParams == null)
310      expParams = makeDefaultExpansion();
311    source.checkNoModifiers("ValueSet", "expanding");
312    focus = source.copy();
313    focus.setExpansion(new ValueSet.ValueSetExpansionComponent());
314    focus.getExpansion().setTimestampElement(DateTimeType.now());
315    focus.getExpansion().setIdentifier(Factory.createUUID()); 
316    for (ParametersParameterComponent p : expParams.getParameter()) {
317      if (Utilities.existsInList(p.getName(), "includeDesignations", "excludeNested"))
318        focus.getExpansion().addParameter().setName(p.getName()).setValue(p.getValue());
319    }
320
321    if (source.hasCompose())
322      handleCompose(source.getCompose(), focus.getExpansion().getParameter(), expParams, source.getUrl(), focus.getExpansion().getExtension());
323
324    if (canBeHeirarchy) {
325      for (ValueSetExpansionContainsComponent c : roots) {
326        focus.getExpansion().getContains().add(c);
327      }
328    } else {
329      for (ValueSetExpansionContainsComponent c : codes) {
330        if (map.containsKey(key(c)) && !c.getAbstract()) { // we may have added abstract codes earlier while we still thought it might be heirarchical, but later we gave up, so now ignore them
331          focus.getExpansion().getContains().add(c);
332          c.getContains().clear(); // make sure any heirarchy is wiped
333        }
334      }
335    }
336
337    if (total > 0) {
338      focus.getExpansion().setTotal(total);
339    }
340
341    return new ValueSetExpansionOutcome(focus);
342  }
343
344  private Parameters makeDefaultExpansion() {
345    Parameters res = new Parameters();
346    res.addParameter("excludeNested", true);
347    res.addParameter("includeDesignations", false);
348    return res;
349  }
350
351  private void addToHeirarchy(List<ValueSetExpansionContainsComponent> target, List<ValueSetExpansionContainsComponent> source) {
352    for (ValueSetExpansionContainsComponent s : source) {
353      target.add(s);
354    }
355  }
356
357  private String getCodeDisplay(CodeSystem cs, String code) throws TerminologyServiceException {
358    ConceptDefinitionComponent def = getConceptForCode(cs.getConcept(), code);
359    if (def == null)
360      throw new TerminologyServiceException("Unable to find code '" + code + "' in code system " + cs.getUrl());
361    return def.getDisplay();
362  }
363
364  private ConceptDefinitionComponent getConceptForCode(List<ConceptDefinitionComponent> clist, String code) {
365    for (ConceptDefinitionComponent c : clist) {
366      if (code.equals(c.getCode()))
367        return c;
368      ConceptDefinitionComponent v = getConceptForCode(c.getConcept(), code);
369      if (v != null)
370        return v;
371    }
372    return null;
373  }
374
375  private void handleCompose(ValueSetComposeComponent compose, List<ValueSetExpansionParameterComponent> params, Parameters expParams, String ctxt, List<Extension> extensions)
376      throws ETooCostly, FileNotFoundException, IOException, FHIRException {
377    compose.checkNoModifiers("ValueSet.compose", "expanding");
378    // Exclude comes first because we build up a map of things to exclude
379    for (ConceptSetComponent inc : compose.getExclude())
380      excludeCodes(inc, params, ctxt);
381    canBeHeirarchy = !expParams.getParameterBool("excludeNested") && excludeKeys.isEmpty() && excludeSystems.isEmpty();
382    boolean first = true;
383    for (ConceptSetComponent inc : compose.getInclude()) {
384      if (first == true)
385        first = false;
386      else
387        canBeHeirarchy = false;
388      includeCodes(inc, params, expParams, canBeHeirarchy, extensions);
389    }
390
391  }
392
393  private ValueSet importValueSet(String value, List<ValueSetExpansionParameterComponent> params, Parameters expParams) throws ETooCostly, TerminologyServiceException, FileNotFoundException, IOException, FHIRFormatError {
394    if (value == null)
395      throw new TerminologyServiceException("unable to find value set with no identity");
396    ValueSet vs = context.fetchResource(ValueSet.class, value);
397    if (vs == null)
398      throw new TerminologyServiceException("Unable to find imported value set " + value);
399    ValueSetExpansionOutcome vso = new ValueSetExpanderSimple(context).expand(vs, expParams);
400    if (vso.getError() != null)
401      throw new TerminologyServiceException("Unable to expand imported value set: " + vso.getError());
402    if (vs.hasVersion())
403      if (!existsInParams(params, "version", new UriType(vs.getUrl() + "|" + vs.getVersion())))
404        params.add(new ValueSetExpansionParameterComponent().setName("version").setValue(new UriType(vs.getUrl() + "|" + vs.getVersion())));
405    for (ValueSetExpansionParameterComponent p : vso.getValueset().getExpansion().getParameter()) {
406      if (!existsInParams(params, p.getName(), p.getValue()))
407        params.add(p);
408    }
409    canBeHeirarchy = false; // if we're importing a value set, we have to be combining, so we won't try for a heirarchy
410    return vso.getValueset();
411  }
412
413  private void copyImportContains(List<ValueSetExpansionContainsComponent> list, ValueSetExpansionContainsComponent parent, Parameters expParams, List<ValueSet> filter) throws FHIRException {
414    for (ValueSetExpansionContainsComponent c : list) {
415      c.checkNoModifiers("Imported Expansion in Code System", "expanding");
416      ValueSetExpansionContainsComponent np = addCode(c.getSystem(), c.getCode(), c.getDisplay(), parent, null, expParams, c.getAbstract(), c.getInactive(), filter);
417      copyImportContains(c.getContains(), np, expParams, filter);
418    }
419  }
420
421  private void includeCodes(ConceptSetComponent inc, List<ValueSetExpansionParameterComponent> params, Parameters expParams, boolean heirarchical, List<Extension> extensions) throws ETooCostly, FileNotFoundException, IOException, FHIRException {
422    inc.checkNoModifiers("Compose.include", "expanding");
423    List<ValueSet> imports = new ArrayList<ValueSet>();
424    for (UriType imp : inc.getValueSet()) {
425      imports.add(importValueSet(imp.getValue(), params, expParams));
426    }
427
428    if (!inc.hasSystem()) {
429      if (imports.isEmpty()) // though this is not supposed to be the case
430        return;
431      ValueSet base = imports.get(0);
432      imports.remove(0);
433      base.checkNoModifiers("Imported ValueSet", "expanding");
434      copyImportContains(base.getExpansion().getContains(), null, expParams, imports);
435    } else {
436      CodeSystem cs = context.fetchCodeSystem(inc.getSystem());
437      if ((cs == null || cs.getContent() != CodeSystemContentMode.COMPLETE)) {
438        doServerIncludeCodes(inc, heirarchical, params, imports, expParams, extensions);
439      } else {
440        doInternalIncludeCodes(inc, params, expParams, imports, cs);
441      }
442    }
443  }
444
445  private void doServerIncludeCodes(ConceptSetComponent inc, boolean heirarchical, List<ValueSetExpansionParameterComponent> params, List<ValueSet> imports, Parameters expParams, List<Extension> extensions) throws FHIRException {
446    ValueSetExpansionOutcome vso = context.expandVS(inc, heirarchical);
447    if (vso.getError() != null) {
448      throw new TerminologyServiceException("Unable to expand imported value set: " + vso.getError());
449    }
450    ValueSet vs = vso.getValueset();
451    if (vs.hasVersion()) {
452      if (!existsInParams(params, "version", new UriType(vs.getUrl() + "|" + vs.getVersion()))) {
453        params.add(new ValueSetExpansionParameterComponent().setName("version").setValue(new UriType(vs.getUrl() + "|" + vs.getVersion())));
454      }
455    }
456    for (ValueSetExpansionParameterComponent p : vso.getValueset().getExpansion().getParameter()) {
457      if (!existsInParams(params, p.getName(), p.getValue())) {
458        params.add(p);
459      }
460    }
461    for (Extension ex : vs.getExpansion().getExtension()) {
462      if (Utilities.existsInList(ex.getUrl(), "http://hl7.org/fhir/StructureDefinition/valueset-toocostly", "http://hl7.org/fhir/StructureDefinition/valueset-unclosed")) {
463        if (!hasExtension(extensions, ex.getUrl())) {
464          extensions.add(ex);
465        }
466      }
467    }
468    for (ValueSetExpansionContainsComponent cc : vs.getExpansion().getContains()) {
469      addCodeAndDescendents(cc, null, expParams, imports);
470    }
471  }
472
473  private boolean hasExtension(List<Extension> extensions, String url) {
474    for (Extension ex : extensions) {
475      if (ex.getUrl().equals(url)) {
476        return true;
477      }
478    }
479    return false;
480  }
481
482  public void doInternalIncludeCodes(ConceptSetComponent inc, List<ValueSetExpansionParameterComponent> params, Parameters expParams, List<ValueSet> imports,
483      CodeSystem cs) throws NoTerminologyServiceException, TerminologyServiceException, FHIRException {
484    if (cs == null) {
485      if (context.isNoTerminologyServer())
486        throw new NoTerminologyServiceException("unable to find code system " + inc.getSystem().toString());
487      else
488        throw new TerminologyServiceException("unable to find code system " + inc.getSystem().toString());
489    }
490    cs.checkNoModifiers("Code System", "expanding");
491    if (cs.getContent() != CodeSystemContentMode.COMPLETE)
492      throw new TerminologyServiceException("Code system " + inc.getSystem().toString() + " is incomplete");
493    if (cs.hasVersion())
494      if (!existsInParams(params, "version", new UriType(cs.getUrl() + "|" + cs.getVersion())))
495        params.add(new ValueSetExpansionParameterComponent().setName("version").setValue(new UriType(cs.getUrl() + "|" + cs.getVersion())));
496
497    if (inc.getConcept().size() == 0 && inc.getFilter().size() == 0) {
498      // special case - add all the code system
499      for (ConceptDefinitionComponent def : cs.getConcept()) {
500        addCodeAndDescendents(cs, inc.getSystem(), def, null, expParams, imports, null);
501      }
502    }
503
504    if (!inc.getConcept().isEmpty()) {
505      canBeHeirarchy = false;
506      for (ConceptReferenceComponent c : inc.getConcept()) {
507        c.checkNoModifiers("Code in Code System", "expanding");
508        addCode(inc.getSystem(), c.getCode(), Utilities.noString(c.getDisplay()) ? getCodeDisplay(cs, c.getCode()) : c.getDisplay(), null, convertDesignations(c.getDesignation()), expParams, false,
509            CodeSystemUtilities.isInactive(cs, c.getCode()), imports);
510      }
511    }
512    if (inc.getFilter().size() > 1) {
513      canBeHeirarchy = false; // which will bt the case if we get around to supporting this
514      throw new TerminologyServiceException("Multiple filters not handled yet"); // need to and them, and this isn't done yet. But this shouldn't arise in non loinc and snomed value sets
515    }
516    if (inc.getFilter().size() == 1) {
517      ConceptSetFilterComponent fc = inc.getFilter().get(0);
518      if ("concept".equals(fc.getProperty()) && fc.getOp() == FilterOperator.ISA) {
519        // special: all codes in the target code system under the value
520        ConceptDefinitionComponent def = getConceptForCode(cs.getConcept(), fc.getValue());
521        if (def == null)
522          throw new TerminologyServiceException("Code '" + fc.getValue() + "' not found in system '" + inc.getSystem() + "'");
523        addCodeAndDescendents(cs, inc.getSystem(), def, null, expParams, imports, null);
524      } else if ("concept".equals(fc.getProperty()) && fc.getOp() == FilterOperator.ISNOTA) {
525        // special: all codes in the target code system that are not under the value
526        ConceptDefinitionComponent defEx = getConceptForCode(cs.getConcept(), fc.getValue());
527        if (defEx == null)
528          throw new TerminologyServiceException("Code '" + fc.getValue() + "' not found in system '" + inc.getSystem() + "'");
529        for (ConceptDefinitionComponent def : cs.getConcept()) {
530          addCodeAndDescendents(cs, inc.getSystem(), def, null, expParams, imports, defEx);
531        }
532      } else if ("concept".equals(fc.getProperty()) && fc.getOp() == FilterOperator.DESCENDENTOF) {
533        // special: all codes in the target code system under the value
534        ConceptDefinitionComponent def = getConceptForCode(cs.getConcept(), fc.getValue());
535        if (def == null)
536          throw new TerminologyServiceException("Code '" + fc.getValue() + "' not found in system '" + inc.getSystem() + "'");
537        for (ConceptDefinitionComponent c : def.getConcept())
538          addCodeAndDescendents(cs, inc.getSystem(), c, null, expParams, imports, null);
539      } else if ("display".equals(fc.getProperty()) && fc.getOp() == FilterOperator.EQUAL) {
540        // gg; note: wtf is this: if the filter is display=v, look up the code 'v', and see if it's diplsay is 'v'?
541        canBeHeirarchy = false;
542        ConceptDefinitionComponent def = getConceptForCode(cs.getConcept(), fc.getValue());
543        if (def != null) {
544          if (isNotBlank(def.getDisplay()) && isNotBlank(fc.getValue())) {
545            if (def.getDisplay().contains(fc.getValue())) {
546              addCode(inc.getSystem(), def.getCode(), def.getDisplay(), null, def.getDesignation(), expParams, CodeSystemUtilities.isNotSelectable(cs, def), CodeSystemUtilities.isInactive(cs, def),
547                  imports);
548            }
549          }
550        }
551      } else
552        throw new NotImplementedException("Search by property[" + fc.getProperty() + "] and op[" + fc.getOp() + "] is not supported yet");
553    }
554  }
555
556  private List<ConceptDefinitionDesignationComponent> convertDesignations(List<ConceptReferenceDesignationComponent> list) {
557    List<ConceptDefinitionDesignationComponent> res = new ArrayList<CodeSystem.ConceptDefinitionDesignationComponent>();
558    for (ConceptReferenceDesignationComponent t : list) {
559      ConceptDefinitionDesignationComponent c = new ConceptDefinitionDesignationComponent();
560      c.setLanguage(t.getLanguage());
561      c.setUse(t.getUse());
562      c.setValue(t.getValue());
563    }
564    return res;
565  }
566
567  private String key(String uri, String code) {
568    return "{" + uri + "}" + code;
569  }
570
571  private String key(ValueSetExpansionContainsComponent c) {
572    return key(c.getSystem(), c.getCode());
573  }
574
575}