001package org.hl7.fhir.r4.utils;
002
003/*-
004 * #%L
005 * org.hl7.fhir.r4
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
024/*
025Copyright (c) 2011+, HL7, Inc
026All rights reserved.
027
028Redistribution and use in source and binary forms, with or without modification, 
029are permitted provided that the following conditions are met:
030
031 * Redistributions of source code must retain the above copyright notice, this 
032   list of conditions and the following disclaimer.
033 * Redistributions in binary form must reproduce the above copyright notice, 
034   this list of conditions and the following disclaimer in the documentation 
035   and/or other materials provided with the distribution.
036 * Neither the name of HL7 nor the names of its contributors may be used to 
037   endorse or promote products derived from this software without specific 
038   prior written permission.
039
040THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
041ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
042WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
043IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
044INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
045NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
046PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
047WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
048ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
049POSSIBILITY OF SUCH DAMAGE.
050
051 */
052
053import java.util.ArrayList;
054import java.util.HashMap;
055import java.util.Iterator;
056import java.util.List;
057import java.util.Map;
058
059import org.apache.commons.lang3.StringUtils;
060import org.fhir.ucum.Utilities;
061import org.hl7.fhir.exceptions.FHIRException;
062import org.hl7.fhir.r4.model.BooleanType;
063import org.hl7.fhir.r4.model.CanonicalType;
064import org.hl7.fhir.r4.model.CodeSystem.ConceptDefinitionComponent;
065import org.hl7.fhir.r4.model.CodeType;
066import org.hl7.fhir.r4.model.CodeableConcept;
067import org.hl7.fhir.r4.model.Coding;
068import org.hl7.fhir.r4.model.DomainResource;
069import org.hl7.fhir.r4.model.Element;
070import org.hl7.fhir.r4.model.ElementDefinition;
071import org.hl7.fhir.r4.model.Extension;
072import org.hl7.fhir.r4.model.ExtensionHelper;
073import org.hl7.fhir.r4.model.Factory;
074import org.hl7.fhir.r4.model.Identifier;
075import org.hl7.fhir.r4.model.IntegerType;
076import org.hl7.fhir.r4.model.MarkdownType;
077import org.hl7.fhir.r4.model.OperationOutcome.OperationOutcomeIssueComponent;
078import org.hl7.fhir.r4.model.PrimitiveType;
079import org.hl7.fhir.r4.model.Questionnaire.QuestionnaireItemComponent;
080import org.hl7.fhir.r4.model.Questionnaire.QuestionnaireItemType;
081import org.hl7.fhir.r4.model.StringType;
082import org.hl7.fhir.r4.model.Type;
083import org.hl7.fhir.r4.model.UriType;
084import org.hl7.fhir.r4.model.ValueSet.ConceptReferenceComponent;
085import org.hl7.fhir.r4.model.ValueSet.ConceptSetComponent;
086import org.hl7.fhir.utilities.StandardsStatus;
087import org.hl7.fhir.utilities.validation.ValidationMessage;
088import org.hl7.fhir.utilities.validation.ValidationMessage.IssueSeverity;
089import org.hl7.fhir.utilities.validation.ValidationMessage.IssueType;
090import org.hl7.fhir.utilities.validation.ValidationMessage.Source;
091
092
093public class ToolingExtensions {
094
095  // validated
096//  private static final String EXT_OID = "http://hl7.org/fhir/StructureDefinition/valueset-oid";
097//  public static final String EXT_DEPRECATED = "http://hl7.org/fhir/StructureDefinition/codesystem-deprecated";
098  public static final String EXT_DEFINITION = "http://hl7.org/fhir/StructureDefinition/valueset-concept-definition";
099  public static final String EXT_CS_COMMENT = "http://hl7.org/fhir/StructureDefinition/codesystem-concept-comments";
100  public static final String EXT_VS_COMMENT = "http://hl7.org/fhir/StructureDefinition/valueset-concept-comments";
101  private static final String EXT_IDENTIFIER = "http://hl7.org/fhir/StructureDefinition/identifier";
102  public static final String EXT_TRANSLATION = "http://hl7.org/fhir/StructureDefinition/translation";
103  public static final String EXT_ISSUE_SOURCE = "http://hl7.org/fhir/StructureDefinition/operationoutcome-issue-source";
104  public static final String EXT_ISSUE_LINE = "http://hl7.org/fhir/StructureDefinition/operationoutcome-issue-line";
105  public static final String EXT_ISSUE_COL = "http://hl7.org/fhir/StructureDefinition/operationoutcome-issue-col";
106  public static final String EXT_DISPLAY_HINT = "http://hl7.org/fhir/StructureDefinition/structuredefinition-display-hint"; 
107  public static final String EXT_REPLACED_BY = "http://hl7.org/fhir/StructureDefinition/valueset-replacedby";
108  public static final String EXT_REGEX = "http://hl7.org/fhir/StructureDefinition/regex"; 
109  public static final String EXT_CONTROL = "http://hl7.org/fhir/StructureDefinition/questionnaire-itemControl"; 
110  public static final String EXT_MINOCCURS = "http://hl7.org/fhir/StructureDefinition/questionnaire-minOccurs"; 
111  public static final String EXT_MAXOCCURS = "http://hl7.org/fhir/StructureDefinition/questionnaire-maxOccurs";
112  public static final String EXT_ALLOWEDRESOURCE = "http://hl7.org/fhir/StructureDefinition/questionnaire-allowedResource";
113  public static final String EXT_REFERENCEFILTER = "http://hl7.org/fhir/StructureDefinition/questionnaire-referenceFilter";
114  public static final String EXT_CODE_GENERATION_PARENT = "http://hl7.org/fhir/StructureDefinition/structuredefinition-codegen-super";
115  public static final String EXT_HIERARCHY = "http://hl7.org/fhir/StructureDefinition/structuredefinition-hierarchy";
116  public static final String EXT_BEST_PRACTICE = "http://hl7.org/fhir/StructureDefinition/elementdefinition-bestpractice";
117  public static final String EXT_BEST_PRACTICE_EXPLANATION = "http://hl7.org/fhir/StructureDefinition/elementdefinition-bestpractice-explanation";
118  // unregistered?
119  public static final String EXT_MAPPING_PREFIX = "http://hl7.org/fhir/tools/StructureDefinition/logical-mapping-prefix";
120  public static final String EXT_MAPPING_SUFFIX = "http://hl7.org/fhir/tools/StructureDefinition/logical-mapping-suffix";
121
122//  public static final String EXT_FLYOVER = "http://hl7.org/fhir/Profile/questionnaire-extensions#flyover";
123  public static final String EXT_QTYPE = "http://hl7.org/fhir/StructureDefinition/questionnnaire-baseType";
124//  private static final String EXT_QREF = "http://www.healthintersections.com.au/fhir/Profile/metadata#reference";
125//  private static final String EXTENSION_FILTER_ONLY = "http://www.healthintersections.com.au/fhir/Profile/metadata#expandNeedsFilter";
126//  private static final String EXT_TYPE = "http://www.healthintersections.com.au/fhir/Profile/metadata#type";
127//  private static final String EXT_REFERENCE = "http://www.healthintersections.com.au/fhir/Profile/metadata#reference";
128  private static final String EXT_FHIRTYPE = "http://hl7.org/fhir/StructureDefinition/questionnaire-fhirType";
129  private static final String EXT_ALLOWABLE_UNITS = "http://hl7.org/fhir/StructureDefinition/elementdefinition-allowedUnits";
130  public static final String EXT_CIMI_REFERENCE = "http://hl7.org/fhir/StructureDefinition/cimi-reference";
131  public static final String EXT_UNCLOSED = "http://hl7.org/fhir/StructureDefinition/valueset-unclosed";
132  public static final String EXT_FMM_LEVEL = "http://hl7.org/fhir/StructureDefinition/structuredefinition-fmm";
133  public static final String EXT_SEC_CAT = "http://hl7.org/fhir/StructureDefinition/structuredefinition-security-category";
134  public static final String EXT_RESOURCE_CATEGORY = "http://hl7.org/fhir/StructureDefinition/structuredefinition-category";
135  public static final String EXT_TABLE_NAME = "http://hl7.org/fhir/StructureDefinition/structuredefinition-table-name";
136  public static final String EXT_OO_FILE = "http://hl7.org/fhir/StructureDefinition/operationoutcome-file";
137  public static final String EXT_WORKGROUP = "http://hl7.org/fhir/StructureDefinition/structuredefinition-wg";
138  public static final String EXT_STANDARDS_STATUS = "http://hl7.org/fhir/StructureDefinition/structuredefinition-standards-status";
139  public static final String EXT_NORMATIVE_VERSION = "http://hl7.org/fhir/StructureDefinition/structuredefinition-normative-version";
140  public static final String EXT_IGP_BASE = "http://hl7.org/fhir/StructureDefinition/igpublisher-res-base";
141  public static final String EXT_IGP_DEFNS = "http://hl7.org/fhir/StructureDefinition/igpublisher-res-defns";
142  public static final String EXT_IGP_FORMAT = "http://hl7.org/fhir/StructureDefinition/igpublisher-res-format";
143  public static final String EXT_IGP_SOURCE = "http://hl7.org/fhir/StructureDefinition/igpublisher-res-source";
144  public static final String EXT_IGP_VERSION = "http://hl7.org/fhir/StructureDefinition/igpublisher-res-version";
145  public static final String EXT_IGP_RESOURCES = "http://hl7.org/fhir/StructureDefinition/igpublisher-folder-resource";
146  public static final String EXT_IGP_PAGES = "http://hl7.org/fhir/StructureDefinition/igpublisher-folder-pages";
147  public static final String EXT_IGP_SPREADSHEET = "http://hl7.org/fhir/StructureDefinition/igpublisher-spreadsheet";
148  public static final String EXT_IGP_MAPPING_CSV = "http://hl7.org/fhir/StructureDefinition/igpublisher-mapping-csv";
149  public static final String EXT_IGP_BUNDLE = "http://hl7.org/fhir/StructureDefinition/igpublisher-bundle";
150  public static final String EXT_IGP_RESOURCE_INFO = "http://hl7.org/fhir/tools/StructureDefinition/resource-information";
151  public static final String EXT_IGP_LOADVERSION = "http://hl7.org/fhir/StructureDefinition/igpublisher-loadversion";
152  public static final String EXT_MAX_VALUESET = "http://hl7.org/fhir/StructureDefinition/elementdefinition-maxValueSet";
153  public static final String EXT_MIN_VALUESET = "http://hl7.org/fhir/StructureDefinition/elementdefinition-minValueSet";
154  public static final String EXT_PROFILE_ELEMENT = "http://hl7.org/fhir/StructureDefinition/elementdefinition-profile-element";
155  public static final String EXT_LIST_PACKAGE = "http://hl7.org/fhir/StructureDefinition/list-packageId";
156  public static final String EXT_MAPPING_NAME = "http://hl7.org/fhir/tools/StructureDefinition/conceptmap-source-name";
157  public static final String EXT_MAPPING_TYPE = "http://hl7.org/fhir/tools/StructureDefinition/conceptmap-source-type";
158  public static final String EXT_MAPPING_CARD = "http://hl7.org/fhir/tools/StructureDefinition/conceptmap-source-cardinality";
159  public static final String EXT_MAPPING_TGTTYPE = "http://hl7.org/fhir/tools/StructureDefinition/conceptmap-target-type";
160  public static final String EXT_MAPPING_TGTCARD = "http://hl7.org/fhir/tools/StructureDefinition/conceptmap-target-cardinality";
161  public static final String EXT_PRIVATE_BASE = "http://hl7.org/fhir/tools/";
162  public static final String EXT_ALLOWED_TYPE =  "http://hl7.org/fhir/StructureDefinition/operationdefinition-allowed-type";
163  public static final String EXT_FHIR_TYPE = "http://hl7.org/fhir/StructureDefinition/structuredefinition-fhir-type";
164  public static final String EXT_XML_TYPE = "http://hl7.org/fhir/StructureDefinition/structuredefinition-xml-type";
165
166  // specific extension helpers
167
168  public static Extension makeIssueSource(Source source) {
169    Extension ex = new Extension();
170    // todo: write this up and get it published with the pack (and handle the redirect?)
171    ex.setUrl(ToolingExtensions.EXT_ISSUE_SOURCE);
172    CodeType c = new CodeType();
173    c.setValue(source.toString());
174    ex.setValue(c);
175    return ex;
176  }
177
178  public static boolean hasExtension(DomainResource de, String url) {
179    return getExtension(de, url) != null;
180  }
181
182  public static boolean hasExtension(Element e, String url) {
183    return getExtension(e, url) != null;
184  }
185
186//  public static void addStringExtension(DomainResource dr, String url, String content) {
187//    if (!StringUtils.isBlank(content)) {
188//      Extension ex = getExtension(dr, url);
189//      if (ex != null)
190//        ex.setValue(new StringType(content));
191//      else
192//        dr.getExtension().add(Factory.newExtension(url, new StringType(content), true));   
193//    }
194//  }
195
196  public static void addMarkdownExtension(DomainResource dr, String url, String content) {
197    if (!StringUtils.isBlank(content)) {
198      Extension ex = getExtension(dr, url);
199      if (ex != null)
200        ex.setValue(new StringType(content));
201      else
202        dr.getExtension().add(Factory.newExtension(url, new MarkdownType(content), true));   
203    }
204  }
205
206  public static void addStringExtension(Element e, String url, String content) {
207    if (!StringUtils.isBlank(content)) {
208      Extension ex = getExtension(e, url);
209      if (ex != null)
210        ex.setValue(new StringType(content));
211      else
212        e.getExtension().add(Factory.newExtension(url, new StringType(content), true));   
213    }
214  }
215
216  public static void addCodeExtension(Element e, String url, String content) {
217    if (!StringUtils.isBlank(content)) {
218      Extension ex = getExtension(e, url);
219      if (ex != null)
220        ex.setValue(new CodeType(content));
221      else
222        e.getExtension().add(Factory.newExtension(url, new CodeType(content), true));   
223    }
224  }
225
226  public static void addStringExtension(DomainResource e, String url, String content) {
227    if (!StringUtils.isBlank(content)) {
228      Extension ex = getExtension(e, url);
229      if (ex != null)
230        ex.setValue(new StringType(content));
231      else
232        e.getExtension().add(Factory.newExtension(url, new StringType(content), true));   
233    }
234  }
235
236  public static void addBooleanExtension(Element e, String url, boolean content) {
237    Extension ex = getExtension(e, url);
238    if (ex != null)
239      ex.setValue(new BooleanType(content));
240    else
241      e.getExtension().add(Factory.newExtension(url, new BooleanType(content), true));   
242  }
243
244  public static void addBooleanExtension(DomainResource e, String url, boolean content) {
245    Extension ex = getExtension(e, url);
246    if (ex != null)
247      ex.setValue(new BooleanType(content));
248    else
249      e.getExtension().add(Factory.newExtension(url, new BooleanType(content), true));   
250  }
251
252  public static void addIntegerExtension(DomainResource dr, String url, int value) {
253    Extension ex = getExtension(dr, url);
254    if (ex != null)
255      ex.setValue(new IntegerType(value));
256    else
257      dr.getExtension().add(Factory.newExtension(url, new IntegerType(value), true));   
258  }
259
260  public static void addCodeExtension(DomainResource dr, String url, String value) {
261    Extension ex = getExtension(dr, url);
262    if (ex != null)
263      ex.setValue(new CodeType(value));
264    else
265      dr.getExtension().add(Factory.newExtension(url, new CodeType(value), true));   
266  }
267
268  public static void addVSComment(ConceptSetComponent nc, String comment) {
269    if (!StringUtils.isBlank(comment))
270      nc.getExtension().add(Factory.newExtension(EXT_VS_COMMENT, Factory.newString_(comment), true));   
271  }
272  public static void addVSComment(ConceptReferenceComponent nc, String comment) {
273    if (!StringUtils.isBlank(comment))
274      nc.getExtension().add(Factory.newExtension(EXT_VS_COMMENT, Factory.newString_(comment), true));   
275  }
276
277  public static void addCSComment(ConceptDefinitionComponent nc, String comment) {
278    if (!StringUtils.isBlank(comment))
279      nc.getExtension().add(Factory.newExtension(EXT_CS_COMMENT, Factory.newString_(comment), true));   
280  }
281
282//  public static void markDeprecated(Element nc) {
283//    setDeprecated(nc);   
284//  }
285//
286
287  public static void addDefinition(Element nc, String definition) {
288    if (!StringUtils.isBlank(definition))
289      nc.getExtension().add(Factory.newExtension(EXT_DEFINITION, Factory.newString_(definition), true));   
290  }
291
292  public static void addDisplayHint(Element def, String hint) {
293    if (!StringUtils.isBlank(hint))
294      def.getExtension().add(Factory.newExtension(EXT_DISPLAY_HINT, Factory.newString_(hint), true));   
295  }
296
297  public static String getDisplayHint(Element def) {
298    return readStringExtension(def, EXT_DISPLAY_HINT);    
299  }
300
301  public static String readStringExtension(Element c, String uri) {
302    Extension ex = ExtensionHelper.getExtension(c, uri);
303    if (ex == null)
304      return null;
305    if (ex.getValue() instanceof UriType)
306      return ((UriType) ex.getValue()).getValue();
307    if (ex.getValue() instanceof CanonicalType)
308      return ((CanonicalType) ex.getValue()).getValue();
309    if (ex.getValue() instanceof CodeType)
310      return ((CodeType) ex.getValue()).getValue();
311    if (ex.getValue() instanceof IntegerType)
312      return ((IntegerType) ex.getValue()).asStringValue();
313    if ((ex.getValue() instanceof MarkdownType))
314      return ((MarkdownType) ex.getValue()).getValue();
315    if (!(ex.getValue() instanceof StringType))
316      return null;
317    return ((StringType) ex.getValue()).getValue();
318  }
319
320  public static String readStringExtension(DomainResource c, String uri) {
321    Extension ex = getExtension(c, uri);
322    if (ex == null)
323      return null;
324    if ((ex.getValue() instanceof StringType))
325      return ((StringType) ex.getValue()).getValue();
326    if ((ex.getValue() instanceof UriType))
327      return ((UriType) ex.getValue()).getValue();
328    if (ex.getValue() instanceof CodeType)
329      return ((CodeType) ex.getValue()).getValue();
330    if (ex.getValue() instanceof IntegerType)
331      return ((IntegerType) ex.getValue()).asStringValue();
332    if ((ex.getValue() instanceof MarkdownType))
333      return ((MarkdownType) ex.getValue()).getValue();
334    return null;
335  }
336
337  @SuppressWarnings("unchecked")
338  public static PrimitiveType<Type> readPrimitiveExtension(DomainResource c, String uri) {
339    Extension ex = getExtension(c, uri);
340    if (ex == null)
341      return null;
342    return (PrimitiveType<Type>) ex.getValue();
343  }
344
345  public static boolean findStringExtension(Element c, String uri) {
346    Extension ex = ExtensionHelper.getExtension(c, uri);
347    if (ex == null)
348      return false;
349    if (!(ex.getValue() instanceof StringType))
350      return false;
351    return !StringUtils.isBlank(((StringType) ex.getValue()).getValue());
352  }
353
354  public static Boolean readBooleanExtension(Element c, String uri) {
355    Extension ex = ExtensionHelper.getExtension(c, uri);
356    if (ex == null)
357      return null;
358    if (!(ex.getValue() instanceof BooleanType))
359      return null;
360    return ((BooleanType) ex.getValue()).getValue();
361  }
362
363  public static boolean findBooleanExtension(Element c, String uri) {
364    Extension ex = ExtensionHelper.getExtension(c, uri);
365    if (ex == null)
366      return false;
367    if (!(ex.getValue() instanceof BooleanType))
368      return false;
369    return true;
370  }
371
372  public static Boolean readBooleanExtension(DomainResource c, String uri) {
373    Extension ex = ExtensionHelper.getExtension(c, uri);
374    if (ex == null)
375      return null;
376    if (!(ex.getValue() instanceof BooleanType))
377      return null;
378    return ((BooleanType) ex.getValue()).getValue();
379  }
380
381  public static boolean readBoolExtension(DomainResource c, String uri) {
382    Extension ex = ExtensionHelper.getExtension(c, uri);
383    if (ex == null)
384      return false;
385    if (!(ex.getValue() instanceof BooleanType))
386      return false;
387    return ((BooleanType) ex.getValue()).getValue();
388  }
389
390  public static boolean findBooleanExtension(DomainResource c, String uri) {
391    Extension ex = ExtensionHelper.getExtension(c, uri);
392    if (ex == null)
393      return false;
394    if (!(ex.getValue() instanceof BooleanType))
395      return false;
396    return true;
397  }
398
399  public static String getCSComment(ConceptDefinitionComponent c) {
400    return readStringExtension(c, EXT_CS_COMMENT);    
401  }
402//
403//  public static Boolean getDeprecated(Element c) {
404//    return readBooleanExtension(c, EXT_DEPRECATED);    
405//  }
406
407  public static boolean hasCSComment(ConceptDefinitionComponent c) {
408    return findStringExtension(c, EXT_CS_COMMENT);    
409  }
410
411//  public static boolean hasDeprecated(Element c) {
412//    return findBooleanExtension(c, EXT_DEPRECATED);    
413//  }
414
415  public static void addFlyOver(QuestionnaireItemComponent item, String text){
416    if (!StringUtils.isBlank(text)) {
417        QuestionnaireItemComponent display = item.addItem();
418        display.setType(QuestionnaireItemType.DISPLAY);
419        display.setText(text);
420        display.getExtension().add(Factory.newExtension(EXT_CONTROL, Factory.newCodeableConcept("flyover", "http://hl7.org/fhir/questionnaire-item-control", "Fly-over"), true));
421    }
422  }
423
424  public static void addMin(QuestionnaireItemComponent item, int min) {
425    item.getExtension().add(Factory.newExtension(EXT_MINOCCURS, Factory.newInteger(min), true));
426  }
427  
428  public static void addMax(QuestionnaireItemComponent item, int max) {
429    item.getExtension().add(Factory.newExtension(EXT_MAXOCCURS, Factory.newInteger(max), true));
430  }
431  
432  public static void addFhirType(QuestionnaireItemComponent group, String value) {
433    group.getExtension().add(Factory.newExtension(EXT_FHIRTYPE, Factory.newString_(value), true));       
434  }
435
436  public static void addControl(QuestionnaireItemComponent group, String value) {
437    group.getExtension().add(Factory.newExtension(EXT_CONTROL, Factory.newCodeableConcept(value, "http://hl7.org/fhir/questionnaire-item-control", value), true));
438  }
439
440  public static void addAllowedResource(QuestionnaireItemComponent group, String value) {
441    group.getExtension().add(Factory.newExtension(EXT_ALLOWEDRESOURCE, Factory.newCode(value), true));       
442  }
443
444  public static void addReferenceFilter(QuestionnaireItemComponent group, String value) {
445    group.getExtension().add(Factory.newExtension(EXT_REFERENCEFILTER, Factory.newString_(value), true));       
446  }
447
448  public static void addIdentifier(Element element, Identifier value) {
449    element.getExtension().add(Factory.newExtension(EXT_IDENTIFIER, value, true));       
450  }
451
452  /**
453   * @param name the identity of the extension of interest
454   * @return The extension, if on this element, else null
455   */
456  public static Extension getExtension(DomainResource resource, String name) {
457    if (name == null)
458      return null;
459    if (!resource.hasExtension())
460      return null;
461    for (Extension e : resource.getExtension()) {
462      if (name.equals(e.getUrl()))
463        return e;
464    }
465    return null;
466  }
467
468  public static Extension getExtension(Element el, String name) {
469    if (name == null)
470      return null;
471    if (!el.hasExtension())
472      return null;
473    for (Extension e : el.getExtension()) {
474      if (name.equals(e.getUrl()))
475        return e;
476    }
477    return null;
478  }
479
480  public static void setStringExtension(DomainResource resource, String uri, String value) {
481    if (Utilities.noString(value))
482      return;
483        Extension ext = getExtension(resource, uri);
484    if (ext != null)
485      ext.setValue(new StringType(value));
486    else
487      resource.getExtension().add(new Extension(new UriType(uri)).setValue(new StringType(value)));
488  }
489
490  public static void setStringExtension(Element resource, String uri, String value) {
491    if (Utilities.noString(value))
492      return;
493        Extension ext = getExtension(resource, uri);
494    if (ext != null)
495      ext.setValue(new StringType(value));
496    else
497      resource.getExtension().add(new Extension(new UriType(uri)).setValue(new StringType(value)));
498  }
499
500  public static void setCodeExtension(DomainResource resource, String uri, String value) {
501    if (Utilities.noString(value))
502      return;
503    
504    Extension ext = getExtension(resource, uri);
505    if (ext != null)
506      ext.setValue(new CodeType(value));
507    else
508      resource.getExtension().add(new Extension(new UriType(uri)).setValue(new CodeType(value)));
509  }
510
511  public static void setCodeExtension(Element element, String uri, String value) {
512    if (Utilities.noString(value))
513      return;
514    
515    Extension ext = getExtension(element, uri);
516    if (ext != null)
517      ext.setValue(new CodeType(value));
518    else
519      element.getExtension().add(new Extension(new UriType(uri)).setValue(new CodeType(value)));
520  }
521
522  public static void setIntegerExtension(DomainResource resource, String uri, int value) {
523    Extension ext = getExtension(resource, uri);
524    if (ext != null)
525      ext.setValue(new IntegerType(value));
526    else
527      resource.getExtension().add(new Extension(new UriType(uri)).setValue(new IntegerType(value)));
528  }
529
530//  public static String getOID(CodeSystem define) {
531//    return readStringExtension(define, EXT_OID);    
532//  }
533//
534//  public static String getOID(ValueSet vs) {
535//    return readStringExtension(vs, EXT_OID);    
536//  }
537//
538//  public static void setOID(CodeSystem define, String oid) throws FHIRFormatError, URISyntaxException {
539//    if (!oid.startsWith("urn:oid:"))
540//      throw new FHIRFormatError("Error in OID format");
541//    if (oid.startsWith("urn:oid:urn:oid:"))
542//      throw new FHIRFormatError("Error in OID format");
543//    if (!hasExtension(define, EXT_OID))
544//    define.getExtension().add(Factory.newExtension(EXT_OID, Factory.newUri(oid), false));       
545//    else if (!oid.equals(readStringExtension(define, EXT_OID)))
546//      throw new Error("Attempt to assign multiple OIDs to a code system");
547//  }
548//  public static void setOID(ValueSet vs, String oid) throws FHIRFormatError, URISyntaxException {
549//    if (!oid.startsWith("urn:oid:"))
550//      throw new FHIRFormatError("Error in OID format");
551//    if (oid.startsWith("urn:oid:urn:oid:"))
552//      throw new FHIRFormatError("Error in OID format");
553//    if (!hasExtension(vs, EXT_OID))
554//    vs.getExtension().add(Factory.newExtension(EXT_OID, Factory.newUri(oid), false));       
555//    else if (!oid.equals(readStringExtension(vs, EXT_OID)))
556//      throw new Error("Attempt to assign multiple OIDs to value set "+vs.getName()+" ("+vs.getUrl()+"). Has "+readStringExtension(vs, EXT_OID)+", trying to add "+oid);
557//  }
558
559  public static boolean hasLanguageTranslation(Element element, String lang) {
560    for (Extension e : element.getExtension()) {
561      if (e.getUrl().equals(EXT_TRANSLATION)) {
562        Extension e1 = ExtensionHelper.getExtension(e, "lang");
563
564        if (e1 != null && e1.getValue() instanceof CodeType && ((CodeType) e.getValue()).getValue().equals(lang))
565          return true;
566      }
567    }
568    return false;
569  }
570
571  public static String getLanguageTranslation(Element element, String lang) {
572    for (Extension e : element.getExtension()) {
573      if (e.getUrl().equals(EXT_TRANSLATION)) {
574        Extension e1 = ExtensionHelper.getExtension(e, "lang");
575
576        if (e1 != null && e1.getValue() instanceof CodeType && ((CodeType) e.getValue()).getValue().equals(lang)) {
577          e1 = ExtensionHelper.getExtension(e, "content");
578          return ((StringType) e.getValue()).getValue();
579        }
580      }
581    }
582    return null;
583  }
584
585  public static void addLanguageTranslation(Element element, String lang, String value) {
586    if (Utilities.noString(lang) || Utilities.noString(value))
587      return;
588    
589    Extension extension = new Extension().setUrl(EXT_TRANSLATION);
590    extension.addExtension().setUrl("lang").setValue(new CodeType(lang));
591    extension.addExtension().setUrl("content").setValue(new StringType(value));
592    element.getExtension().add(extension);
593  }
594
595  public static Type getAllowedUnits(ElementDefinition eld) {
596    for (Extension e : eld.getExtension()) 
597      if (e.getUrl().equals(EXT_ALLOWABLE_UNITS)) 
598        return e.getValue();
599    return null;
600  }
601
602  public static void setAllowableUnits(ElementDefinition eld, CodeableConcept cc) {
603    for (Extension e : eld.getExtension()) 
604      if (e.getUrl().equals(EXT_ALLOWABLE_UNITS)) {
605        e.setValue(cc);
606        return;
607      }
608    eld.getExtension().add(new Extension().setUrl(EXT_ALLOWABLE_UNITS).setValue(cc));
609  }
610
611  public static List<Extension> getExtensions(Element element, String url) {
612    List<Extension> results = new ArrayList<Extension>();
613    for (Extension ex : element.getExtension())
614      if (ex.getUrl().equals(url))
615        results.add(ex);
616    return results;
617  }
618
619  public static List<Extension> getExtensions(DomainResource resource, String url) {
620    List<Extension> results = new ArrayList<Extension>();
621    for (Extension ex : resource.getExtension())
622      if (ex.getUrl().equals(url))
623        results.add(ex);
624    return results;
625  }
626
627//  public static void addDEReference(DataElement de, String value) {
628//    for (Extension e : de.getExtension()) 
629//      if (e.getUrl().equals(EXT_CIMI_REFERENCE)) {
630//        e.setValue(new UriType(value));
631//        return;
632//      }
633//    de.getExtension().add(new Extension().setUrl(EXT_CIMI_REFERENCE).setValue(new UriType(value)));
634//  }
635
636//  public static void setDeprecated(Element nc) {
637//    for (Extension e : nc.getExtension()) 
638//      if (e.getUrl().equals(EXT_DEPRECATED)) {
639//        e.setValue(new BooleanType(true));
640//        return;
641//      }
642//    nc.getExtension().add(new Extension().setUrl(EXT_DEPRECATED).setValue(new BooleanType(true)));    
643//  }
644
645  public static void setExtension(Element focus, String url, Coding c) {
646    for (Extension e : focus.getExtension()) 
647      if (e.getUrl().equals(url)) {
648        e.setValue(c);
649        return;
650      }
651    focus.getExtension().add(new Extension().setUrl(url).setValue(c));    
652  }
653
654  public static void removeExtension(DomainResource focus, String url) {
655    Iterator<Extension> i = focus.getExtension().iterator();
656    while (i.hasNext()) {
657      Extension e = i.next(); // must be called before you can call i.remove()
658      if (e.getUrl().equals(url)) {
659        i.remove();
660      }
661    }
662  }
663  
664  public static void removeExtension(Element focus, String url) {
665    Iterator<Extension> i = focus.getExtension().iterator();
666    while (i.hasNext()) {
667      Extension e = i.next(); // must be called before you can call i.remove()
668      if (e.getUrl().equals(url)) {
669        i.remove();
670      }
671    }
672  }
673
674  public static int readIntegerExtension(DomainResource dr, String uri, int defaultValue) {
675    Extension ex = ExtensionHelper.getExtension(dr, uri);
676    if (ex == null)
677      return defaultValue;
678    if (ex.getValue() instanceof IntegerType)
679      return ((IntegerType) ex.getValue()).getValue();
680    throw new Error("Unable to read extension "+uri+" as an integer");
681  }
682
683  public static int readIntegerExtension(Element e, String uri, int defaultValue) {
684    Extension ex = ExtensionHelper.getExtension(e, uri);
685    if (ex == null)
686      return defaultValue;
687    if (ex.getValue() instanceof IntegerType)
688      return ((IntegerType) ex.getValue()).getValue();
689    throw new Error("Unable to read extension "+uri+" as an integer");
690  }
691
692  public static Map<String, String> getLanguageTranslations(Element e) {
693    Map<String, String> res = new HashMap<String, String>();
694    for (Extension ext : e.getExtension()) {
695      if (ext.getUrl().equals(EXT_TRANSLATION)) {
696        String lang = readStringExtension(ext, "lang");
697        String value = readStringExtension(ext, "content");
698        res.put(lang,  value);
699      }
700    }
701    return res;
702  }
703
704  public static StandardsStatus getStandardsStatus(DomainResource dr) throws FHIRException {
705    return StandardsStatus.fromCode(ToolingExtensions.readStringExtension(dr, ToolingExtensions.EXT_STANDARDS_STATUS));
706  }
707
708  public static void setStandardsStatus(DomainResource dr, StandardsStatus status, String normativeVersion) {
709    if (status == null)
710      ToolingExtensions.removeExtension(dr, ToolingExtensions.EXT_STANDARDS_STATUS);
711    else
712      ToolingExtensions.setCodeExtension(dr, ToolingExtensions.EXT_STANDARDS_STATUS, status.toCode());
713    if (normativeVersion == null)
714      ToolingExtensions.removeExtension(dr, ToolingExtensions.EXT_NORMATIVE_VERSION);
715    else
716      ToolingExtensions.setCodeExtension(dr, ToolingExtensions.EXT_NORMATIVE_VERSION, normativeVersion);
717  }
718
719  public static void setStandardsStatus(Element dr, StandardsStatus status, String normativeVersion) {
720    if (status == null)
721      ToolingExtensions.removeExtension(dr, ToolingExtensions.EXT_STANDARDS_STATUS);
722    else
723      ToolingExtensions.setCodeExtension(dr, ToolingExtensions.EXT_STANDARDS_STATUS, status.toCode());
724    if (normativeVersion == null)
725      ToolingExtensions.removeExtension(dr, ToolingExtensions.EXT_NORMATIVE_VERSION);
726    else
727      ToolingExtensions.setCodeExtension(dr, ToolingExtensions.EXT_NORMATIVE_VERSION, normativeVersion);
728  }
729
730  public static ValidationMessage readValidationMessage(OperationOutcomeIssueComponent issue, Source source) {
731    ValidationMessage vm = new ValidationMessage();
732    vm.setSource(source);
733    vm.setLevel(mapSeverity(issue.getSeverity()));
734    vm.setType(mapType(issue.getCode()));
735    if (issue.hasExtension(ToolingExtensions.EXT_ISSUE_LINE))
736      vm.setLine(ToolingExtensions.readIntegerExtension(issue, ToolingExtensions.EXT_ISSUE_LINE, 0));
737    if (issue.hasExtension(ToolingExtensions.EXT_ISSUE_COL))
738      vm.setCol(ToolingExtensions.readIntegerExtension(issue, ToolingExtensions.EXT_ISSUE_COL, 0));
739    if (issue.hasExpression())
740      vm.setLocation(issue.getExpression().get(0).asStringValue());
741    vm.setMessage(issue.getDetails().getText());
742    if (issue.hasExtension("http://hl7.org/fhir/StructureDefinition/rendering-xhtml"))
743      vm.setHtml(ToolingExtensions.readStringExtension(issue, "http://hl7.org/fhir/StructureDefinition/rendering-xhtml"));
744    return vm;
745  }
746
747  private static IssueType mapType(org.hl7.fhir.r4.model.OperationOutcome.IssueType code) {
748    switch (code) {
749    case BUSINESSRULE: return IssueType.BUSINESSRULE;
750    case CODEINVALID: return IssueType.CODEINVALID;
751    case CONFLICT: return IssueType.CONFLICT;
752    case DELETED: return IssueType.DELETED;
753    case DUPLICATE: return IssueType.DUPLICATE;
754    case EXCEPTION: return IssueType.EXCEPTION;
755    case EXPIRED: return IssueType.EXPIRED;
756    case EXTENSION: return IssueType.EXTENSION;
757    case FORBIDDEN: return IssueType.FORBIDDEN;
758    case INCOMPLETE: return IssueType.INCOMPLETE;
759    case INFORMATIONAL: return IssueType.INFORMATIONAL;
760    case INVALID: return IssueType.INVALID;
761    case INVARIANT: return IssueType.INVARIANT;
762    case LOCKERROR: return IssueType.LOCKERROR;
763    case LOGIN: return IssueType.LOGIN;
764    case MULTIPLEMATCHES: return IssueType.MULTIPLEMATCHES;
765    case NOSTORE: return IssueType.NOSTORE;
766    case NOTFOUND: return IssueType.NOTFOUND;
767    case NOTSUPPORTED: return IssueType.NOTSUPPORTED;
768    case NULL: return IssueType.NULL;
769    case PROCESSING: return IssueType.PROCESSING;
770    case REQUIRED: return IssueType.REQUIRED;
771    case SECURITY: return IssueType.SECURITY;
772    case STRUCTURE: return IssueType.STRUCTURE;
773    case SUPPRESSED: return IssueType.SUPPRESSED;
774    case THROTTLED: return IssueType.THROTTLED;
775    case TIMEOUT: return IssueType.TIMEOUT;
776    case TOOCOSTLY: return IssueType.TOOCOSTLY;
777    case TOOLONG: return IssueType.TOOLONG;
778    case TRANSIENT: return IssueType.TRANSIENT;
779    case UNKNOWN: return IssueType.UNKNOWN;
780    case VALUE: return IssueType.VALUE;
781    default: return null;
782    }
783  }
784
785  private static IssueSeverity mapSeverity(org.hl7.fhir.r4.model.OperationOutcome.IssueSeverity severity) {
786    switch (severity) {
787    case ERROR: return IssueSeverity.ERROR;
788    case FATAL: return IssueSeverity.FATAL;
789    case INFORMATION: return IssueSeverity.INFORMATION;
790    case WARNING: return IssueSeverity.WARNING;
791    default: return null;
792    }
793  }
794
795//  public static boolean hasOID(ValueSet vs) {
796//    return hasExtension(vs, EXT_OID);
797//  }
798//  
799//  public static boolean hasOID(CodeSystem cs) {
800//    return hasExtension(cs, EXT_OID);
801//  }
802//  
803  
804}