diff --git a/build.gradle.kts b/build.gradle.kts index b673a405..8d8d6180 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -7,7 +7,7 @@ plugins { } group = "org.hl7.fhir" -version = "1.9.2-SNAPSHOT" +version = "1.9.3-SNAPSHOT" java { withJavadocJar() diff --git a/gradle.properties b/gradle.properties index fdfd9210..e479133d 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,4 +1,4 @@ -fhirCoreVersion = 6.3.2 +fhirCoreVersion = 6.3.19 apachePoiVersion = 5.2.1 jacksonVersion = 2.16.0 apacheHttpcomponentsVersion = 4.5.13 diff --git a/src/main/java/org/hl7/fhir/definitions/generators/specification/DataTypeTableGenerator.java b/src/main/java/org/hl7/fhir/definitions/generators/specification/DataTypeTableGenerator.java index 5b711013..074e0352 100644 --- a/src/main/java/org/hl7/fhir/definitions/generators/specification/DataTypeTableGenerator.java +++ b/src/main/java/org/hl7/fhir/definitions/generators/specification/DataTypeTableGenerator.java @@ -5,6 +5,7 @@ import org.hl7.fhir.definitions.model.ElementDefn; import org.hl7.fhir.r5.model.Enumerations.FHIRVersion; import org.hl7.fhir.tools.publisher.PageProcessor; +import org.hl7.fhir.utilities.i18n.RenderingI18nContext; import org.hl7.fhir.utilities.xhtml.HierarchicalTableGenerator; import org.hl7.fhir.utilities.xhtml.HierarchicalTableGenerator.TableGenerationMode; import org.hl7.fhir.utilities.xhtml.HierarchicalTableGenerator.TableModel; @@ -16,7 +17,7 @@ public DataTypeTableGenerator(String dest, PageProcessor page, String pageName, } public XhtmlNode generate(ElementDefn e, Set outputTracker, boolean isActive) throws Exception { - HierarchicalTableGenerator gen = new HierarchicalTableGenerator(dest, inlineGraphics, false); + HierarchicalTableGenerator gen = new HierarchicalTableGenerator(new RenderingI18nContext(), dest, inlineGraphics, false); TableModel model = gen.initNormalTable("", false, true, e.getName(), isActive, isActive ? TableGenerationMode.XHTML : TableGenerationMode.XML); model.getRows().add(genElement(e, gen, false, e.getName(), false, "", RenderMode.DATATYPE, true, e.getStandardsStatus(), null, e.isAbstractType(), false)); diff --git a/src/main/java/org/hl7/fhir/definitions/generators/specification/ProfileGenerator.java b/src/main/java/org/hl7/fhir/definitions/generators/specification/ProfileGenerator.java index 6ccbc7a3..05860299 100644 --- a/src/main/java/org/hl7/fhir/definitions/generators/specification/ProfileGenerator.java +++ b/src/main/java/org/hl7/fhir/definitions/generators/specification/ProfileGenerator.java @@ -76,6 +76,7 @@ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWIS import org.hl7.fhir.exceptions.FHIRFormatError; import org.hl7.fhir.r5.conformance.profile.ProfileKnowledgeProvider; import org.hl7.fhir.r5.conformance.profile.ProfileUtilities; +import org.hl7.fhir.r5.context.ContextUtilities; import org.hl7.fhir.r5.formats.FormatUtilities; import org.hl7.fhir.r5.model.BooleanType; import org.hl7.fhir.r5.model.Bundle; @@ -138,6 +139,7 @@ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWIS import org.hl7.fhir.r5.model.UriType; import org.hl7.fhir.r5.renderers.OperationDefinitionRenderer; import org.hl7.fhir.r5.renderers.utils.RenderingContext; +import org.hl7.fhir.r5.renderers.utils.ResourceWrapper; import org.hl7.fhir.r5.utils.BuildExtensions; import org.hl7.fhir.r5.utils.CanonicalResourceUtilities; import org.hl7.fhir.r5.utils.ToolingExtensions; @@ -2601,7 +2603,7 @@ else if (op.getKind().toLowerCase().equals("query")) produceOpParam(op.getName(), opd.getParameter(), p, null); } OperationDefinitionRenderer opr = new OperationDefinitionRenderer(rc); - opr.render(opd); + opr.renderResource(ResourceWrapper.forResource(new ContextUtilities(context), opd)); return opd; } diff --git a/src/main/java/org/hl7/fhir/definitions/generators/specification/ResourceDependencyGenerator.java b/src/main/java/org/hl7/fhir/definitions/generators/specification/ResourceDependencyGenerator.java index 068a04c4..29f47ae5 100644 --- a/src/main/java/org/hl7/fhir/definitions/generators/specification/ResourceDependencyGenerator.java +++ b/src/main/java/org/hl7/fhir/definitions/generators/specification/ResourceDependencyGenerator.java @@ -18,6 +18,7 @@ import org.hl7.fhir.tools.publisher.PageProcessor; import org.hl7.fhir.utilities.StandardsStatus; import org.hl7.fhir.utilities.Utilities; +import org.hl7.fhir.utilities.i18n.RenderingI18nContext; import org.hl7.fhir.utilities.xhtml.HierarchicalTableGenerator; import org.hl7.fhir.utilities.xhtml.HierarchicalTableGenerator.Cell; import org.hl7.fhir.utilities.xhtml.HierarchicalTableGenerator.Row; @@ -49,7 +50,7 @@ public ResourceDependencyGenerator(String dest, PageProcessor page, String pageN } public XhtmlNode generate(ElementDefn e, String prefix) throws Exception { - HierarchicalTableGenerator gen = new HierarchicalTableGenerator(dest, inlineGraphics, true); + HierarchicalTableGenerator gen = new HierarchicalTableGenerator(new RenderingI18nContext(), dest, inlineGraphics, true); RenderMode mode = RenderMode.RESOURCE; TableModel model = initTable(gen, prefix, mode == RenderMode.LOGICAL, e.getName()); diff --git a/src/main/java/org/hl7/fhir/definitions/generators/specification/ResourceTableGenerator.java b/src/main/java/org/hl7/fhir/definitions/generators/specification/ResourceTableGenerator.java index 5fb2cfcd..fdd93133 100644 --- a/src/main/java/org/hl7/fhir/definitions/generators/specification/ResourceTableGenerator.java +++ b/src/main/java/org/hl7/fhir/definitions/generators/specification/ResourceTableGenerator.java @@ -4,6 +4,7 @@ import org.hl7.fhir.definitions.model.ResourceDefn; import org.hl7.fhir.r5.model.Enumerations.FHIRVersion; import org.hl7.fhir.tools.publisher.PageProcessor; +import org.hl7.fhir.utilities.i18n.RenderingI18nContext; import org.hl7.fhir.utilities.xhtml.HierarchicalTableGenerator; import org.hl7.fhir.utilities.xhtml.HierarchicalTableGenerator.TableGenerationMode; import org.hl7.fhir.utilities.xhtml.HierarchicalTableGenerator.TableModel; @@ -16,7 +17,7 @@ public ResourceTableGenerator(String dest, PageProcessor page, String pageName, } public XhtmlNode generate(ResourceDefn r, String prefix, boolean isActive) throws Exception { - HierarchicalTableGenerator gen = new HierarchicalTableGenerator(dest, inlineGraphics, true); + HierarchicalTableGenerator gen = new HierarchicalTableGenerator(new RenderingI18nContext(), dest, inlineGraphics, true); ElementDefn e = r.getRoot(); RenderMode mode = e.typeCode().equals("Logical") && hasLogicalMapping(e) ? RenderMode.LOGICAL : RenderMode.RESOURCE; TableModel model = gen.initNormalTable(prefix, mode == RenderMode.LOGICAL, true, r.getName(), isActive, isActive ? TableGenerationMode.XHTML : TableGenerationMode.XML); diff --git a/src/main/java/org/hl7/fhir/definitions/generators/specification/SDUsageMapper.java b/src/main/java/org/hl7/fhir/definitions/generators/specification/SDUsageMapper.java index 72adadc8..460e8a46 100644 --- a/src/main/java/org/hl7/fhir/definitions/generators/specification/SDUsageMapper.java +++ b/src/main/java/org/hl7/fhir/definitions/generators/specification/SDUsageMapper.java @@ -112,17 +112,19 @@ private void process(String name, String path, Element resource) { } private void walkChildren(String name, String path, Element element) { - for (Element ex : element.getChildren("extension")) { - see(name, path, ex.getNamedChildValue("url")); - } - for (Element ex : element.getChildren("modifierExtension")) { - see(name, path, ex.getNamedChildValue("url")); - } - for (Element c : element.getChildren()) { - if (c.isResource()) { - process(name, path, c); - } else if (!c.isPrimitive()) { - walkChildren(name, path, c); + if (element.hasChildren()) { + for (Element ex : element.getChildren("extension")) { + see(name, path, ex.getNamedChildValue("url")); + } + for (Element ex : element.getChildren("modifierExtension")) { + see(name, path, ex.getNamedChildValue("url")); + } + for (Element c : element.getChildren()) { + if (c.isResource()) { + process(name, path, c); + } else if (!c.isPrimitive()) { + walkChildren(name, path, c); + } } } } diff --git a/src/main/java/org/hl7/fhir/definitions/generators/specification/json/SchemaGenerator.java b/src/main/java/org/hl7/fhir/definitions/generators/specification/json/SchemaGenerator.java index 46e6a08a..349c0b9b 100644 --- a/src/main/java/org/hl7/fhir/definitions/generators/specification/json/SchemaGenerator.java +++ b/src/main/java/org/hl7/fhir/definitions/generators/specification/json/SchemaGenerator.java @@ -41,10 +41,10 @@ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWIS import org.hl7.fhir.definitions.model.TypeRef; import org.hl7.fhir.exceptions.FHIRException; import org.hl7.fhir.tools.publisher.BuildWorkerContext; -import org.hl7.fhir.utilities.CSFile; import org.hl7.fhir.utilities.IniFile; import org.hl7.fhir.utilities.TextFile; import org.hl7.fhir.utilities.Utilities; +import org.hl7.fhir.utilities.filesystem.CSFile; import com.google.gson.Gson; import com.google.gson.GsonBuilder; diff --git a/src/main/java/org/hl7/fhir/definitions/generators/xsd/SchemaGenerator.java b/src/main/java/org/hl7/fhir/definitions/generators/xsd/SchemaGenerator.java index 42d4debf..f91d7236 100644 --- a/src/main/java/org/hl7/fhir/definitions/generators/xsd/SchemaGenerator.java +++ b/src/main/java/org/hl7/fhir/definitions/generators/xsd/SchemaGenerator.java @@ -42,10 +42,10 @@ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWIS import org.hl7.fhir.definitions.model.Definitions; import org.hl7.fhir.definitions.model.ResourceDefn; import org.hl7.fhir.tools.publisher.BuildWorkerContext; -import org.hl7.fhir.utilities.CSFile; import org.hl7.fhir.utilities.IniFile; import org.hl7.fhir.utilities.TextFile; import org.hl7.fhir.utilities.Utilities; +import org.hl7.fhir.utilities.filesystem.CSFile; public class SchemaGenerator { diff --git a/src/main/java/org/hl7/fhir/definitions/model/Example.java b/src/main/java/org/hl7/fhir/definitions/model/Example.java index 8331d178..3bfd461e 100644 --- a/src/main/java/org/hl7/fhir/definitions/model/Example.java +++ b/src/main/java/org/hl7/fhir/definitions/model/Example.java @@ -30,7 +30,10 @@ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWIS */ import java.io.File; +import java.io.FileNotFoundException; import java.io.FileOutputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; @@ -39,14 +42,17 @@ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWIS import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; +import org.hl7.fhir.r5.context.IWorkerContext; import org.hl7.fhir.r5.elementmodel.Element; +import org.hl7.fhir.r5.elementmodel.Manager; +import org.hl7.fhir.r5.elementmodel.Manager.FhirFormat; import org.hl7.fhir.r5.model.Resource; import org.hl7.fhir.tools.publisher.PageProcessor; -import org.hl7.fhir.utilities.CSFile; -import org.hl7.fhir.utilities.CSFileInputStream; import org.hl7.fhir.utilities.CSVProcessor; import org.hl7.fhir.utilities.TextFile; import org.hl7.fhir.utilities.Utilities; +import org.hl7.fhir.utilities.filesystem.CSFile; +import org.hl7.fhir.utilities.filesystem.CSFileInputStream; import org.hl7.fhir.utilities.validation.ValidationMessage; import org.hl7.fhir.utilities.xml.XMLUtil; import org.w3c.dom.Document; @@ -62,7 +68,6 @@ public class Example { private String xhtm; private ExampleType type; private boolean registered; - private Document xml; private String resourceName; private Set inbounds = new HashSet(); private String ig; @@ -70,6 +75,9 @@ public class Example { private Element element; private List errors = new ArrayList<>(); private Resource resource; + private IWorkerContext context; + private File path; + private boolean noId; public enum ExampleType { @@ -80,35 +88,42 @@ public enum ExampleType { } - public Example(String name, String id, String title, String description, boolean registered, ExampleType type, Document doc) throws Exception { + public Example(String name, String id, String title, String description, boolean registered, ExampleType type, Element element) throws Exception { this.name = name; this.id = id; this.description = description; this.type = type; this.registered = registered; this.title = title; + this.element = element; - xml = doc; - resourceName = xml.getDocumentElement().getNodeName(); - if (XMLUtil.getNamedChild(xml.getDocumentElement(), "id") == null) + resourceName = element.fhirType(); + String xid = element.getIdBase(); + if (xid == null) throw new Exception("no id element (looking for '"+id+"' from example "+id); - String xid = XMLUtil.getNamedChild(xml.getDocumentElement(), "id").getAttribute("value"); if (!id.equals(xid)) { throw new Exception("misidentified resource example "+id+" expected '"+id+"' found '"+xid+"'"); } } - public Example(String name, String id, String description, File path, boolean registered, ExampleType type, boolean noId) throws Exception { + public Example(IWorkerContext context, String name, String id, String description, File path, boolean registered, ExampleType type, boolean noId) throws Exception { super(); this.name = name; this.id = id; this.description = description; - // this.path = path; + this.path = path; this.type = type; this.registered = registered; this.title = getFileTitle(path); + this.context = context; + this.noId = noId; + + } + + private void loadExample() + throws FileNotFoundException, IOException, UnsupportedEncodingException, Exception { if( type == ExampleType.CsvFile ) { CSVProcessor csv = new CSVProcessor(); csv.setSource(new CSFileInputStream(path)); @@ -120,23 +135,20 @@ public Example(String name, String id, String description, File path, boolean re } if (type == ExampleType.XmlFile || type == ExampleType.CsvFile || type == ExampleType.Container) { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setNamespaceAware(true); try { - DocumentBuilder builder = factory.newDocumentBuilder(); String xs = TextFile.fileToString(new CSFile(path.getAbsolutePath())); xs = xs.replace("[%test-server%]", PageProcessor.TEST_SERVER_URL); - xml = builder.parse(new ByteArrayInputStream(xs.getBytes(Charsets.UTF_8))); - resourceName = xml.getDocumentElement().getNodeName(); + element = Manager.parseSingle(context, new ByteArrayInputStream(xs.getBytes(Charsets.UTF_8)), FhirFormat.XML); + resourceName = element.fhirType(); } catch (Exception e) { throw new Exception("unable to read "+path.getAbsolutePath()+": "+e.getMessage(), e); } } - if (xml != null && !noId) { + if (element != null && !noId) { if (!Utilities.noString(id)) { - if (XMLUtil.getNamedChild(xml.getDocumentElement(), "id") == null) + String xid = element.getIdBase(); + if (xid == null) throw new Exception("no id element (looking for '"+id+"' from "+path.getName()); - String xid = XMLUtil.getNamedChild(xml.getDocumentElement(), "id").getAttribute("value"); if (!id.equals(xid)) { throw new Exception("misidentified resource "+path+" expected '"+id+"' found '"+xid+"'"); } @@ -191,9 +203,6 @@ public String getTitle() { return title; } - public Document getXml() { - return xml; - } public boolean isRegistered() { return registered; @@ -237,7 +246,11 @@ public String getExampleFor() { } - public Element getElement() { + public Element getElement() throws FileNotFoundException, UnsupportedEncodingException, IOException, Exception { + if (element == null) { + loadExample(); + } + return element; } @@ -247,40 +260,42 @@ public void setElement(Element element) { } - public boolean hasXml() { - return xml != null; - } - - public List getErrors() { return errors; } - public boolean hasContained() { - if (xml == null) { - return false; + public boolean hasContained() throws FileNotFoundException, UnsupportedEncodingException, IOException, Exception { + if (element == null) { + loadExample(); } - Node n = xml.getDocumentElement().getFirstChild(); - while (n != null && !"contained".equals(n.getNodeName())) { - n = n.getNextSibling(); + + if (element == null) { + return false; } - return n != null; + return element.hasChildren("contained"); } - public String getURL() { - return xml != null ? XMLUtil.getNamedChildValue(xml.getDocumentElement(), "url") : null; + public String getURL() throws FileNotFoundException, UnsupportedEncodingException, IOException, Exception { + if (element == null) { + loadExample(); + } + + if (element == null) { + return null; + } + return element.getNamedChildValue("url"); } public String getOID() { - if (xml == null) { + if (element == null) { return null; } - for (org.w3c.dom.Element id : XMLUtil.getNamedChildren(xml.getDocumentElement(), "identifier")) { - String system = XMLUtil.getNamedChildValue(id, "system"); - String value = XMLUtil.getNamedChildValue(id, "value"); + for (Element id : element.getChildren("identifier")) { + String system = id.getNamedChildValue("system"); + String value = id.getNamedChildValue("value"); if ("urn:ietf:rfc:3986".equals(system) && value != null && value.startsWith("urn:oid:")) { return value.substring(8); } @@ -304,4 +319,9 @@ public String present() { } + public String fhirType() { + return resourceName; + } + + } diff --git a/src/main/java/org/hl7/fhir/definitions/model/ResourceDefn.java b/src/main/java/org/hl7/fhir/definitions/model/ResourceDefn.java index 0a685ee7..03342206 100644 --- a/src/main/java/org/hl7/fhir/definitions/model/ResourceDefn.java +++ b/src/main/java/org/hl7/fhir/definitions/model/ResourceDefn.java @@ -1,4 +1,7 @@ package org.hl7.fhir.definitions.model; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.UnsupportedEncodingException; /* Copyright (c) 2011+, HL7, Inc All rights reserved. @@ -33,11 +36,11 @@ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWIS import java.util.Map; import org.hl7.fhir.exceptions.FHIRException; +import org.hl7.fhir.r5.elementmodel.Element; import org.hl7.fhir.r5.model.StructureDefinition; import org.hl7.fhir.utilities.StandardsStatus; import org.hl7.fhir.utilities.Utilities; import org.hl7.fhir.utilities.xml.XMLUtil; -import org.w3c.dom.Element; public class ResourceDefn { @@ -356,16 +359,15 @@ public void setProposedOrder(String proposedOrder) { this.proposedOrder = proposedOrder; } - public Example getExampleById(String id) { + public Example getExampleById(String id) throws FileNotFoundException, UnsupportedEncodingException, IOException, Exception { for (Example e : examples) { if (e.getId().equals(id)) return e; if ("Bundle".equals(e.getResourceName())) { - List children = new ArrayList(); - XMLUtil.getNamedChildren(e.getXml().getDocumentElement(), "entry", children); + List children = e.getElement().getChildren("entry"); for (Element c : children) { - Element res = XMLUtil.getFirstChild(XMLUtil.getNamedChild(c, "resource")); - if (id.equals(XMLUtil.getNamedChildValue(res, "id"))) + Element res = c.getNamedChild("resource"); + if (id.equals(res.getIdBase())) return e; } } diff --git a/src/main/java/org/hl7/fhir/definitions/parsers/IgParser.java b/src/main/java/org/hl7/fhir/definitions/parsers/IgParser.java index e70bf4ba..27dd773d 100644 --- a/src/main/java/org/hl7/fhir/definitions/parsers/IgParser.java +++ b/src/main/java/org/hl7/fhir/definitions/parsers/IgParser.java @@ -47,10 +47,10 @@ import org.hl7.fhir.r5.model.ValueSet; import org.hl7.fhir.r5.utils.ToolingExtensions; import org.hl7.fhir.tools.publisher.BuildWorkerContext; -import org.hl7.fhir.utilities.CSFile; -import org.hl7.fhir.utilities.CSFileInputStream; import org.hl7.fhir.utilities.Logger; import org.hl7.fhir.utilities.Logger.LogMessageType; +import org.hl7.fhir.utilities.filesystem.CSFile; +import org.hl7.fhir.utilities.filesystem.CSFileInputStream; import org.hl7.fhir.utilities.Utilities; import org.hl7.fhir.utilities.validation.ValidationMessage; @@ -167,7 +167,7 @@ public void load(String rootDir, ImplementationGuideDefn igd, List parts = divideContainedResources(ex.getId(), ex.getXml()); - for (String n : parts.keySet()) { - definitions.getResourceByName(parts.get(n).getDocumentElement().getNodeName()).getExamples().add(new Example("Part of "+ex.getName(), ex.getId()+"-"+n, ex.getTitle()+"-"+n, "Part of the example", false, ExampleType.XmlFile, parts.get(n))); - } + throw new Error("not done yet"); +// Map parts = divideContainedResources(ex.getId(), ex.getXml()); +// for (String n : parts.keySet()) { +// definitions.getResourceByName(parts.get(n).getDocumentElement().getNodeName()).getExamples().add(new Example(context, "Part of "+ex.getName(), ex.getId()+"-"+n, ex.getTitle()+"-"+n, "Part of the example", false, ExampleType.XmlFile, parts.get(n))); +// } } private Map divideContainedResources(String rootId, Document doc) throws Exception { @@ -1101,7 +1102,7 @@ private void loadGlobalBindings() throws Exception { logger.log("Load Common Bindings", LogMessageType.Process); BindingsParser parser = new BindingsParser(new CSFileInputStream(new CSFile(termDir + "bindings.xml")), termDir + "bindings.xml", srcDir, registry, version.toCode(), - definitions.getCodeSystems(), page.getConceptMaps(), genDate, exceptionIfExcelNotNormalised, page.packageInfo(), page.getDefinitions(), context.translator()); + definitions.getCodeSystems(), page.getConceptMaps(), genDate, exceptionIfExcelNotNormalised, page.packageInfo(), page.getDefinitions()); List cds = parser.parse(); for (BindingSpecification cd : cds) { @@ -1179,7 +1180,7 @@ private void genTypeProfile(org.hl7.fhir.definitions.model.TypeDefn t) throws Ex t.setProfile(profile); DataTypeTableGenerator dtg = new DataTypeTableGenerator(dstDir, page, t.getName(), true, version, ""); t.getProfile().getText().setDiv(new XhtmlNode(NodeType.Element, "div")); - t.getProfile().getText().getDiv().getChildNodes().add(dtg.generate(t, null, false)); + t.getProfile().getText().getDiv().addChildNode(dtg.generate(t, null, false)); context.dropResource(t.getProfile()); context.cacheResource(t.getProfile()); } catch (Exception e) { diff --git a/src/main/java/org/hl7/fhir/definitions/parsers/ValueSetGenerator.java b/src/main/java/org/hl7/fhir/definitions/parsers/ValueSetGenerator.java index 2d0dae85..c51880d7 100644 --- a/src/main/java/org/hl7/fhir/definitions/parsers/ValueSetGenerator.java +++ b/src/main/java/org/hl7/fhir/definitions/parsers/ValueSetGenerator.java @@ -46,17 +46,15 @@ public class ValueSetGenerator { private Definitions definitions; private String version; private Calendar genDate; - private TranslationServices translator; private PackageInformation packageInfo; private IWorkerContext context; - public ValueSetGenerator(Definitions definitions, String version, Calendar genDate, TranslationServices translator, PackageInformation packageInfo, IWorkerContext context) throws ParserConfigurationException, SAXException, IOException { + public ValueSetGenerator(Definitions definitions, String version, Calendar genDate, PackageInformation packageInfo, IWorkerContext context) throws ParserConfigurationException, SAXException, IOException { super(); this.definitions = definitions; this.version = version; this.genDate = genDate; - this.translator = translator; this.packageInfo = packageInfo; this.context = context; } @@ -223,15 +221,9 @@ private void genResourceTypes(ValueSet vs) { private ConceptDefinitionComponent makeConceptForResource(String code, String definition, boolean isAbstract) { ConceptDefinitionComponent c = new ConceptDefinitionComponent(); - Map t = translator.translations(code); c.setCode(code); c.setDisplay(code); c.setDefinition((isAbstract ? "--- Abstract Type! ---" : "")+ definition); - if (t != null) { - for (String l : t.keySet()) { - c.addDesignation().setLanguage(l).setValue(t.get(l)).getUse().setSystem("http://terminology.hl7.org/CodeSystem/designation-usage").setCode("display"); - } - } return c; } @@ -444,22 +436,6 @@ public void loadOperationOutcomeValueSet(BindingSpecification cd) throws Excepti CodeSystem cs = new CodeSystem(); cs.setHierarchyMeaning(CodeSystemHierarchyMeaning.ISA); - Set codes = translator.listTranslations("ecode"); - for (String s : sorted(codes)) { - Map langs = translator.translations(s); - ConceptDefinitionComponent cv = cs.addConcept(); - cv.setCode(s); - cv.setDisplay(langs.get("en")); - for (String lang : langs.keySet()) { - if (!lang.equals("en")) { - String value = langs.get(lang); - ConceptDefinitionDesignationComponent dc = cv.addDesignation(); - dc.setLanguage(lang); - dc.setValue(value); - dc.getUse().setSystem("http://terminology.hl7.org/CodeSystem/designation-usage").setCode("display"); - } - } - } KindlingUtilities.makeUniversal(cs); CodeSystemConvertor.populate(cs, vs); diff --git a/src/main/java/org/hl7/fhir/definitions/parsers/spreadsheets/BindingsParser.java b/src/main/java/org/hl7/fhir/definitions/parsers/spreadsheets/BindingsParser.java index c4f94fc2..9b16bbdc 100644 --- a/src/main/java/org/hl7/fhir/definitions/parsers/spreadsheets/BindingsParser.java +++ b/src/main/java/org/hl7/fhir/definitions/parsers/spreadsheets/BindingsParser.java @@ -89,9 +89,8 @@ public class BindingsParser { private boolean exceptionIfExcelNotNormalised; private PackageInformation packageInfo; private Definitions definitions; - private TranslationServices translator; - public BindingsParser(InputStream file, String filename, String root, OIDRegistry registry, String version, CanonicalResourceManager codeSystems, CanonicalResourceManager maps, Calendar genDate, boolean exceptionIfExcelNotNormalised, PackageInformation packageInfo, Definitions definitions, TranslationServices translator) { + public BindingsParser(InputStream file, String filename, String root, OIDRegistry registry, String version, CanonicalResourceManager codeSystems, CanonicalResourceManager maps, Calendar genDate, boolean exceptionIfExcelNotNormalised, PackageInformation packageInfo, Definitions definitions) { this.file = file; this.filename = filename; this.root = root; @@ -103,7 +102,6 @@ public BindingsParser(InputStream file, String filename, String root, OIDRegistr this.exceptionIfExcelNotNormalised = exceptionIfExcelNotNormalised; this.packageInfo = packageInfo; this.definitions = definitions; - this.translator = translator; } public List parse() throws Exception { @@ -270,22 +268,6 @@ private void loadOperationOutcomeValueSet(BindingSpecification cd) { CodeSystem cs = new CodeSystem(); cs.setHierarchyMeaning(CodeSystemHierarchyMeaning.ISA); - Set codes = translator.listTranslations("ecode"); - for (String s : Utilities.sorted(codes)) { - Map langs = translator.translations(s); - ConceptDefinitionComponent cv = cs.addConcept(); - cv.setCode(s); - cv.setDisplay(langs.get("en")); - for (String lang : langs.keySet()) { - if (!lang.equals("en")) { - String value = langs.get(lang); - ConceptDefinitionDesignationComponent dc = cv.addDesignation(); - dc.setLanguage(lang); - dc.setValue(value); - dc.getUse().setSystem("http://terminology.hl7.org/CodeSystem/designation-usage").setCode("display"); - } - } - } KindlingUtilities.makeUniversal(cs); CodeSystemConvertor.populate(cs, vs); cs.setUrl("http://hl7.org/fhir/operation-outcome"); diff --git a/src/main/java/org/hl7/fhir/definitions/parsers/spreadsheets/OldSpreadsheetParser.java b/src/main/java/org/hl7/fhir/definitions/parsers/spreadsheets/OldSpreadsheetParser.java index 1b5a979d..e48b3372 100644 --- a/src/main/java/org/hl7/fhir/definitions/parsers/spreadsheets/OldSpreadsheetParser.java +++ b/src/main/java/org/hl7/fhir/definitions/parsers/spreadsheets/OldSpreadsheetParser.java @@ -139,13 +139,13 @@ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWIS import org.hl7.fhir.tools.converters.MarkDownPreProcessor; import org.hl7.fhir.tools.publisher.BuildWorkerContext; import org.hl7.fhir.tools.publisher.KindlingUtilities; -import org.hl7.fhir.utilities.CSFile; -import org.hl7.fhir.utilities.CSFileInputStream; import org.hl7.fhir.utilities.IniFile; import org.hl7.fhir.utilities.Logger; import org.hl7.fhir.utilities.StandardsStatus; import org.hl7.fhir.utilities.TextFile; import org.hl7.fhir.utilities.Utilities; +import org.hl7.fhir.utilities.filesystem.CSFile; +import org.hl7.fhir.utilities.filesystem.CSFileInputStream; import org.hl7.fhir.utilities.validation.ValidationMessage; import org.hl7.fhir.utilities.xls.XLSXmlNormaliser; import org.hl7.fhir.utilities.xls.XLSXmlParser; @@ -741,7 +741,7 @@ else if ("structuredefinition".equalsIgnoreCase(type)) throw new Exception("Unknown source type: "+type+" at "+getLocation(row)); String example = checkFile(sheet, row, "Example", true, null); // todo-profile if (example != null) - pack.getExamples().add(new Example(example, Utilities.fileTitle(example), "General Example for "+pack.getSource(), new File(example), true, ExampleType.XmlFile, isAbstract)); + pack.getExamples().add(new Example(context, example, Utilities.fileTitle(example), "General Example for "+pack.getSource(), new File(example), true, ExampleType.XmlFile, isAbstract)); defn.getConformancePackages().add(pack); } } @@ -1135,7 +1135,7 @@ private void readBindings(Sheet sheet) throws Exception { String bindingName = sheet.getColumn(row, "Binding Name"); } - ValueSetGenerator vsGen = new ValueSetGenerator(definitions, version.toCode(), genDate, context.translator(), packageInfo, context); + ValueSetGenerator vsGen = new ValueSetGenerator(definitions, version.toCode(), genDate, packageInfo, context); for (int row = 0; row < sheet.rows.size(); row++) { String bindingName = sheet.getColumn(row, "Binding Name"); @@ -1208,7 +1208,7 @@ private void readBindings(Sheet sheet) throws Exception { cd.setValueSet(loadValueSet(ref)); } else if (cd.getBinding() == BindingMethod.Special) { if ("#operation-outcome".equals(sheet.getColumn(row, "Reference"))) - new ValueSetGenerator(definitions, version.toCode(), genDate, context.translator(), packageInfo, context).loadOperationOutcomeValueSet(cd); + new ValueSetGenerator(definitions, version.toCode(), genDate, packageInfo, context).loadOperationOutcomeValueSet(cd); else throw new Exception("Special bindings are only allowed in bindings.xml"); } @@ -1645,7 +1645,7 @@ private void readExamples(ResourceDefn defn, Sheet sheet) throws Exception { } ExampleType etype = parseExampleType(type, row); - list.add(new Example(name, id, desc, file, parseBoolean(sheet.getColumn(row, "Registered"), row, true), etype, isAbstract)); + list.add(new Example(context, name, id, desc, file, parseBoolean(sheet.getColumn(row, "Registered"), row, true), etype, isAbstract)); } } } @@ -1655,7 +1655,7 @@ private void readExamples(ResourceDefn defn, Sheet sheet) throws Exception { throw new Exception("Example (file '" + file.getAbsolutePath() + "') not found parsing " + this.name); if (file.exists()) defn.getExamples().add( - new Example("General", "example", "Example of " + title, file, true, ExampleType.XmlFile, isAbstract)); + new Example(context, "General", "example", "Example of " + title, file, true, ExampleType.XmlFile, isAbstract)); } } diff --git a/src/main/java/org/hl7/fhir/definitions/parsers/spreadsheets/SpreadSheetBase.java b/src/main/java/org/hl7/fhir/definitions/parsers/spreadsheets/SpreadSheetBase.java index f12c84cb..d2d0024c 100644 --- a/src/main/java/org/hl7/fhir/definitions/parsers/spreadsheets/SpreadSheetBase.java +++ b/src/main/java/org/hl7/fhir/definitions/parsers/spreadsheets/SpreadSheetBase.java @@ -17,9 +17,9 @@ import org.hl7.fhir.r5.model.Element; import org.hl7.fhir.r5.model.Extension; import org.hl7.fhir.r5.model.Resource; -import org.hl7.fhir.utilities.CSFile; -import org.hl7.fhir.utilities.CSFileInputStream; import org.hl7.fhir.utilities.Utilities; +import org.hl7.fhir.utilities.filesystem.CSFile; +import org.hl7.fhir.utilities.filesystem.CSFileInputStream; public class SpreadSheetBase { diff --git a/src/main/java/org/hl7/fhir/definitions/parsers/spreadsheets/SpreadSheetCreator.java b/src/main/java/org/hl7/fhir/definitions/parsers/spreadsheets/SpreadSheetCreator.java index 580bb453..01cec5a0 100644 --- a/src/main/java/org/hl7/fhir/definitions/parsers/spreadsheets/SpreadSheetCreator.java +++ b/src/main/java/org/hl7/fhir/definitions/parsers/spreadsheets/SpreadSheetCreator.java @@ -196,13 +196,13 @@ private void addInvariantColumns(XSSFSheet sheet, StructureDefinition sd) { private void addElements(XSSFSheet resources, XSSFSheet bindings, XSSFSheet invariants, ElementDefinition ed, int rowCount) throws IOException { Row row = resources.createRow(rowCount); int columnCount = 0; - ed.removeExtension(ToolingExtensions.EXT_ED_HEIRARCHY); + ed.removeExtension(ToolingExtensions.EXT_ED_HIERARCHY); addCell(ed.getPath(), row, columnCount++); // Path addCell(aliases(ed), row, columnCount++); // Aliases addCell(ed.getMin()+".."+ed.getMax(), row, columnCount++); // Card. addCell(inv(ed), row, columnCount++); // Inv. addCell(type(ed), row, columnCount++); // Type - addCell(typeHeirarchy(ed, BuildExtensions.EXT_HIERARCHY), row, columnCount++); + addCell(typeHierarchy(ed, BuildExtensions.EXT_HIERARCHY), row, columnCount++); addCell(bool(ed.getIsModifierElement()), row, columnCount++); // Is Modifier addCell(ed.getIsModifierReason(), row, columnCount++); // Modifier Reason addCell(bool(ed.getIsSummaryElement()), row, columnCount++); // Summary @@ -232,7 +232,7 @@ private void addElements(XSSFSheet resources, XSSFSheet bindings, XSSFSheet inva } } - private String typeHeirarchy(ElementDefinition ed, String extHeirarchy) { + private String typeHierarchy(ElementDefinition ed, String extHierarchy) { for (TypeRefComponent tr : ed.getType()) { if (BuildExtensions.readBoolExtension(tr, BuildExtensions.EXT_HIERARCHY)) { return "true"; diff --git a/src/main/java/org/hl7/fhir/definitions/validation/JsonSchemaValidationTests.java b/src/main/java/org/hl7/fhir/definitions/validation/JsonSchemaValidationTests.java index 95091537..a20335b0 100644 --- a/src/main/java/org/hl7/fhir/definitions/validation/JsonSchemaValidationTests.java +++ b/src/main/java/org/hl7/fhir/definitions/validation/JsonSchemaValidationTests.java @@ -5,9 +5,9 @@ import org.everit.json.schema.ValidationException; import org.everit.json.schema.loader.SchemaLoader; -import org.hl7.fhir.utilities.CSFileInputStream; import org.hl7.fhir.utilities.TextFile; import org.hl7.fhir.utilities.Utilities; +import org.hl7.fhir.utilities.filesystem.CSFileInputStream; import org.json.JSONObject; import org.json.JSONTokener; import org.junit.Test; diff --git a/src/main/java/org/hl7/fhir/definitions/validation/XmlValidator.java b/src/main/java/org/hl7/fhir/definitions/validation/XmlValidator.java index 42f0b67f..85fbeb1b 100644 --- a/src/main/java/org/hl7/fhir/definitions/validation/XmlValidator.java +++ b/src/main/java/org/hl7/fhir/definitions/validation/XmlValidator.java @@ -39,10 +39,10 @@ import org.hl7.fhir.exceptions.FHIRException; -import org.hl7.fhir.utilities.CSFile; -import org.hl7.fhir.utilities.CSFileInputStream; import org.hl7.fhir.utilities.Logger; import org.hl7.fhir.utilities.Logger.LogMessageType; +import org.hl7.fhir.utilities.filesystem.CSFile; +import org.hl7.fhir.utilities.filesystem.CSFileInputStream; import org.hl7.fhir.utilities.SchemaInputSource; import org.hl7.fhir.utilities.TextFile; import org.hl7.fhir.utilities.Utilities; diff --git a/src/main/java/org/hl7/fhir/tools/converters/CKMImporter.java b/src/main/java/org/hl7/fhir/tools/converters/CKMImporter.java index ac44b275..681a5c1e 100644 --- a/src/main/java/org/hl7/fhir/tools/converters/CKMImporter.java +++ b/src/main/java/org/hl7/fhir/tools/converters/CKMImporter.java @@ -8,11 +8,10 @@ import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; - -import org.hl7.fhir.utilities.SimpleHTTPClient; -import org.hl7.fhir.utilities.SimpleHTTPClient.HTTPResult; import org.hl7.fhir.utilities.TextFile; import org.hl7.fhir.utilities.Utilities; +import org.hl7.fhir.utilities.http.HTTPResult; +import org.hl7.fhir.utilities.http.ManagedWebAccess; import org.hl7.fhir.utilities.xml.XMLUtil; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -106,8 +105,7 @@ private void processArchetype(String id) throws Exception { } private Document loadXml(String address) throws Exception { - SimpleHTTPClient http = new SimpleHTTPClient(); - HTTPResult res = http.get(address, "application/xml"); + HTTPResult res = ManagedWebAccess.get("application/xml"); res.checkThrowException(); InputStream xml = new ByteArrayInputStream(res.getContent()); diff --git a/src/main/java/org/hl7/fhir/tools/publisher/BreadCrumbManager.java b/src/main/java/org/hl7/fhir/tools/publisher/BreadCrumbManager.java index 7a97ffb0..fb72a520 100644 --- a/src/main/java/org/hl7/fhir/tools/publisher/BreadCrumbManager.java +++ b/src/main/java/org/hl7/fhir/tools/publisher/BreadCrumbManager.java @@ -15,9 +15,9 @@ import org.hl7.fhir.r5.model.StructureDefinition; import org.hl7.fhir.r5.model.StructureDefinition.ExtensionContextType; import org.hl7.fhir.r5.utils.Translations; -import org.hl7.fhir.utilities.CSFile; -import org.hl7.fhir.utilities.CSFileInputStream; import org.hl7.fhir.utilities.Utilities; +import org.hl7.fhir.utilities.filesystem.CSFile; +import org.hl7.fhir.utilities.filesystem.CSFileInputStream; import org.hl7.fhir.utilities.xhtml.XhtmlNode; import org.hl7.fhir.utilities.xml.XMLUtil; import org.w3c.dom.Document; diff --git a/src/main/java/org/hl7/fhir/tools/publisher/BuildWorkerContext.java b/src/main/java/org/hl7/fhir/tools/publisher/BuildWorkerContext.java index d8c9f928..d601e2d7 100644 --- a/src/main/java/org/hl7/fhir/tools/publisher/BuildWorkerContext.java +++ b/src/main/java/org/hl7/fhir/tools/publisher/BuildWorkerContext.java @@ -65,13 +65,13 @@ import org.hl7.fhir.r5.terminologies.utilities.ValidationResult; import org.hl7.fhir.r5.utils.client.EFhirClientException; import org.hl7.fhir.r5.utils.validation.IResourceValidator; -import org.hl7.fhir.utilities.CSFileInputStream; import org.hl7.fhir.utilities.CommaSeparatedStringBuilder; import org.hl7.fhir.utilities.TextFile; import org.hl7.fhir.utilities.TranslatorXml; import org.hl7.fhir.utilities.Utilities; import org.hl7.fhir.utilities.VersionUtil; import org.hl7.fhir.utilities.VersionUtilities; +import org.hl7.fhir.utilities.filesystem.CSFileInputStream; import org.hl7.fhir.utilities.i18n.I18nConstants; import org.hl7.fhir.utilities.npm.BasePackageCacheManager; import org.hl7.fhir.utilities.npm.NpmPackage; @@ -131,11 +131,10 @@ public BuildWorkerContext(Definitions definitions, String terminologyCachePath, super(codeSystems, valueSets, maps, profiles, guides); initTxCache(terminologyCachePath); this.definitions = definitions; - this.terminologyClientManager.setMasterClient(client); + this.terminologyClientManager.setMasterClient(client, true); this.terminologyClientManager.setUsage("publication"); this.txLog = new HTMLClientLogger(null); setExpansionParameters(buildExpansionProfile()); - this.setTranslator(new TranslatorXml(Utilities.path(folder, "implementations", "translations.xml"))); setWarnAboutMissingMessages(false); } @@ -273,10 +272,16 @@ private ConceptDefinitionComponent locateSnomed(String code) throws Exception { return cc; } + private void queryForTerm(String code) { + ValidationResult vr = super.validateCode(new ValidationOptions(), "http://snomed.info/sct", null, code, null); + if (vr.isOk()) { + snomedCodes.put(code, new Concept(vr.getDisplay())); + } + } + private ValidationResult verifySnomed(String code, String display) throws Exception { - SnomedServerResponse response = null; if (!snomedCodes.containsKey(code)) - response = queryForTerm(code); + queryForTerm(code); if (snomedCodes.containsKey(code)) if (display == null) return new ValidationResult("http://snomed.info/sct", null, new ConceptDefinitionComponent().setCode(code).setDisplay(snomedCodes.get(code).display), null); @@ -285,9 +290,7 @@ else if (snomedCodes.get(code).has(display)) else return new ValidationResult(IssueSeverity.WARNING, "Snomed Display Name for "+code+" must be one of '"+snomedCodes.get(code).summary()+"'", null); - if (response != null) // this is a wrong expression - return new ValidationResult(IssueSeverity.ERROR, "The Snomed Expression "+code+" must use the form "+response.correctExpression, null); - else if (serverOk) + if (serverOk) return new ValidationResult(IssueSeverity.ERROR, "Unknown Snomed Code "+code, null); else return new ValidationResult(IssueSeverity.WARNING, "Unknown Snomed Code "+code, null); @@ -298,57 +301,6 @@ private static class SnomedServerResponse { String display; } - private SnomedServerResponse queryForTerm(String code) throws Exception { - if (!triedServer || serverOk) { - triedServer = true; - HttpClient httpclient = new DefaultHttpClient(); - HttpGet httpget = new HttpGet(FhirSettings.getTxFhirProduction()+"/snomed/tool/"+SNOMED_EDITION+"/"+URLEncoder.encode(code, "UTF-8").replace("+", "%20")); -// HttpGet httpget = new HttpGet("http://local.fhir.org:960/r4/snomed/tool/"+SNOMED_EDITION+"/"+URLEncoder.encode(code, "UTF-8").replace("+", "%20")); // don't like the url encoded this way - HttpResponse response = httpclient.execute(httpget); - HttpEntity entity = response.getEntity(); - InputStream instream = entity.getContent(); - try { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); - Document xdoc = builder.parse(instream); - // we always get back a version, and a type. What we do depends on the type - String t = xdoc.getDocumentElement().getAttribute("type"); - serverOk = true; - if (t.equals("error")) - throw new Exception(xdoc.getDocumentElement().getAttribute("message")); - if (t.equals("description")) - throw new Exception("The Snomed code (\""+code+"\") is a description id not a concept id which is not valid"); - if (t.equals("concept")) { - Concept c = new Concept(); - c.display = xdoc.getDocumentElement().getAttribute("display"); - Element child = XMLUtil.getFirstChild(xdoc.getDocumentElement()); - while (child != null) { - c.displays.add(child.getAttribute("value")); - child = XMLUtil.getNextSibling(child); - } - snomedCodes.put(code, c); - return null; - } - if (t.equals("expression")) { - SnomedServerResponse resp = new SnomedServerResponse(); - resp.correctExpression = xdoc.getDocumentElement().getAttribute("expressionMinimal"); - resp.display = xdoc.getDocumentElement().getAttribute("display"); - if (!snomedCodes.containsKey(resp.correctExpression)) { - Concept c = new Concept(); - c.display = resp.display; - snomedCodes.put(resp.correctExpression, c); - } - return resp; - } - throw new Exception("Unrecognised response from server"); - } finally { - instream.close(); - } - } else - return null; - } - private ConceptDefinitionComponent locateLoinc(String code) throws Exception { if (!loincCodes.containsKey(code)) return null; @@ -561,7 +513,7 @@ private String lookupLoinc(String code) throws Exception { triedServer = true; // for this, we use the FHIR client if (terminologyClientManager.getMasterClient() == null) { - terminologyClientManager.setMasterClient(new TerminologyClientR5("tx-dev.fhir.org", "?", "fhir/main-build")); + terminologyClientManager.setMasterClient(new TerminologyClientR5("tx-dev.fhir.org", "?", "fhir/main-build"), true); this.txLog = new HTMLClientLogger(null); } Map params = new HashMap(); @@ -862,4 +814,9 @@ public String getSpecUrl() { public T fetchResourceRaw(Class class_, String uri) { throw new NotImplementedException(); } + + @Override + public String getCanonicalForDefaultContext() { + return "http://hl7.org/fhir"; + } } diff --git a/src/main/java/org/hl7/fhir/tools/publisher/ExampleAdorner.java b/src/main/java/org/hl7/fhir/tools/publisher/ExampleAdorner.java index f97555e8..4a767c72 100644 --- a/src/main/java/org/hl7/fhir/tools/publisher/ExampleAdorner.java +++ b/src/main/java/org/hl7/fhir/tools/publisher/ExampleAdorner.java @@ -193,22 +193,13 @@ else if (!e.isBaseResourceElement() && e.typeCode().equals("uri")) if (r == null) throw new Exception("unable to find type "+type); for (Example e : r.getExamples()) { - if (id.equals(e.getId())) + if (id.equals(e.getId())) { if (Utilities.noString(e.getIg())) { return new ExampleAdornerState(State.Reference, s.getPath()+".reference", s.getDefinition(), "", ""); } else { ImplementationGuideDefn ig = definitions.getIgs().get(e.getIg()); return new ExampleAdornerState(State.Reference, s.getPath()+".reference", s.getDefinition(), "", ""); } - if (e.getXml() != null && e.getXml().getDocumentElement().getLocalName().equals("feed")) { - List entries = new ArrayList(); - XMLUtil.getNamedChildren(e.getXml().getDocumentElement(), "entry", entries); - String url = "http://hl7.org/fhir/"+type+"/"+id; - for (Element c : entries) { - String t = XMLUtil.getNamedChild(c, "id").getAttribute("value"); - if (url.equals(t)) - return new ExampleAdornerState(State.Reference, s.getPath()+".reference", s.getDefinition(), "", ""); - } } } return new ExampleAdornerState(State.Reference, s.getPath()+".reference", s.getDefinition(), "", ""); diff --git a/src/main/java/org/hl7/fhir/tools/publisher/ExampleInspector.java b/src/main/java/org/hl7/fhir/tools/publisher/ExampleInspector.java index 631b2221..5135df98 100644 --- a/src/main/java/org/hl7/fhir/tools/publisher/ExampleInspector.java +++ b/src/main/java/org/hl7/fhir/tools/publisher/ExampleInspector.java @@ -52,6 +52,7 @@ import org.hl7.fhir.r5.model.SearchParameter; import org.hl7.fhir.r5.model.StructureDefinition; import org.hl7.fhir.r5.model.ValueSet; +import org.hl7.fhir.r5.utils.validation.IMessagingServices; import org.hl7.fhir.r5.utils.validation.IResourceValidator; import org.hl7.fhir.r5.utils.validation.IValidationPolicyAdvisor; import org.hl7.fhir.r5.utils.validation.IValidatorResourceFetcher; @@ -67,12 +68,11 @@ import org.hl7.fhir.r5.utils.validation.constants.ReferenceValidationPolicy; import org.hl7.fhir.rdf.ModelComparer; import org.hl7.fhir.rdf.ShExValidator; -import org.hl7.fhir.utilities.CSFileInputStream; import org.hl7.fhir.utilities.Logger; import org.hl7.fhir.utilities.Logger.LogMessageType; import org.hl7.fhir.utilities.SIDUtilities; -import org.hl7.fhir.utilities.SimpleHTTPClient; -import org.hl7.fhir.utilities.SimpleHTTPClient.HTTPResult; +import org.hl7.fhir.utilities.filesystem.CSFileInputStream; +import org.hl7.fhir.utilities.http.ManagedWebAccess; import org.hl7.fhir.utilities.TextFile; import org.hl7.fhir.utilities.Utilities; import org.hl7.fhir.utilities.ZipGenerator; @@ -80,6 +80,7 @@ import org.hl7.fhir.utilities.validation.ValidationMessage.IssueSeverity; import org.hl7.fhir.utilities.validation.ValidationMessage.IssueType; import org.hl7.fhir.utilities.validation.ValidationMessage.Source; +import org.hl7.fhir.validation.instance.BasePolicyAdvisorForFullValidation; import org.hl7.fhir.validation.instance.InstanceValidator; import org.json.JSONObject; import org.json.JSONTokener; @@ -228,6 +229,7 @@ public void prepare() throws Exception { validator.setAllowExamples(true); validator.setDebug(false); validator.setForPublication(true); + validator.setPolicyAdvisor(new BasePolicyAdvisorForFullValidation(ReferenceValidationPolicy.CHECK_TYPE_IF_EXISTS)); fpe = new FHIRPathEngine(context); fpe.setHostServices(this); @@ -569,38 +571,31 @@ public void setByRdf(boolean byRdf) { @Override public Element fetch(IResourceValidator validator,Object appContext, String url) throws IOException, FHIRException { + if (url.contains("/_history/")) { + url = url.substring(0, url.indexOf("/_history")); + } String[] parts = url.split("\\/"); if (parts.length == 2 && definitions.hasResource(parts[0])) { ResourceDefn r = definitions.getResourceByName(parts[0]); - for (Example e : r.getExamples()) { - if (e.getElement() == null && e.hasXml()) { - e.setElement(new org.hl7.fhir.r5.elementmodel.XmlParser(context).parse(new ArrayList<>(), e.getXml())); - if (e.getElement() != null && - e.getElement().getProperty().getStructure() != null && - e.getElement().getProperty().getStructure().getBaseDefinition() != null && - e.getElement().getProperty().getStructure().getBaseDefinition().contains("MetadataResource")) { - String urle = e.getElement().getChildValue("url"); - String v = e.getElement().getChildValue("url"); - if (urle != null && urle.startsWith("http://hl7.org/fhir") && !version.toCode().equals(v)) { - e.getElement().setChildValue("version", version.toCode()); - - } - } - } - if (e.getElement() != null) { - if (e.getElement().fhirType().equals("Bundle")) { - for (Base b : e.getElement().listChildrenByName("entry")) { - if (b.getChildByName("resource").hasValues()) { - Element res = (Element) b.getChildByName("resource").getValues().get(0); - if (res.fhirType().equals(parts[0]) && parts[1].equals(res.getChildValue("id"))) { - return res; + try { + for (Example e : r.getExamples()) { + if (e.getElement() != null) { + if (e.getElement().fhirType().equals("Bundle")) { + for (Base b : e.getElement().listChildrenByName("entry")) { + if (b.getChildByName("resource").hasValues()) { + Element res = (Element) b.getChildByName("resource").getValues().get(0); + if (res.fhirType().equals(parts[0]) && parts[1].equals(res.getChildValue("id"))) { + return res; + } } } + } else if (e.getElement().fhirType().equals(parts[0]) && e.getId().equals(parts[1])) { + return e.getElement(); } - } else if (e.getElement().fhirType().equals(parts[0]) && e.getId().equals(parts[1])) { - return e.getElement(); } } + } catch (Exception e) { + throw new FHIRException(e); } try { if (parts[0].equals("StructureDefinition")) @@ -661,8 +656,7 @@ public IValidatorResourceFetcher setLocale(Locale locale) { @Override public byte[] fetchRaw(IResourceValidator validator, String source) throws MalformedURLException, IOException { - SimpleHTTPClient http = new SimpleHTTPClient(); - HTTPResult res = http.get(source); + org.hl7.fhir.utilities.http.HTTPResult res = ManagedWebAccess.get(source); res.checkThrowException(); return res.getContent(); } @@ -837,7 +831,11 @@ public Base resolveReference(FHIRPathEngine engine, Object appContext, String ur if (ex.getResource() != null) { return ex.getResource(); } else { - return ex.getElement(); // new XmlParser().parse(ex.getXml()); + try { + return ex.getElement(); // new XmlParser().parse(ex.getXml()); + } catch (Exception e) { + throw new FHIRException(e); + } } } } @@ -868,6 +866,14 @@ public Set fetchCanonicalResourceVersions(IResourceValidator validator, return new HashSet<>(); } + @Override + public List getImpliedProfilesForResource(IResourceValidator validator, Object appContext, + String stackPath, ElementDefinition definition, StructureDefinition structure, Element resource, boolean valid, + IMessagingServices msgServices, List messages) { + return new BasePolicyAdvisorForFullValidation(ReferenceValidationPolicy.CHECK_TYPE_IF_EXISTS).getImpliedProfilesForResource(validator, appContext, stackPath, + definition, structure, resource, valid, msgServices, messages); + } + } diff --git a/src/main/java/org/hl7/fhir/tools/publisher/LogicalModelProcessor.java b/src/main/java/org/hl7/fhir/tools/publisher/LogicalModelProcessor.java index 220d7d99..c36fdee1 100644 --- a/src/main/java/org/hl7/fhir/tools/publisher/LogicalModelProcessor.java +++ b/src/main/java/org/hl7/fhir/tools/publisher/LogicalModelProcessor.java @@ -13,11 +13,14 @@ import org.hl7.fhir.r5.conformance.profile.BindingResolution; import org.hl7.fhir.r5.conformance.profile.ProfileKnowledgeProvider; import org.hl7.fhir.r5.conformance.profile.ProfileUtilities; +import org.hl7.fhir.r5.context.ContextUtilities; import org.hl7.fhir.r5.model.ElementDefinition.ElementDefinitionBindingComponent; import org.hl7.fhir.r5.model.Enumerations.FHIRVersion; import org.hl7.fhir.r5.model.StructureDefinition; +import org.hl7.fhir.r5.renderers.Renderer.RenderingStatus; import org.hl7.fhir.r5.renderers.StructureDefinitionRenderer; import org.hl7.fhir.r5.renderers.utils.RenderingContext; +import org.hl7.fhir.r5.renderers.utils.ResourceWrapper; import org.hl7.fhir.r5.utils.ToolingExtensions; import org.hl7.fhir.utilities.StandardsStatus; import org.hl7.fhir.utilities.Utilities; @@ -146,7 +149,8 @@ private String lmHeader(String n, String title, String mode, boolean hasXMlJson) private String genLogicalModelTable(StructureDefinition sd, String prefix) throws Exception { ProfileUtilities pu = new ProfileUtilities(page.getWorkerContext(), null, this); StructureDefinitionRenderer sdr = new StructureDefinitionRenderer(rc); - XhtmlNode x = sdr.generateTable(sd.getId()+"-definitions.html", sd, sd.hasSnapshot() ? false : true, page.getFolders().dstDir, false, sd.getId(), true, prefix, prefix, true, false, null, false, rc, ""); + XhtmlNode x = sdr.generateTable(new RenderingStatus(), sd.getId()+"-definitions.html", sd, sd.hasSnapshot() ? false : true, page.getFolders().dstDir, false, sd.getId(), true, prefix, prefix, true, false, null, false, rc, "", + ResourceWrapper.forResource(rc.getContextUtilities(), sd)); return new XhtmlComposer(XhtmlComposer.HTML).compose(x); } @@ -224,4 +228,9 @@ public boolean isPrimitiveType(String typeSimple) { throw new NotImplementedException("Not implemented"); } + @Override + public String getCanonicalForDefaultContext() { + return "http://hl7.org/fhir"; + } + } diff --git a/src/main/java/org/hl7/fhir/tools/publisher/OldVersionRedirector.java b/src/main/java/org/hl7/fhir/tools/publisher/OldVersionRedirector.java index 5c617b29..1f49b59f 100644 --- a/src/main/java/org/hl7/fhir/tools/publisher/OldVersionRedirector.java +++ b/src/main/java/org/hl7/fhir/tools/publisher/OldVersionRedirector.java @@ -5,9 +5,9 @@ import java.util.ArrayList; import java.util.List; -import org.hl7.fhir.utilities.CSFile; import org.hl7.fhir.utilities.TextFile; import org.hl7.fhir.utilities.Utilities; +import org.hl7.fhir.utilities.filesystem.CSFile; /** * This class takes 3 parameters: diff --git a/src/main/java/org/hl7/fhir/tools/publisher/PageProcessor.java b/src/main/java/org/hl7/fhir/tools/publisher/PageProcessor.java index 2d8d39cb..1b488a09 100644 --- a/src/main/java/org/hl7/fhir/tools/publisher/PageProcessor.java +++ b/src/main/java/org/hl7/fhir/tools/publisher/PageProcessor.java @@ -27,7 +27,7 @@ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWIS ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + */ import java.io.ByteArrayOutputStream; import java.io.File; @@ -35,9 +35,11 @@ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWIS import java.io.FileOutputStream; import java.io.IOException; import java.io.StringWriter; +import java.io.UnsupportedEncodingException; import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; import java.net.URISyntaxException; +import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.util.ArrayDeque; import java.util.ArrayList; @@ -63,8 +65,6 @@ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWIS import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMSource; @@ -137,6 +137,8 @@ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWIS import org.hl7.fhir.r5.context.CanonicalResourceManager; import org.hl7.fhir.r5.context.ILoggingService; import org.hl7.fhir.r5.elementmodel.Element; +import org.hl7.fhir.r5.elementmodel.Manager; +import org.hl7.fhir.r5.elementmodel.Manager.FhirFormat; import org.hl7.fhir.r5.fhirpath.FHIRPathEngine; import org.hl7.fhir.r5.fhirpath.TypeDetails; import org.hl7.fhir.r5.fhirpath.ExpressionNode.CollectionStatus; @@ -213,12 +215,15 @@ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWIS import org.hl7.fhir.r5.renderers.IMarkdownProcessor; import org.hl7.fhir.r5.renderers.RendererFactory; import org.hl7.fhir.r5.renderers.StructureDefinitionRenderer; -import org.hl7.fhir.r5.renderers.utils.DOMWrappers; +import org.hl7.fhir.r5.renderers.Renderer.RenderingStatus; import org.hl7.fhir.r5.renderers.utils.RenderingContext; +import org.hl7.fhir.r5.renderers.utils.ResourceWrapper; import org.hl7.fhir.r5.renderers.utils.RenderingContext.GenerationRules; import org.hl7.fhir.r5.renderers.utils.RenderingContext.ITypeParser; +import org.hl7.fhir.r5.renderers.utils.RenderingContext.QuestionnaireRendererMode; import org.hl7.fhir.r5.renderers.utils.RenderingContext.ResourceRendererMode; import org.hl7.fhir.r5.renderers.utils.Resolver.IReferenceResolver; +import org.hl7.fhir.r5.renderers.utils.Resolver.ResourceReferenceKind; import org.hl7.fhir.r5.renderers.utils.Resolver.ResourceWithReference; import org.hl7.fhir.r5.terminologies.CodeSystemUtilities; import org.hl7.fhir.r5.terminologies.TerminologyCacheManager; @@ -235,13 +240,14 @@ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWIS import org.hl7.fhir.r5.utils.validation.IResourceValidator; import org.hl7.fhir.tools.converters.MarkDownPreProcessor; import org.hl7.fhir.tools.publisher.ReferenceTracker.RefType; -import org.hl7.fhir.utilities.CSFile; -import org.hl7.fhir.utilities.CSFileInputStream; import org.hl7.fhir.utilities.CommaSeparatedStringBuilder; import org.hl7.fhir.utilities.IniFile; import org.hl7.fhir.utilities.Logger; import org.hl7.fhir.utilities.MarkDownProcessor; import org.hl7.fhir.utilities.MarkDownProcessor.Dialect; +import org.hl7.fhir.utilities.filesystem.CSFile; +import org.hl7.fhir.utilities.filesystem.CSFileInputStream; +import org.hl7.fhir.utilities.i18n.RenderingI18nContext; import org.hl7.fhir.utilities.StandardsStatus; import org.hl7.fhir.utilities.TextFile; import org.hl7.fhir.utilities.Utilities; @@ -284,7 +290,7 @@ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWIS public class PageProcessor implements Logger, ProfileKnowledgeProvider, IReferenceResolver, ILoggingService, TypeLinkProvider, ITypeParser, IMarkdownProcessor { public enum PageInfoType { PAGE, RESOURCE, OPERATION, VALUESET, CODESYSTEM; - + public String toCode() { switch (this) { case PAGE: return "page"; @@ -329,7 +335,7 @@ public String getTitle() { public String getPage() { return page; } - + } public class PageEvaluationContext implements IEvaluationContext { @@ -417,9 +423,9 @@ public int compare(String arg0, String arg1) { return 1; } } else { - int c = p0[i].compareTo(p1[i]); - if (c != 0) - return c; + int c = p0[i].compareTo(p1[i]); + if (c != 0) + return c; } } if (p0.length > p1.length) @@ -458,7 +464,7 @@ public int compare(String arg0, String arg1) { private HTMLLinkChecker htmlchecker; private final String tsServer; // terminology to use private BuildWorkerContext workerContext; -// private List collectedValidationErrors = new ArrayList(); + // private List collectedValidationErrors = new ArrayList(); private List validationErrors = new ArrayList(); private long lastSecs = 0; private Set searchTypeUsage = new HashSet(); @@ -484,23 +490,23 @@ public int compare(String arg0, String arg1) { private String getComputerName() { - Map env = System.getenv(); - if (env.containsKey("COMPUTERNAME")) - return env.get("COMPUTERNAME"); - else if (env.containsKey("HOSTNAME")) - return env.get("HOSTNAME"); - else if (env.containsKey("USERNAME")) - return env.get("USERNAME"); - else { - String res = System.getProperty("user.name"); - if (res == null) { - return "Unknown Computer"; - } else { - return res; - } + Map env = System.getenv(); + if (env.containsKey("COMPUTERNAME")) + return env.get("COMPUTERNAME"); + else if (env.containsKey("HOSTNAME")) + return env.get("HOSTNAME"); + else if (env.containsKey("USERNAME")) + return env.get("USERNAME"); + else { + String res = System.getProperty("user.name"); + if (res == null) { + return "Unknown Computer"; + } else { + return res; } + } } - + public PageProcessor(String tsServer) throws URISyntaxException, UcumException { super(); this.tsServer = tsServer; @@ -518,19 +524,19 @@ public PageProcessor(String tsServer) throws URISyntaxException, UcumException { public final static String CI_LOCATION = "http://build.fhir.org/"; public final static String CI_PUB_NAME = "FHIR CI-Build"; public final static String CI_PUB_NOTICE = - "

"+ + "

"+ "This is the Continuous Integration Build of FHIR (will be incorrect/inconsistent at times).
See the Directory of published versions"+ "

\r\n"; - + public final static String LOCAL_SEARCH = "http://build.fhir.org/search-build.html"; public final static String LOCAL_EXTN_LOCATION = "https://build.fhir.org/ig/HL7/fhir-extensions/"; public final static String LOCAL_LOCATION = "file:{dest}"; -// public final static String LOCAL_PUB_NAME = "FHIR Local Build"; + // public final static String LOCAL_PUB_NAME = "FHIR Local Build"; public final static String LOCAL_PUB_NOTICE = - "

"+ + "

"+ "This is your Local Build of FHIR.
See the Directory of published versions for published versions"+ "

\r\n"; - + private static final String REASON_UNKNOWN = "Unknown"; private static final String UNNOWN_DESCRIPTION = "no reason provided"; public static final String CODE_LIMIT_EXPANSION = "1000"; @@ -540,50 +546,50 @@ public PageProcessor(String tsServer) throws URISyntaxException, UcumException { private static final String VS_INC_END = ""; // ""; public static final String TEST_SERVER_URL = "http://test.fhir.org/r5"; -// private boolean notime; + // private boolean notime; private String dictForDt(String dt) throws Exception { - File tmp = Utilities.createTempFile("tmp", ".tmp"); - DictHTMLGenerator gen = new DictHTMLGenerator(new FileOutputStream(tmp), this, ""); - TypeParser tp = new TypeParser(version.toCode()); - TypeRef t = tp.parse(dt, false, null, workerContext, true).get(0); - - ElementDefn e; - if (t.getName().equals("Resource")) - e = definitions.getBaseResources().get("DomainResource").getRoot(); - else - e = definitions.getElementDefn(t.getName()); - if (e == null) { - gen.close(); - throw new Exception("unable to find definition for "+ dt); - } - else { - gen.generate(e); - gen.close(); - } - String val = TextFile.fileToString(tmp.getAbsolutePath())+"\r\n"; - tmp.delete(); - return val; + File tmp = Utilities.createTempFile("tmp", ".tmp"); + DictHTMLGenerator gen = new DictHTMLGenerator(new FileOutputStream(tmp), this, ""); + TypeParser tp = new TypeParser(version.toCode()); + TypeRef t = tp.parse(dt, false, null, workerContext, true).get(0); + + ElementDefn e; + if (t.getName().equals("Resource")) + e = definitions.getBaseResources().get("DomainResource").getRoot(); + else + e = definitions.getElementDefn(t.getName()); + if (e == null) { + gen.close(); + throw new Exception("unable to find definition for "+ dt); + } + else { + gen.generate(e); + gen.close(); + } + String val = TextFile.fileToString(tmp.getAbsolutePath())+"\r\n"; + tmp.delete(); + return val; } private String tsForDt(String dt) throws Exception { - File tmp = Utilities.createTempFile("tmp", ".tmp"); - tmp.deleteOnExit(); - TerminologyNotesGenerator gen = new TerminologyNotesGenerator(new FileOutputStream(tmp), this); - TypeParser tp = new TypeParser(version.toCode()); - TypeRef t = tp.parse(dt, false, null, workerContext, true).get(0); - ElementDefn e = definitions.getElementDefn(t.getName()); - if (e == null) { - gen.close(); - throw new Exception("unable to find definition for "+ dt); - } - else { - gen.generate("", e); - gen.close(); - } - String val = TextFile.fileToString(tmp.getAbsolutePath())+"\r\n"; - tmp.delete(); - return val; + File tmp = Utilities.createTempFile("tmp", ".tmp"); + tmp.deleteOnExit(); + TerminologyNotesGenerator gen = new TerminologyNotesGenerator(new FileOutputStream(tmp), this); + TypeParser tp = new TypeParser(version.toCode()); + TypeRef t = tp.parse(dt, false, null, workerContext, true).get(0); + ElementDefn e = definitions.getElementDefn(t.getName()); + if (e == null) { + gen.close(); + throw new Exception("unable to find definition for "+ dt); + } + else { + gen.generate("", e); + gen.close(); + } + String val = TextFile.fileToString(tmp.getAbsolutePath())+"\r\n"; + tmp.delete(); + return val; } private String treeForDt(String dt, String linkPrefix) throws Exception { @@ -592,22 +598,22 @@ private String treeForDt(String dt, String linkPrefix) throws Exception { } private String xmlForDt(String dt, String pn) throws Exception { - File tmp = Utilities.createTempFile("tmp", ".tmp"); - XmlSpecGenerator gen = new XmlSpecGenerator(new FileOutputStream(tmp), pn == null ? null : pn.substring(0, pn.indexOf("."))+"-definitions.html", null, this, ""); - TypeParser tp = new TypeParser(version.toCode()); - TypeRef t = tp.parse(dt, false, null, workerContext, true).get(0); - ElementDefn e = definitions.getElementDefn(t.getName()); - if (e == null) { - gen.close(); - throw new Exception("unable to find definition for "+ dt); - } - else { - gen.generate(e, e.getName().equals("Element") || e.getName().equals("BackboneElement"), false); - gen.close(); - } - String val = TextFile.fileToString(tmp.getAbsolutePath())+"\r\n"; - tmp.delete(); - return val; + File tmp = Utilities.createTempFile("tmp", ".tmp"); + XmlSpecGenerator gen = new XmlSpecGenerator(new FileOutputStream(tmp), pn == null ? null : pn.substring(0, pn.indexOf("."))+"-definitions.html", null, this, ""); + TypeParser tp = new TypeParser(version.toCode()); + TypeRef t = tp.parse(dt, false, null, workerContext, true).get(0); + ElementDefn e = definitions.getElementDefn(t.getName()); + if (e == null) { + gen.close(); + throw new Exception("unable to find definition for "+ dt); + } + else { + gen.generate(e, e.getName().equals("Element") || e.getName().equals("BackboneElement"), false); + gen.close(); + } + String val = TextFile.fileToString(tmp.getAbsolutePath())+"\r\n"; + tmp.delete(); + return val; } private String jsonForDt(String dt, String pn) throws Exception { @@ -754,10 +760,10 @@ else if (com[0].equals("refheader")) src = s1+refHeader(com.length > 1 ? com[1] : null)+s3; else if (com[0].equals("resourcesheader")) src = s1+resourcesHeader(com.length > 1 ? com[1] : null)+s3; -// else if (com[0].equals("formatsheader")) -// src = s1+formatsHeader(name, com.length > 1 ? com[1] : null)+s3; -// else if (com[0].equals("resourcesheader")) -// src = s1+resourcesHeader(name, com.length > 1 ? com[1] : null)+s3; + // else if (com[0].equals("formatsheader")) + // src = s1+formatsHeader(name, com.length > 1 ? com[1] : null)+s3; + // else if (com[0].equals("resourcesheader")) + // src = s1+resourcesHeader(name, com.length > 1 ? com[1] : null)+s3; else if (com[0].equals("txheader")) src = s1+txHeader(name, com.length > 1 ? com[1] : null)+s3; else if (com[0].equals("sct-vs-list")) @@ -772,8 +778,8 @@ else if (com[0].equals("cmpheader")) src = s1+cmpHeader(name, com.length > 1 ? com[1] : null)+s3; else if (com[0].equals("dictheader")) src = s1+dictHeader(((Bundle) resource).getId().toLowerCase(), com.length > 1 ? com[1] : "")+s3; -// else if (com[0].equals("atomheader")) -// src = s1+atomHeader(name, com.length > 1 ? com[1] : null)+s3; + // else if (com[0].equals("atomheader")) + // src = s1+atomHeader(name, com.length > 1 ? com[1] : null)+s3; else if (com[0].equals("codelist")) src = s1+codelist((CodeSystem) resource, com.length > 1 ? com[1] : null, false, true, file)+s3; else if (com[0].equals("codelist-nh")) @@ -796,7 +802,7 @@ else if (rd != null) { else if (com[0].equals("onthispage")) src = s1+onThisPage(s2.substring(com[0].length() + 1))+s3; else if (com[0].equals("maponthispage")) - src = s1+mapOnThisPage(null)+s3; + src = s1+mapOnThisPage(null)+s3; else if (com[0].equals("res-category")) { even = false; src = s1+resCategory(s2.substring(com[0].length() + 1))+s3; @@ -857,7 +863,7 @@ else if (com[0].equals("conceptmaplistvs")) { level = Integer.parseInt(com[1]); src = s1+s3; } else if (com[0].equals("w5")) { - src = s1+genW5("true".equals(com[1]))+s3; + src = s1+genW5("true".equals(com[1]))+s3; } else if (com[0].equals("res-ref-list")) { src = s1+genResRefList(com[1])+s3; } else if (com[0].equals("sclist")) { @@ -888,7 +894,7 @@ else if (com[0].equals("conceptmaplistvs")) { } else if (com[0].equals("search-footer")) { src = s1+searchFooter(level)+s3; } else if (com[0].equals("search-header")) { - src = s1+searchHeader(level)+s3; + src = s1+searchHeader(level)+s3; } else if (com[0].equals("profileheader")) { src = s1+profileHeader(((StructureDefinition) resource).getId().toLowerCase(), com[1], hasExamples((StructureDefinition) resource, ig))+s3; } else if (com[0].equals("resource-table")) { @@ -907,10 +913,10 @@ else if (com[0].equals("conceptmaplistvs")) { } else if (com[0].equals("profile-diff")) { ConstraintStructure p = definitions.findProfile(com[1]); src = s1 + generateProfileStructureTable(p, true, com[1]+".html", com[1], genlevel(level)) + s3; -// } else if (com[0].equals("example")) { -// String[] parts = com[1].split("\\/"); -// Example e = findExample(parts[0], parts[1]); -// src = s1+genExample(e, com.length > 2 ? Integer.parseInt(com[2]) : 0, genlevel(level))+s3; + // } else if (com[0].equals("example")) { + // String[] parts = com[1].split("\\/"); + // Example e = findExample(parts[0], parts[1]); + // src = s1+genExample(e, com.length > 2 ? Integer.parseInt(com[2]) : 0, genlevel(level))+s3; } else if (com[0].equals("r4r5transform")) { src = s1+dtR4R5Transform(com[1])+s3; } else if (com[0].equals("fmm-style")) { @@ -1102,10 +1108,10 @@ else if (com[0].equals("datatypecodes")) src = s1 + genDTCodes() + s3; else if (com[0].equals("allparams")) src = s1 + allParamlist() + s3; -// else if (com[0].equals("bindingtable-codelists")) -// src = s1 + genBindingTable(true) + s3; -// else if (com[0].equals("bindingtable")) -// src = s1 + genBindingsTable() + s3; + // else if (com[0].equals("bindingtable-codelists")) + // src = s1 + genBindingTable(true) + s3; + // else if (com[0].equals("bindingtable")) + // src = s1 + genBindingsTable() + s3; else if (com[0].equals("codeslist")) src = s1 + genCodeSystemsTable() + s3; else if (com[0].equals("valuesetslist")) @@ -1118,10 +1124,10 @@ else if (com[0].equals("igvaluesetslist")) src = s1 + genIGValueSetsTable() + s3; else if (com[0].equals("conceptmapslist")) src = s1 + genConceptMapsTable() + s3; -// else if (com[0].equals("bindingtable-others")) -// src = s1 + genBindingTable(false) + s3; + // else if (com[0].equals("bindingtable-others")) + // src = s1 + genBindingTable(false) + s3; else if (com[0].equals("resimplall")) - src = s1 + genResImplList() + s3; + src = s1 + genResImplList() + s3; else if (com[0].equals("txurl")) src = s1 + "http://hl7.org/fhir/"+Utilities.fileTitle(file) + s3; else if (com[0].equals("vstxurl")) @@ -1166,7 +1172,7 @@ else if (com[0].equals("csnamed")) { } else if (com[0].equals("csstatus")) { src = s1 + checkTitle(((CodeSystem) resource).getStatus().toCode()) + s3; } else if (com[0].equals("vstitle")) { - src = s1 + checkTitle(((ValueSet) resource).getTitle()) + s3; + src = s1 + checkTitle(((ValueSet) resource).getTitle()) + s3; } else if (com[0].equals("cstitle")) { src = s1 + checkTitle(((CodeSystem) resource).getTitle()) + s3; } else if (com[0].equals("vsver") || com[0].equals("ext-ver")) { @@ -1185,8 +1191,8 @@ else if (com[0].equals("vsusage")) src = s1 + generateValueSetUsage((ValueSet) resource, genlevel(level), true) + s3; else if (com[0].equals("csusage")) src = s1 + generateCSUsage((CodeSystem) resource, genlevel(level)) + s3; -// else if (com[0].equals("vssummary")) -// src = s1 + "todo" + s3; + // else if (com[0].equals("vssummary")) + // src = s1 + "todo" + s3; else if (com[0].equals("compartmentlist")) src = s1 + compartmentlist() + s3; else if (com[0].equals("qa")) @@ -1268,8 +1274,8 @@ else if (com[0].equals("status-codes")) else if (com[0].equals("dictionary.name")) { String n = name.contains(File.separator) ? name.substring(name.lastIndexOf(File.separator)+1) : name; src = s1 + definitions.getDictionaries().get(n).getName() + s3; -// } else if (com[0].equals("dictionary.view")) -// src = s1 + ResourceUtilities.representDataElementCollection(this.workerContext, (Bundle) resource, true, "hspc-qnlab-de") + s3; + // } else if (com[0].equals("dictionary.view")) + // src = s1 + ResourceUtilities.representDataElementCollection(this.workerContext, (Bundle) resource, true, "hspc-qnlab-de") + s3; } else if (com[0].equals("search-param-pack") && resource instanceof SearchParameter) src = s1 + ((SearchParameter) resource).getUserData("pack").toString().toLowerCase() + s3; else if (com[0].equals("search-param-name") && resource instanceof SearchParameter) @@ -1389,10 +1395,10 @@ else if (com[0].equals("operation.1")) { Operation op = (Operation) object; src = s1+genOperation2(op, rd.getName(), rd.getName().toLowerCase(), false, rd.getStatus(), genlevel(level), rd.getNormativePackage())+s3; } else if (com[0].equals("past-narrative-link")) { - if (object == null || !(object instanceof Boolean)) - src = s1 + s3; - else - src = s1 + "

Jump past Narrative

" + s3; + if (object == null || !(object instanceof Boolean)) + src = s1 + s3; + else + src = s1 + "

Jump past Narrative

" + s3; } else if (others != null && others.containsKey(s2)) src = s1+others.get(s2)+s3; else if (com[0].equals("canonical-resources")) @@ -1420,7 +1426,7 @@ else if (com[0].equals("special-search-parameters")) { } else if (com[0].equals("jira-link")) { src = s1+genJiralink(file, null)+s3; } else if (com[0].equals("search-location")) { - src = s1+searchLocation+s3; + src = s1+searchLocation+s3; } else if (com[0].equals("extensions-location")) { src = s1+extensionsLocation+s3; } else if (com[0].equals("multi-language-resources")) { @@ -1497,22 +1503,22 @@ private String vsFlags(ValueSet vs) { String c = ""; if (vs.hasExperimental() || vs.hasImmutable()) { c = c + - Utilities.stringJoin(", ", vs.hasExperimental() && vs.getExperimental() ? "Experimental" : "", - (vs.hasImmutable() && vs.getImmutable() ? "Immutable" : "")); + Utilities.stringJoin(", ", vs.hasExperimental() && vs.getExperimental() ? "Experimental" : "", + (vs.hasImmutable() && vs.getImmutable() ? "Immutable" : "")); } return c; - + } - + private String csFlags(CodeSystem cs) { String c = ""; if (cs.hasExperimental() || cs.hasCaseSensitive() || cs.hasCompositional() || cs.hasContent() || cs.hasVersionNeeded()) { c = c + - Utilities.stringJoin(", ", cs.hasExperimental() && cs.getExperimental() ? "Experimental" : "", - (cs.hasCaseSensitive() ? cs.getCaseSensitive() ? "CaseSensitive" : "Not CaseSensitive" : ""), - (cs.hasVersionNeeded() && cs.getVersionNeeded() ? "VersionNeeded" : ""), - (cs.hasCompositional() && cs.getCompositional() ? "Compositional" : ""), - (cs.hasContent() ? cs.getContent().getDisplay() : "")); + Utilities.stringJoin(", ", cs.hasExperimental() && cs.getExperimental() ? "Experimental" : "", + (cs.hasCaseSensitive() ? cs.getCaseSensitive() ? "CaseSensitive" : "Not CaseSensitive" : ""), + (cs.hasVersionNeeded() && cs.getVersionNeeded() ? "VersionNeeded" : ""), + (cs.hasCompositional() && cs.getCompositional() ? "Compositional" : ""), + (cs.hasContent() ? cs.getContent().getDisplay() : "")); } if (cs.hasSupplements()) { c = c + ". Supplements: "+cs.getSupplements(); @@ -1553,14 +1559,14 @@ private String buildDTStatus(String tn) throws Exception { String wgref = "http://www.hl7.org/Special/committees/fiwg/index.cfm"; String wgn = "FHIR Infrastructure"; return ""+ - ""+ - "
"+wgn+" Work GroupMaturity Level: "+td.getFmmLevel()+"Standards Status: "+td.getStandardsStatus().toDisplay()+"
"; + "Maturity Level: "+td.getFmmLevel()+""+ + "Standards Status: "+td.getStandardsStatus().toDisplay()+""; } private String genJiralink(String file, String rn) { String url = Utilities.pathURL(webLocation, file); return "https://jira.hl7.org/secure/CreateIssueDetails!init.jspa?pid=10405&issuetype=10600&customfield_11302=FHIR-core&"+ - "customfield_11808=R5&customfield_10612="+url/*+(rn = null ? "" : "&customfield_11300="+rn)*/; + "customfield_11808=R5&customfield_10612="+url/*+(rn = null ? "" : "&customfield_11300="+rn)*/; } @@ -1575,16 +1581,16 @@ private String fileSuffix(String file) { private String getSTUNoteHeader(String id) { return - "\r\n"+ - "
\r\n"+ - "

Note to Implementers:\r\n"; + "\r\n"+ + "

\r\n"+ + "

Note to Implementers:\r\n"; } private String getBallotNoteHeader(String id) { return - "\r\n"+ - "

\r\n"+ - "

Note to Balloters:\r\n"; + "\r\n"+ + "

\r\n"+ + "

Note to Balloters:\r\n"; } private String genExampleXRef(String type, String name, Resource resource) { @@ -1686,7 +1692,7 @@ private String genDiffLinks() { for (String n : definitions.sortedResourceNames()) { resourceDiffLinks(b, n); } - + b.append("\r\n"); return b.toString(); } @@ -1723,7 +1729,7 @@ private String buildShortParameterList(String param) throws Exception { ResourceDefn rd = definitions.getResourceByName(op[0]); Operation od = rd.getOperationByName(op[1].substring(1)); - + StringBuilder b = new StringBuilder(); b.append("\r\n"); for (OperationParameter pd : od.getParameters()) { @@ -1731,7 +1737,7 @@ private String buildShortParameterList(String param) throws Exception { b.append("\r\n"); } b.append("
"+pd.getName()+""+processMarkdown("short param list", pd.getDoc(), "")+"
\r\n"); - + return b.toString(); } @@ -1786,7 +1792,7 @@ private void genBestPracticeList(StringBuilder b, ElementDefn e) throws Exceptio private String buildCircularReferenceList(Boolean hierarchy) { StringBuilder b = new StringBuilder(); - + for (String s : sorted(definitions.getResources().keySet())) { ResourceDefn t = definitions.getResources().get(s); buildCircularReferenceList(b, s, t.getRoot(), t, hierarchy); @@ -1826,7 +1832,7 @@ private void buildCircularReferenceList(StringBuilder b, String s, ElementDefn t buildCircularReferenceList(b, s, e, rd, hierarchy); } - + private boolean pointsAtElement(SearchParameterDefn sp, ElementDefn t) { if (sp.getType() != SearchType.reference) return false; @@ -1870,18 +1876,18 @@ private String getStandardsStatusNote(String prefix, String value, String type, "

\r\n"; case NORMATIVE: return ansiNote("This "+type.replace("_", " ")+" has", pack, ""); -// return "

\r\n" + -// "ANSI Note: This "+type.replace("_", " ")+" is normative content as part of the overall resource for R4 in the "+Utilities.capitalize(pack)+" Package.\r\n" + -// "

\r\n"; + // return "

\r\n" + + // "ANSI Note: This "+type.replace("_", " ")+" is normative content as part of the overall resource for R4 in the "+Utilities.capitalize(pack)+" Package.\r\n" + + // "

\r\n"; } throw new Error("Not done yet"); } private String produceDataTypeTx(String dtname) throws Exception { - + TypeDefn dt = definitions.getElementDefn(dtname); ByteArrayOutputStream bs = new ByteArrayOutputStream(); - + TerminologyNotesGenerator tgen = new TerminologyNotesGenerator(bs, this); tgen.setNoHeader(true); tgen.generate("", dt); @@ -1897,11 +1903,11 @@ private String getNormativeList(String genlevel, String name) { } else { StringBuilder b = new StringBuilder(); b.append("
\r\n"); -// b.append("
    \r\n"); -// for (String s : sorted(map.keySet())) { -// b.append("
  • "+map.get(s)+"
  • \r\n"); -// } -// b.append("
\r\n"); + // b.append("
    \r\n"); + // for (String s : sorted(map.keySet())) { + // b.append("
  • "+map.get(s)+"
  • \r\n"); + // } + // b.append("
\r\n"); b.append("\r\n"); // pages, resources, operations, value sets, code systems normativeCell(b, map, PageInfoType.PAGE); @@ -1931,20 +1937,20 @@ private void normativeCell(StringBuilder b, Map map, PageInfoT int i = s.toLowerCase().indexOf(type.toCode()+" "); if (i > -1) s = s.substring(0, i)+s.substring(i+type.toCode().length()+1); - + String pn = p.getPage(); String pnd = Utilities.changeFileExt(pn, "-definitions.html"); if (pageExists(pnd)) b.append("
  • "+Utilities.escapeXml(s)+"
  • \r\n"); -// "ΔR "+ -// "ΔB\r\n"+ -// "
    + Defns: ΔR "+ -// "ΔB"); + // "ΔR "+ + // "ΔB\r\n"+ + // "
    + Defns: ΔR "+ + // "ΔB"); else b.append("
  • "+Utilities.escapeXml(s)+"
  • \r\n"); -// "ΔR "+ -// "ΔB; + // "ΔR "+ + // "ΔB; } b.append(""); b.append("\r\n"); @@ -1964,22 +1970,22 @@ private boolean pageExists(String pnd) { private String ansiNote(String statusDesc, String pack, String genlevel) { return ansiNote(statusDesc, pack, genlevel, null); } - + private String ansiNote(String statusDesc, String pack, String genlevel, String suffix) { return ""; -// "
    \r\n"+ -// " \r\n"+ -// " \r\n"+ -// " \r\n"+ -// " \r\n"+ -// "
    \r\n"+ -// " \r\n"+ // -// " \r\n"+ -// " "+statusDesc+" been approved as part of an ANSI standard.\r\n"+ -// " See the "+Utilities.capitalize(pack)+" Package for further details.\r\n"+ (Utilities.noString(suffix) ? "" : suffix)+ -// "
    \r\n"; - } - + // "\r\n"+ + // " \r\n"+ + // " \r\n"+ + // " \r\n"+ + // " \r\n"+ + // "
    \r\n"+ + // " \r\n"+ // + // " \r\n"+ + // " "+statusDesc+" been approved as part of an ANSI standard.\r\n"+ + // " See the "+Utilities.capitalize(pack)+" Package for further details.\r\n"+ (Utilities.noString(suffix) ? "" : suffix)+ + // "
    \r\n"; + } + private String getNormativeNote(String genlevel, String pack, String type, String title, String filename) throws Exception { if (pack == null) throw new Error("Normative package not known for "+filename); @@ -1992,10 +1998,10 @@ private String getNormativeNote(String genlevel, String pack, String type, Strin map.put(filename, new PageInfo(PageInfoType.fromCode(type), filename, title)); } return ansiNote("This page has", pack, genlevel); -// "

    \r\n" + -// "ANSI "+Utilities.capitalize(pack)+" .\r\n" + -// "

    \r\n" + -// ""; + // "

    \r\n" + + // "ANSI "+Utilities.capitalize(pack)+" .\r\n" + + // "

    \r\n" + + // ""; } private String getMixedNormativeNote(String genlevel, String pack, String type, String title, String filename) throws Exception { @@ -2008,10 +2014,10 @@ private String getMixedNormativeNote(String genlevel, String pack, String type, map.put(filename, new PageInfo(PageInfoType.fromCode(type), filename, title)); } return ansiNote("Some of the content on this page (marked clearly) has", pack, genlevel); -// "

    \r\n" + -// "ANSI Note: Some of the content on this page (marked clearly) is normative content in the "+Utilities.capitalize(pack)+" Package.\r\n" + -// "

    \r\n" + -// ""; + // "

    \r\n" + + // "ANSI Note: Some of the content on this page (marked clearly) is normative content in the "+Utilities.capitalize(pack)+" Package.\r\n" + + // "

    \r\n" + + // ""; } private String getMostlyNormativeNote(String genlevel, String pack, String type, String title, String filename) throws Exception { @@ -2024,11 +2030,11 @@ private String getMostlyNormativeNote(String genlevel, String pack, String type, map.put(filename, new PageInfo(PageInfoType.fromCode(type), filename, title)); } return ansiNote("Most of the content on this page has", pack, genlevel, "The few parts of this page that are not normative are clearly marked"); -// return "

    \r\n" + -// "ANSI Note: Most of the content on this page is normative content in the "+Utilities.capitalize(pack)+" Package.\r\n" + -// "Once normative, it will lose it's Maturity Level, and breaking changes will no longer be made. \r\n" + -// "

    \r\n" + -// ""; + // return "

    \r\n" + + // "ANSI Note: Most of the content on this page is normative content in the "+Utilities.capitalize(pack)+" Package.\r\n" + + // "Once normative, it will lose it's Maturity Level, and breaking changes will no longer be made. \r\n" + + // "

    \r\n" + + // ""; } private String buildResListByFMG() throws FHIRException { @@ -2038,7 +2044,7 @@ private String buildResListByFMG() throws FHIRException { for (ResourceDefn rd : definitions.getResources().values()) res.add(rd.getName()); Collections.sort(res); - + StringBuilder b = new StringBuilder(); listByApprovalStatus(b, res, FMGApproval.NOPROPOSAL, "Not yet proposed"); listByApprovalStatus(b, res, FMGApproval.PENDING, "Pending"); @@ -2067,7 +2073,7 @@ private String buildResListByMaturity() throws FHIRException { for (ResourceDefn rd : definitions.getResources().values()) res.add(rd.getFmmLevel()+":" +rd.getName()); Collections.sort(res); - + StringBuilder b = new StringBuilder(); for (int i = 5; i >= 0; i--) { b.append("

    Level "); @@ -2095,7 +2101,7 @@ private String buildResListBySecurity() throws FHIRException { for (ResourceDefn rd : definitions.getResources().values()) res.add((rd.getSecurityCategorization() == null ? "9" : rd.getSecurityCategorization().toIndex())+":" +rd.getName()); Collections.sort(res); - + StringBuilder b = new StringBuilder(); for (int i = 0; i <= 5; i++) { b.append("

    "+secCategory(i)); @@ -2134,7 +2140,7 @@ private String buildResListByBallot() throws FHIRException { for (ResourceDefn rd : definitions.getResources().values()) res.add(rd.getName()); Collections.sort(res); - + StringBuilder b = new StringBuilder(); StandardsStatus[] values = StandardsStatus.values(); for (int i = values.length - 1; i >= 0; i--) { @@ -2222,7 +2228,7 @@ private String dtR4R5Transform(String name) throws Exception { File f = new File(Utilities.path(folders.rootDir, "implementations", "r3maps", "R4toR3", name+".map")); if (!f.exists()) { - return "No R4/R5 map exists for "+name; + return "No R4/R5 map exists for "+name; } String n = name.toLowerCase(); String status = r4r5StatusForResource(name); @@ -2264,7 +2270,7 @@ private String dtR4R5Transform(String name) throws Exception { } public String r4nameForResource(String name) { - + if ("DeviceUseStatement".equals(name)) { return "DeviceUsage"; } @@ -2403,7 +2409,7 @@ public String genChoiceElementsJson() throws Exception { ElementDefn t = definitions.getTypes().get(s); buildChoiceElementList(b, s, t); } - + for (String s : sorted(definitions.getResources().keySet())) { ResourceDefn t = definitions.getResources().get(s); buildChoiceElementList(b, s, t.getRoot()); @@ -2411,7 +2417,7 @@ public String genChoiceElementsJson() throws Exception { return "{\r\n \"elements\" : {\r\n"+b.toString()+"\r\n }\r\n}\r\n"; } - + public String genBackboneElementsJson() throws Exception { List classes = new ArrayList(); listAllbackboneClasses(classes); @@ -2567,12 +2573,12 @@ private String genIdentifierList() throws Exception { if (c == null) b.append(" "+Utilities.escapeXml(ns.getType().getText())+country+"\r\n"); else { - if (c.getSystem().equals("http://hl7.org/fhir/identifier-type")) - b.append(" "+c.getCode()+""+country+"\r\n"); - else if (c.getSystem().equals("http://terminology.hl7.org/CodeSystem/v2-0203")) - b.append(" "+c.getCode()+""+country+"\r\n"); - else - throw new Exception("Unknown Identifier Type System"); + if (c.getSystem().equals("http://hl7.org/fhir/identifier-type")) + b.append(" "+c.getCode()+""+country+"\r\n"); + else if (c.getSystem().equals("http://terminology.hl7.org/CodeSystem/v2-0203")) + b.append(" "+c.getCode()+""+country+"\r\n"); + else + throw new Exception("Unknown Identifier Type System"); } } else b.append(" "+country+"\r\n"); @@ -2621,7 +2627,7 @@ private String getUri(NamingSystem ns) { private String genCompModel(StructureDefinition sd, String name, String base, String prefix) throws Exception { if (sd == null) return "

    No "+name+" could be generated

    \r\n"; - return new XhtmlComposer(XhtmlComposer.HTML).compose(new StructureDefinitionRenderer(rc).generateTable("??", sd, false, folders.dstDir, false, base, true, prefix, prefix, false, false, null, false, rc.copy().setLang("*"), "")); + return new XhtmlComposer(XhtmlComposer.HTML).compose(new StructureDefinitionRenderer(rc).generateTable(new RenderingStatus(), "??", sd, false, folders.dstDir, false, base, true, prefix, prefix, false, false, null, false, rc.copy(false).withLocale(null), "", ResourceWrapper.forResource(rc.getContextUtilities(), sd))); } private String genPCLink(String leftName, String leftLink) { @@ -2662,9 +2668,9 @@ private String txsummary(ValueSet vs, String prefix) throws Exception { c = "Copyright:"+processMarkdown("vs.copyright", vs.getCopyright(), prefix)+"\r\n"; if (vs.hasExperimental() || vs.hasImmutable()) { c = c + "Flags:"+ - Utilities.stringJoin(", ", vs.hasExperimental() && vs.getExperimental() ? "Experimental" : "", - (vs.hasImmutable() && vs.getImmutable() ? "Immutable" : ""))+ - "\r\n"; + Utilities.stringJoin(", ", vs.hasExperimental() && vs.getExperimental() ? "Experimental" : "", + (vs.hasImmutable() && vs.getImmutable() ? "Immutable" : ""))+ + "\r\n"; } return c; } @@ -2675,12 +2681,12 @@ private String txsummary(CodeSystem cs, String prefix) throws Exception { c = "Copyright:"+processMarkdown("cs.copyright", cs.getCopyright(), prefix)+"\r\n"; if (cs.hasExperimental() || cs.hasCaseSensitive() || cs.hasCompositional() || cs.hasContent() || cs.hasVersionNeeded()) { c = c + "Flags:"+ - Utilities.stringJoin(", ", cs.hasExperimental() && cs.getExperimental() ? "Experimental" : "", - (cs.hasCaseSensitive() ? cs.getCaseSensitive() ? "CaseSensitive" : "Not CaseSensitive" : ""), - (cs.hasVersionNeeded() && cs.getVersionNeeded() ? "VersionNeeded" : ""), - (cs.hasCompositional() && cs.getCompositional() ? "Compositional" : ""), - (cs.hasContent() ? cs.getContent().getDisplay() : ""))+ - "\r\n"; + Utilities.stringJoin(", ", cs.hasExperimental() && cs.getExperimental() ? "Experimental" : "", + (cs.hasCaseSensitive() ? cs.getCaseSensitive() ? "CaseSensitive" : "Not CaseSensitive" : ""), + (cs.hasVersionNeeded() && cs.getVersionNeeded() ? "VersionNeeded" : ""), + (cs.hasCompositional() && cs.getCompositional() ? "Compositional" : ""), + (cs.hasContent() ? cs.getContent().getDisplay() : ""))+ + "\r\n"; } if (cs.hasValueSet()) { ValueSet vs = definitions.getValuesets().get(cs.getValueSet()); @@ -2720,10 +2726,10 @@ private String genExampleProfileLink(Resource resource) throws FHIRException { } private String umlForDt(String dt, String id) throws Exception { - if (!"Base".equals(dt)) { + if (!"Base".equals(dt)) { dt = dt+","+definitions.getElementDefn(dt).typeCode(); - } - + } + File tmp = Utilities.createTempFile("tmp", ".tmp"); tmp.deleteOnExit(); try { @@ -2756,22 +2762,22 @@ private String genExtensionsTable() throws Exception { Collections.sort(names); Set processed = new HashSet(); for (ImplementationGuideDefn ig : definitions.getSortedIgs()) { -// if (ig.isCore()) { - for (String n : names) { - StructureDefinition ed = workerContext.fetchResource(StructureDefinition.class, n); - if (!processed.contains(ed)) { - processed.add(ed); -// if (ig.getCode().equals(ToolResourceUtilities.getUsage(ed))) { - genExtensionRow(ig, s, ed); -// } - } + // if (ig.isCore()) { + for (String n : names) { + StructureDefinition ed = workerContext.fetchResource(StructureDefinition.class, n); + if (!processed.contains(ed)) { + processed.add(ed); + // if (ig.getCode().equals(ToolResourceUtilities.getUsage(ed))) { + genExtensionRow(ig, s, ed); + // } } -// } + } + // } } s.append("\r\n"); return s.toString(); } - + private void genExtensionRow(ImplementationGuideDefn ig, StringBuilder s, StructureDefinition ed) throws Exception { StandardsStatus status = ToolingExtensions.getStandardsStatus(ed); if (status == StandardsStatus.DEPRECATED) { @@ -2811,7 +2817,7 @@ else if (definitions.hasResource(ref)) else s.append(ec.getExpression()); } else if (ec.getType() == ExtensionContextType.FHIRPATH) { - s.append(Utilities.escapeXml(ec.getExpression())); + s.append(Utilities.escapeXml(ec.getExpression())); } else if (ec.getType() == ExtensionContextType.EXTENSION) { StructureDefinition extension = workerContext.fetchResource(StructureDefinition.class, ec.getExpression()); if (extension==null) @@ -2835,8 +2841,8 @@ else if (definitions.hasResource(ref)) } String uc = ed.hasUserData("usage.count") ? ed.getUserData("usage.count").toString() : ""; s.append(""+uc+""); -// s.append("XML"); -// s.append("JSON"); + // s.append("XML"); + // s.append("JSON"); s.append(""); } @@ -3150,13 +3156,13 @@ private String genOperationList() throws Exception { ResourceDefn r = definitions.getResourceByName(n); genOperationDetails(b, n, r.getOperations(), false); } -// b.append(" Operations Defined by Implementation Guides\r\n"); -// for (ImplementationGuideDefn ig : definitions.getSortedIgs()) { -// for (Profile p : ig.getProfiles()) { -// if (!p.getOperations().isEmpty()) -// genOperationDetails(b, ig.getCode()+File.separator+p.getId(), p.getOperations(), false); -// } -// } + // b.append(" Operations Defined by Implementation Guides\r\n"); + // for (ImplementationGuideDefn ig : definitions.getSortedIgs()) { + // for (Profile p : ig.getProfiles()) { + // if (!p.getOperations().isEmpty()) + // genOperationDetails(b, ig.getCode()+File.separator+p.getId(), p.getOperations(), false); + // } + // } b.append(""); return b.toString(); } @@ -3277,14 +3283,14 @@ else if (level.equals("l3")) b.append(" "); if (cm.getSourceScopeCanonicalType().getValue().equals(id)) { b.append("to ") - .append(describeValueSetByRef(cm.getTargetScope())); + .append(describeValueSetByRef(cm.getTargetScope())); } else { b.append("from ") - .append(describeValueSetByRef(cm.getSourceScope())); + .append(describeValueSetByRef(cm.getSourceScope())); } b.append("").append(cm.getName()) - .append("XMLJSON"); + .append("XMLJSON"); } b.append("\r\n"); return b.toString(); @@ -3432,15 +3438,15 @@ private String compResourceMap(String name) throws Exception { out.append("
  • ").append(rd.getName()).append("
  • \r\n"); } else { // if (!rules.equals("{def}")) { in.append(" ").append(rd.getName()).append("") - .append(rules.replace("|", "or").replace("{def}", "[base]")).append("\r\n"); + .append(rules.replace("|", "or").replace("{def}", "[base]")).append("\r\n"); } } return "

    \r\nThe following resources may be in this compartment:\r\n

    \r\n" + - "\r\n"+ - " \r\n"+ - in.toString()+ - "
    ResourceInclusion Criteria
    \r\n"+ - "

    \r\nA resource is in this compartment if the nominated search parameter (or chain) refers to the "+name+" resource that defines the compartment.\r\n

    \r\n"; + "\r\n"+ + " \r\n"+ + in.toString()+ + "
    ResourceInclusion Criteria
    \r\n"+ + "

    \r\nA resource is in this compartment if the nominated search parameter (or chain) refers to the "+name+" resource that defines the compartment.\r\n

    \r\n"; } private String compartmentlist() { @@ -3449,7 +3455,7 @@ private String compartmentlist() { b.append(" TitleDescriptionIdentityMembership\r\n"); for (Compartment c : definitions.getCompartments()) { b.append(" ").append(c.getTitle()).append("") - .append(Utilities.escapeXml(c.getDescription())).append("").append("").append(Utilities.escapeXml(c.getIdentity())).append("").append(Utilities.escapeXml(c.getMembership())).append("\r\n"); + .append(Utilities.escapeXml(c.getDescription())).append("").append("").append(Utilities.escapeXml(c.getIdentity())).append("").append(Utilities.escapeXml(c.getMembership())).append("\r\n"); } b.append("\r\n"); return b.toString(); @@ -3458,7 +3464,7 @@ private String compartmentlist() { private String renderCodeSystemWithLangs(Set langs, CodeSystem cs, String prefix) throws Exception { Narrative n = cs.getText(); - + StringBuilder b = new StringBuilder(); b.append("
    \r\n"); b.append("
      \r\n"); @@ -3470,26 +3476,26 @@ private String renderCodeSystemWithLangs(Set langs, CodeSystem cs, Strin b.append("
      \r\n"); cs.setText(null); - RenderingContext lrc = rc.copy().setLang("*").setCopyButton(true); - RendererFactory.factory(cs, lrc).render(cs); + RenderingContext lrc = rc.copy(false).withLocale(null).setCopyButton(true); + RendererFactory.factory(cs, lrc).renderResource(ResourceWrapper.forResource(lrc.getContextUtilities(), cs)); b.append(new XhtmlComposer(XhtmlComposer.HTML).compose(cs.getText().getDiv())); b.append("
      \r\n"); - + b.append("
      \r\n"); cs.setText(null); - lrc = rc.copy().setLang("en"); - RendererFactory.factory(cs, lrc).render(cs); + lrc = rc.copy(false).withLocaleCode("en"); + RendererFactory.factory(cs, lrc).renderResource(ResourceWrapper.forResource(lrc.getContextUtilities(), cs)); b.append(new XhtmlComposer(XhtmlComposer.HTML).compose(cs.getText().getDiv())); b.append("
      \r\n"); - + for (String l : sorted(langs)) { b.append("
      \r\n"); String desc = cs.getDescriptionElement().getTranslation(l); if (!Utilities.noString(desc)) - b.append(processMarkdown("RenderingCodeSystem", workerContext.translator().translate("render-cs", "Definition", l)+": "+desc, prefix)); + b.append(processMarkdown("RenderingCodeSystem", "Definition: "+desc, prefix)); cs.setText(null); - lrc = rc.copy().setLang(l); - RendererFactory.factory(cs, lrc).render(cs); + lrc = rc.copy(false).withLocaleCode(l); + RendererFactory.factory(cs, lrc).renderResource(ResourceWrapper.forResource(lrc.getContextUtilities(), cs)); b.append(new XhtmlComposer(XhtmlComposer.HTML).compose(cs.getText().getDiv())); b.append("
      \r\n"); } @@ -3537,7 +3543,7 @@ private void findTranslations(Set res, List private String r2Json(ValueSet vs) throws Exception { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); IParser json = new JsonParser().setOutputStyle(OutputStyle.PRETTY); -// json.setSuppressXhtml("Snipped for Brevity"); + // json.setSuppressXhtml("Snipped for Brevity"); json.compose(bytes, vs); return new String(bytes.toByteArray()); } @@ -3545,7 +3551,7 @@ private String r2Json(ValueSet vs) throws Exception { private String r2Json(CodeSystem vs) throws Exception { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); IParser json = new JsonParser().setOutputStyle(OutputStyle.PRETTY); -// json.setSuppressXhtml("Snipped for Brevity"); + // json.setSuppressXhtml("Snipped for Brevity"); json.compose(bytes, vs); return new String(bytes.toByteArray()); } @@ -3556,8 +3562,8 @@ private void cloneToXhtml(String src, String dst, String name, String descriptio DocumentBuilder builder = factory.newDocumentBuilder(); Document xdoc = builder.parse(new CSFileInputStream(new CSFile(src))); -// XhtmlGenerator xhtml = new XhtmlGenerator(null); -// xhtml.generate(xdoc, new CSFile(dst), name, description, level, adorn); + // XhtmlGenerator xhtml = new XhtmlGenerator(null); + // xhtml.generate(xdoc, new CSFile(dst), name, description, level, adorn); String n = new File(dst).getName(); n = n.substring(0, n.length()-9); @@ -3736,7 +3742,7 @@ public String mapOnThisPage(String mappings) { private static class TocSort implements Comparator { @Override - public int compare(String arg0, String arg1) { + public int compare(String arg0, String arg1) { String[] a0 = arg0.split("\\."); String[] a1 = arg1.split("\\."); for (int i = 0; i < Math.min(a0.length, a1.length); i++) { @@ -3763,7 +3769,7 @@ public TocItem(TocEntry entry, Row row, int depth) { private String genIgToc(ImplementationGuideDefn ig) throws Exception { - HierarchicalTableGenerator gen = new HierarchicalTableGenerator(folders.dstDir, false, true); + HierarchicalTableGenerator gen = new HierarchicalTableGenerator(new RenderingI18nContext(), folders.dstDir, false, true); return new XhtmlComposer(XhtmlComposer.HTML).compose(gen.generate(ig.genToc(gen, "toc"), "../", 0, null)); } @@ -3773,7 +3779,7 @@ private String generateToc() throws Exception { entries.addAll(toc.keySet()); Collections.sort(entries, new SectionSorter()); Set pages = new HashSet(); - HierarchicalTableGenerator gen = new HierarchicalTableGenerator(folders.dstDir, false, true); + HierarchicalTableGenerator gen = new HierarchicalTableGenerator(new RenderingI18nContext(), folders.dstDir, false, true); TableModel model = gen.new TableModel("toc", true); model.getTitles().add(gen.new Title(null, model.getDocoRef(), "Table of Contents", "Table of Contents", null, 0)); Deque stack = new ArrayDeque(); @@ -3801,25 +3807,25 @@ else if (td.startsWith(stack.getFirst().entry.getText())) } Cell cell = gen.new Cell(null, t.getLink(), nd+" "+td, t.getText()+" ", null); row.getCells().add(cell); -// if (np != null) { -// cell.addPiece(gen.new Piece(null, " ", null)); -// cell.addPiece(gen.new Piece("versions.html#std-process", "basic".equals(np) ? "(Normative)" : "(Normative / "+Utilities.capitalize(np)+")", null).addStyle("color: #008000")); -// if (np.equals("infrastructure")) -// row.setIcon("icon_page_n_i.gif", null); -// else if (np.equals("conformance")) -// row.setIcon("icon_page_n_c.gif", null); -// else if (np.equals("patient")) -// row.setIcon("icon_page_n_p.gif", null); -// else if (np.equals("observation")) -// row.setIcon("icon_page_n_o.gif", null); -// else -// row.setIcon("icon_page_n.gif", null); -// } else { - cell.addPiece(gen.new Piece(null, " ", null)); - if (t.getStatus() != null) { - cell.addPiece(gen.new Piece("versions.html#std-process", "("+t.getStatus().toCode()+")", null).addStyle("padding: 3px; border: 1px lightgrey solid; color: #000000; background-color: "+t.getStatus().getColor())); - } -// } + // if (np != null) { + // cell.addPiece(gen.new Piece(null, " ", null)); + // cell.addPiece(gen.new Piece("versions.html#std-process", "basic".equals(np) ? "(Normative)" : "(Normative / "+Utilities.capitalize(np)+")", null).addStyle("color: #008000")); + // if (np.equals("infrastructure")) + // row.setIcon("icon_page_n_i.gif", null); + // else if (np.equals("conformance")) + // row.setIcon("icon_page_n_c.gif", null); + // else if (np.equals("patient")) + // row.setIcon("icon_page_n_p.gif", null); + // else if (np.equals("observation")) + // row.setIcon("icon_page_n_o.gif", null); + // else + // row.setIcon("icon_page_n.gif", null); + // } else { + cell.addPiece(gen.new Piece(null, " ", null)); + if (t.getStatus() != null) { + cell.addPiece(gen.new Piece("versions.html#std-process", "("+t.getStatus().toCode()+")", null).addStyle("padding: 3px; border: 1px lightgrey solid; color: #000000; background-color: "+t.getStatus().getColor())); + } + // } if (stack.isEmpty()) model.getRows().add(row); else @@ -3918,7 +3924,7 @@ private String generateValueSetUsage(ValueSet vs, String prefix, boolean addTitl scanForProfileUsage(items, vs, r, prefix); } for (ElementDefn e : definitions.getInfrastructure().values()) { - scanForUsage(items, vs, e, definitions.getSrcFile(e.getName())+"-definitions.html", prefix, "Datatype"); + scanForUsage(items, vs, e, definitions.getSrcFile(e.getName())+"-definitions.html", prefix, "Datatype"); } for (ElementDefn e : definitions.getTypes().values()) { if (!definitions.dataTypeIsSharedInfo(e.getName())) { @@ -3947,14 +3953,14 @@ private String generateValueSetUsage(ValueSet vs, String prefix, boolean addTitl } } } -// for (ConceptSetComponent t : vsi.getCompose().getInclude()) { -// if (vs.hasCodeSystem() && t.getSystem().equals(vs.getCodeSystem().getSystem())) -// b.append("
    • Included in Valueset "+Utilities.escapeXml(vs.getName())+"
    • \r\n"); -// } -// for (ConceptSetComponent t : vsi.getCompose().getExclude()) { -// if (vs.hasCodeSystem() && t.getSystem().equals(vs.getCodeSystem().getSystem())) -// b.append("
    • Excluded in Valueset "+Utilities.escapeXml(vs.getName())+"
    • \r\n"); -// } + // for (ConceptSetComponent t : vsi.getCompose().getInclude()) { + // if (vs.hasCodeSystem() && t.getSystem().equals(vs.getCodeSystem().getSystem())) + // b.append("
    • Included in Valueset "+Utilities.escapeXml(vs.getName())+"
    • \r\n"); + // } + // for (ConceptSetComponent t : vsi.getCompose().getExclude()) { + // if (vs.hasCodeSystem() && t.getSystem().equals(vs.getCodeSystem().getSystem())) + // b.append("
    • Excluded in Valueset "+Utilities.escapeXml(vs.getName())+"
    • \r\n"); + // } } } if (ini.getPropertyNames(vs.getUrl()) != null) { @@ -4062,17 +4068,17 @@ private String getBSTypeDesc(ElementDefn ed, BindingSpecification cd, String pre private String generateCodeDefinition(String name) { throw new Error("fix this"); -// BindingSpecification cd = definitions.getBindingByURL("#"+name); -// return Utilities.escapeXml(cd.getDefinition()); + // BindingSpecification cd = definitions.getBindingByURL("#"+name); + // return Utilities.escapeXml(cd.getDefinition()); } private String generateValueSetDefinition(String name) { throw new Error("fix this"); -// BindingSpecification cd = definitions.getBindingByURL(name); -// if (cd == null) -// return definitions.getExtraValuesets().get(name).getDescription(); -// else -// return Utilities.escapeXml(cd.getDefinition()); + // BindingSpecification cd = definitions.getBindingByURL(name); + // if (cd == null) + // return definitions.getExtraValuesets().get(name).getDescription(); + // else + // return Utilities.escapeXml(cd.getDefinition()); } private void generateCode(BindingSpecification cd, StringBuilder s, boolean hasSource, boolean hasId, boolean hasComment, boolean hasDefinition, boolean hasParent, int level, DefinedCode c) { @@ -4163,7 +4169,7 @@ private String genResourceConstraints(ResourceDefn res, String prefix) throws Ex } if (b.length() > 0) return " \r\n

      Constraints

      "+ - ""+b+"
      UniqueKeyLevelLocationDescriptionExpression

      "; + ""+b+"
      UniqueKeyLevelLocationDescriptionExpression

    "; else return ""; } @@ -4190,15 +4196,15 @@ public class ConstraintsSorter implements Comparator { @Override public int compare(String s0, String s1) { - String[] parts0 = s0.split("\\-"); - String[] parts1 = s1.split("\\-"); - if (parts0.length != 2 || parts1.length != 2) - return s0.compareTo(s1); - int comp = parts0[0].compareTo(parts1[0]); - if (comp == 0 && Utilities.isInteger(parts0[1]) && Utilities.isInteger(parts1[1])) - return new Integer(parts0[1]).compareTo(new Integer(parts1[1])); - else - return parts0[1].compareTo(parts1[1]); + String[] parts0 = s0.split("\\-"); + String[] parts1 = s1.split("\\-"); + if (parts0.length != 2 || parts1.length != 2) + return s0.compareTo(s1); + int comp = parts0[0].compareTo(parts1[0]); + if (comp == 0 && Utilities.isInteger(parts0[1]) && Utilities.isInteger(parts1[1])) + return new Integer(parts0[1]).compareTo(new Integer(parts1[1])); + else + return parts0[1].compareTo(parts1[1]); } } @@ -4288,15 +4294,15 @@ private void generateConstraintsTable(String path, ProfiledType pt, Map 0) -// s.append("/"); -// s.append("f:" + p); -// } -// return s.toString(); - return path; + // String[] parts = path.split("\\."); + // StringBuilder s = new StringBuilder(); + // for (String p : parts) { + // if (s.length() > 0) + // s.append("/"); + // s.append("f:" + p); + // } + // return s.toString(); + return path; } private String pageHeader(String n) { @@ -4419,7 +4425,7 @@ private String narrHeader(String mode) { b.append("\r\n"); return b.toString(); } - + private String profilesHeader(String mode) { StringBuilder b = new StringBuilder(); b.append("
      "); @@ -4452,47 +4458,47 @@ private String refHeader(String mode) { } -// private String resourcesHeader(String n, String mode) { -// if (n.contains("-")) -// n = n.substring(0, n.indexOf('-')); -// StringBuilder b = new StringBuilder(); -// b.append("
      "); -// b.append("
      •  
      • "); -// if (mode == null || mode.equals("content")) -// b.append("
      • Content
      • "); -// else -// b.append("
      • Content
      • "); -// if ("definitions".equals(mode)) -// b.append("
      • Detailed Descriptions
      • "); -// else -// b.append("
      • Detailed Descriptions
      • "); -// b.append("
      •  
      • "); -// b.append("
      \r\n"); -// return b.toString(); -// } - -// private String formatsHeader(String n, String mode) { -// if (n.contains("-")) -// n = n.substring(0, n.indexOf('-')); -// StringBuilder b = new StringBuilder(); -// b.append("
      "); -// b.append("
      •  
      • "); -// if (mode == null || mode.equals("content")) -// b.append("
      • Content
      • "); -// else -// b.append("
      • Content
      • "); -// if ("examples".equals(mode)) -// b.append("
      • Examples
      • "); -// else -// b.append("
      • Examples
      • "); -// if ("definitions".equals(mode)) -// b.append("
      • Detailed Descriptions
      • "); -// else -// b.append("
      • Detailed Descriptions
      • "); -// b.append("
      •  
      • "); -// b.append("
      \r\n"); -// return b.toString(); -// } + // private String resourcesHeader(String n, String mode) { + // if (n.contains("-")) + // n = n.substring(0, n.indexOf('-')); + // StringBuilder b = new StringBuilder(); + // b.append("
      "); + // b.append("
      •  
      • "); + // if (mode == null || mode.equals("content")) + // b.append("
      • Content
      • "); + // else + // b.append("
      • Content
      • "); + // if ("definitions".equals(mode)) + // b.append("
      • Detailed Descriptions
      • "); + // else + // b.append("
      • Detailed Descriptions
      • "); + // b.append("
      •  
      • "); + // b.append("
      \r\n"); + // return b.toString(); + // } + + // private String formatsHeader(String n, String mode) { + // if (n.contains("-")) + // n = n.substring(0, n.indexOf('-')); + // StringBuilder b = new StringBuilder(); + // b.append("
      "); + // b.append("
      •  
      • "); + // if (mode == null || mode.equals("content")) + // b.append("
      • Content
      • "); + // else + // b.append("
      • Content
      • "); + // if ("examples".equals(mode)) + // b.append("
      • Examples
      • "); + // else + // b.append("
      • Examples
      • "); + // if ("definitions".equals(mode)) + // b.append("
      • Detailed Descriptions
      • "); + // else + // b.append("
      • Detailed Descriptions
      • "); + // b.append("
      •  
      • "); + // b.append("
      \r\n"); + // return b.toString(); + // } private String profileHeader(String n, String mode, boolean hasExamples) { StringBuilder b = new StringBuilder(); @@ -4507,8 +4513,8 @@ private String profileHeader(String n, String mode, boolean hasExamples) { b.append(makeHeaderTab("Examples", n+"-examples.html", mode==null || "examples".equals(mode))); b.append(makeHeaderTab("Detailed Descriptions", n+"-definitions.html", "definitions".equals(mode))); b.append(makeHeaderTab("Mappings", n+"-mappings.html", "mappings".equals(mode))); -// if (!isDict && !n.equals("elementdefinition-de")) // todo: do this properly -// b.append(makeHeaderTab("HTML Form", n+"-questionnaire.html", "questionnaire".equals(mode))); + // if (!isDict && !n.equals("elementdefinition-de")) // todo: do this properly + // b.append(makeHeaderTab("HTML Form", n+"-questionnaire.html", "questionnaire".equals(mode))); b.append(makeHeaderTab("XML", n+".profile.xml.html", "xml".equals(mode))); b.append(makeHeaderTab("JSON", n+".profile.json.html", "json".equals(mode))); @@ -4624,24 +4630,24 @@ private String cmpHeader(String n, String mode) { return b.toString(); } -// private String atomHeader(String n, String mode) { -// if (n.contains("-")) -// n = n.substring(0, n.indexOf('-')); -// StringBuilder b = new StringBuilder(); -// b.append("
      "); -// b.append("
      •  
      • "); -// if (mode == null || mode.equals("content")) -// b.append("
      • Content
      • "); -// else -// b.append("
      • Content
      • "); -// if ("examples".equals(mode)) -// b.append("
      • Examples
      • "); -// else -// b.append("
      • Examples
      • "); -// b.append("
      •  
      • "); -// b.append("
      \r\n"); -// return b.toString(); -// } + // private String atomHeader(String n, String mode) { + // if (n.contains("-")) + // n = n.substring(0, n.indexOf('-')); + // StringBuilder b = new StringBuilder(); + // b.append("
      "); + // b.append("
      •  
      • "); + // if (mode == null || mode.equals("content")) + // b.append("
      • Content
      • "); + // else + // b.append("
      • Content
      • "); + // if ("examples".equals(mode)) + // b.append("
      • Examples
      • "); + // else + // b.append("
      • Examples
      • "); + // b.append("
      •  
      • "); + // b.append("
      \r\n"); + // return b.toString(); + // } private String codelist(CodeSystem cs, String mode, boolean links, boolean heading, String source) throws Exception { if (cs == null) @@ -4732,8 +4738,8 @@ private String resHeader(String n, String title, String mode) throws Exception { b.append(makeHeaderTab("Search Params", n+"-search.html", "search".equals(mode))); b.append(makeHeaderTab("Profiles", n+"-profiles.html", "profiles".equals(mode))); b.append(makeHeaderTab("Extensions", extensionsLocation+"extensions-"+ ("Resource".equals(res.getName()) ? "resource" : res.getName())+".html", "extensions".equals(mode))); -// if (!isAbstract) -// b.append(makeHeaderTab("HTML Form", n+"-questionnaire.html", "questionnaire".equals(mode))); + // if (!isAbstract) + // b.append(makeHeaderTab("HTML Form", n+"-questionnaire.html", "questionnaire".equals(mode))); b.append(makeHeaderTab("R4 Conversions", extensionsLocation+"conversions-"+ ("Resource".equals(res.getName()) ? "resource" : res.getName())+".html", "conversion".equals(mode))); b.append("
    \r\n"); @@ -4789,15 +4795,15 @@ private String genCodeSystemsTable() throws Exception { names.addAll(definitions.getCodeSystems().keys()); -// for (String n : definitions.getBindings().keySet()) { -// if ((definitions.getBindingByName(n).getBinding() == Binding.CodeList && !definitions.getBindingByName(n).getVSSources().contains("")) || -// (definitions.getBindingByName(n).getBinding() == Binding.Special)) -// names.add(definitions.getBindingByName(n).getReference().substring(1)); -// } -// -//// not this one Logical Interactions (RESTful framework) http://hl7.org/fhir/rest-operations 2.16.840.1.113883.6.308 -// s.append(" http://hl7.org/fhir/"+cd.getReference().substring(1)+""+Utilities.escapeXml(cd.getDefinition())+"\r\n"); -// + // for (String n : definitions.getBindings().keySet()) { + // if ((definitions.getBindingByName(n).getBinding() == Binding.CodeList && !definitions.getBindingByName(n).getVSSources().contains("")) || + // (definitions.getBindingByName(n).getBinding() == Binding.Special)) + // names.add(definitions.getBindingByName(n).getReference().substring(1)); + // } + // + //// not this one Logical Interactions (RESTful framework) http://hl7.org/fhir/rest-operations 2.16.840.1.113883.6.308 + // s.append(" http://hl7.org/fhir/"+cd.getReference().substring(1)+""+Utilities.escapeXml(cd.getDefinition())+"\r\n"); + // Collections.sort(names); for (String n : names) { if (n.startsWith("http://hl7.org") && !n.startsWith("http://terminology.hl7.org/CodeSystem/v2") && !n.startsWith("http://terminology.hl7.org/CodeSystem/v3")) { @@ -4853,7 +4859,7 @@ private String genOidsList() { } return b.toString(); } - + private String genConceptMapsTable() throws Exception { StringBuilder s = new StringBuilder(); s.append("\r\n"); @@ -4863,15 +4869,15 @@ private String genConceptMapsTable() throws Exception { Collections.sort(sorts); Set urls = new HashSet<>(); - + for (String sn : sorts) { ConceptMap ae = conceptMaps.get(sn); if (!urls.contains(ae.getUrl())) { urls.add(ae.getUrl()); ConceptMap cm = ae; s.append(" ") - .append("") - .append("\r\n"); + .append("") + .append("\r\n"); } } s.append("
    ").append(cm.getId()).append("").append(cm.getName()).append("").append(describeValueSetByRef(cm.getSourceScope())).append("").append(describeValueSetByRef(cm.getTargetScope())).append("
    ").append(describeValueSetByRef(cm.getSourceScope())).append("").append(describeValueSetByRef(cm.getTargetScope())).append("
    \r\n"); @@ -5010,7 +5016,7 @@ private String getTail(String sn) { if (!sn.contains("/")) { System.out.print(sn); } - + return sn.substring(getNamespace(sn).length()+1); } @@ -5132,18 +5138,18 @@ String processPageIncludesForPrinting(String file, String src, Resource resource boolean even = false; List tabs = new ArrayList(); Map resDesc = new HashMap<>(); - + src = processTypeLinks(src); while (src.contains("<%") || src.contains("[%")) - { - int i1 = src.indexOf("<%"); - int i2 = src.indexOf("%>"); - if (i1 == -1) { - i1 = src.indexOf("[%"); - i2 = src.indexOf("%]"); - } + { + int i1 = src.indexOf("<%"); + int i2 = src.indexOf("%>"); + if (i1 == -1) { + i1 = src.indexOf("[%"); + i2 = src.indexOf("%]"); + } String s1 = src.substring(0, i1); String s2 = src.substring(i1 + 2, i2).trim(); @@ -5219,17 +5225,17 @@ else if (com[0].equals("file")) { } } else if (com[0].equals("conceptmaplistvs")) { throw new Error("Fix this"); -// BindingSpecification bs = definitions.getBindingByName(Utilities.fileTitle(file)); -// String ref; -// if (bs == null) { -// ref = "http://hl7.org/fhir/ValueSet/"+Utilities.fileTitle(file); -// } else { -// ref = bs.getReference(); -// if (ref.startsWith("valueset-")) -// ref = ref.substring(9); -// ref = "http://hl7.org/fhir/ValueSet/"+ref; -// } -// src = s1 + conceptmaplist(ref, com[1]) + s3; + // BindingSpecification bs = definitions.getBindingByName(Utilities.fileTitle(file)); + // String ref; + // if (bs == null) { + // ref = "http://hl7.org/fhir/ValueSet/"+Utilities.fileTitle(file); + // } else { + // ref = bs.getReference(); + // if (ref.startsWith("valueset-")) + // ref = ref.substring(9); + // ref = "http://hl7.org/fhir/ValueSet/"+ref; + // } + // src = s1 + conceptmaplist(ref, com[1]) + s3; } else if (com[0].equals("dtmappings")) src = s1 + genDataTypeMappings(com[1]) + s3; else if (com[0].equals("dtusage")) @@ -5278,12 +5284,12 @@ else if (com[0].equals("resourcecodes")) src = s1 + genResCodes() + s3; else if (com[0].equals("datatypecodes")) src = s1 + genDTCodes() + s3; -// else if (com[0].equals("bindingtable-codelists")) -// src = s1 + genBindingTable(true) + s3; -// else if (com[0].equals("bindingtable")) -// src = s1 + genBindingsTable() + s3; -// else if (com[0].equals("bindingtable-others")) -// src = s1 + genBindingTable(false) + s3; + // else if (com[0].equals("bindingtable-codelists")) + // src = s1 + genBindingTable(true) + s3; + // else if (com[0].equals("bindingtable")) + // src = s1 + genBindingsTable() + s3; + // else if (com[0].equals("bindingtable-others")) + // src = s1 + genBindingTable(false) + s3; else if (com[0].equals("codeslist")) src = s1 + genCodeSystemsTable() + s3; else if (com[0].equals("valuesetslist")) @@ -5322,14 +5328,14 @@ else if (com[0].equals("vsusage")) src = s1 + generateValueSetUsage((ValueSet) resource, genlevel(0), true) + s3; else if (com[0].equals("csusage")) src = s1 + generateCSUsage((CodeSystem) resource, genlevel(0)) + s3; -// else if (com[0].equals("vssummary")) -// src = s1 + "todo" + s3; + // else if (com[0].equals("vssummary")) + // src = s1 + "todo" + s3; else if (com[0].equals("piperesources")) src = s1+pipeResources()+s3; else if (com[0].equals("pub-name")) src = s1 + publicationType + s3; -// else if (com[0].equals("vsexpansion")) -// src = s1 + expandValueSet(Utilities.fileTitle(file), resource == null ? null : (ValueSet) resource) + s3; + // else if (com[0].equals("vsexpansion")) + // src = s1 + expandValueSet(Utilities.fileTitle(file), resource == null ? null : (ValueSet) resource) + s3; else if (com[0].equals("vsexpansionig")) src = s1 + expandValueSetIG((ValueSet) resource, true) + s3; else if (com[0].equals("pub-notice")) @@ -5402,11 +5408,11 @@ private String fixUrlReference(String n) { return n; } - private String expandValueSetIG(ValueSet vs, boolean heirarchy) throws Exception { + private String expandValueSetIG(ValueSet vs, boolean hierarchy) throws Exception { if (!hasDynamicContent(vs)) return ""; try { - ValueSetExpansionOutcome result = workerContext.expandVS(vs, true, heirarchy); + ValueSetExpansionOutcome result = workerContext.expandVS(vs, true, hierarchy); if (result.getError() != null) return "
    \r\n"+VS_INC_START+""+processExpansionError(result.getError())+VS_INC_END; ValueSet exp = result.getValueset(); @@ -5415,8 +5421,8 @@ private String expandValueSetIG(ValueSet vs, boolean heirarchy) throws Exception exp.setCompose(null); exp.setText(null); exp.setDescription("Value Set Contents (Expansion) for "+vs.present()+" at "+Config.DATE_FORMAT().format(new Date())); - RenderingContext lrc = rc.copy(); - RendererFactory.factory(exp, lrc).render(exp); + RenderingContext lrc = rc.copy(false); + RendererFactory.factory(exp, lrc).renderResource(ResourceWrapper.forResource(lrc.getContextUtilities(), exp)); return "
    \r\n"+VS_INC_START+""+new XhtmlComposer(XhtmlComposer.HTML).compose(exp.getText().getDiv())+VS_INC_END; } catch (Exception e) { return "
    \r\n"+VS_INC_START+""+processExpansionError(e.getMessage())+VS_INC_END; @@ -5460,10 +5466,10 @@ private String csContent(String fileTitle, CodeSystem cs, String prefix) throws if (langs.size() > 0) return renderCodeSystemWithLangs(langs, cs, ""); else { - RenderingContext lrc = rc.copy().setLang("*").setCopyButton(true); + RenderingContext lrc = rc.copy(false).withLocale(null).setCopyButton(true); Narrative n = cs.getText(); cs.setText(null); - RendererFactory.factory(cs, lrc).render(cs); + RendererFactory.factory(cs, lrc).renderResource(ResourceWrapper.forResource(lrc.getContextUtilities(), cs)); String x = new XhtmlComposer(XhtmlComposer.HTML).compose(cs.getText().getDiv()); cs.setText(n); return x; @@ -5477,13 +5483,13 @@ private String vsCLD(String fileTitle, ValueSet vs, String prefix) throws Except vs1.setExpansion(null); vs1.setText(null); ImplementationGuideDefn ig = (ImplementationGuideDefn) vs.getUserData(ToolResourceUtilities.NAME_RES_IG); - RenderingContext lrc = rc.copy().setLocalPrefix(prefix); - RendererFactory.factory(vs1, lrc).render(vs1); + RenderingContext lrc = rc.copy(false).setLocalPrefix(prefix); + RendererFactory.factory(vs1, lrc).renderResource(ResourceWrapper.forResource(lrc.getContextUtilities(), vs1)); return "
    \r\n"+VS_INC_START+""+new XhtmlComposer(XhtmlComposer.HTML).compose(vs1.getText().getDiv())+VS_INC_END; } - public ValueSet expandValueSet(ValueSet vs, boolean heirarchy) throws Exception { - ValueSetExpansionOutcome result = workerContext.expandVS(vs, true, heirarchy); + public ValueSet expandValueSet(ValueSet vs, boolean hierarchy) throws Exception { + ValueSetExpansionOutcome result = workerContext.expandVS(vs, true, hierarchy); if (result.getError() != null) return null; else @@ -5523,13 +5529,13 @@ private boolean hasDynamicContent(ValueSet vs) { private String generateVSDesc(String fileTitle) throws Exception { throw new Error("Fix this"); -// BindingSpecification cd = definitions.getBindingByName(fileTitle); -// if (cd == null) -// return new XhtmlComposer(XhtmlComposer.HTML).compose(definitions.getExtraValuesets().get(fileTitle).getText().getDiv()); -// else if (cd.getReferredValueSet().hasText() && cd.getReferredValueSet().getText().hasDiv()) -// return new XhtmlComposer(XhtmlComposer.HTML).compose(cd.getReferredValueSet().getText().getDiv()); -// else -// return cd.getReferredValueSet().getDescription(); + // BindingSpecification cd = definitions.getBindingByName(fileTitle); + // if (cd == null) + // return new XhtmlComposer(XhtmlComposer.HTML).compose(definitions.getExtraValuesets().get(fileTitle).getText().getDiv()); + // else if (cd.getReferredValueSet().hasText() && cd.getReferredValueSet().getText().hasDiv()) + // return new XhtmlComposer(XhtmlComposer.HTML).compose(cd.getReferredValueSet().getText().getDiv()); + // else + // return cd.getReferredValueSet().getDescription(); } String processPageIncludesForBook(String file, String src, String type, Resource resource, ImplementationGuideDefn ig, WorkGroup wg) throws Exception { @@ -5543,13 +5549,13 @@ String processPageIncludesForBook(String file, String src, String type, Resource src = processTypeLinks(src); while (src.contains("<%") || src.contains("[%")) - { - int i1 = src.indexOf("<%"); - int i2 = i1 == -1 ? -1 : src.substring(i1).indexOf("%>")+i1; - if (i1 == -1) { - i1 = src.indexOf("[%"); - i2 = i1 == -1 ? -1 : src.substring(i1).indexOf("%]")+i1; - } + { + int i1 = src.indexOf("<%"); + int i2 = i1 == -1 ? -1 : src.substring(i1).indexOf("%>")+i1; + if (i1 == -1) { + i1 = src.indexOf("[%"); + i2 = i1 == -1 ? -1 : src.substring(i1).indexOf("%]")+i1; + } String s1 = src.substring(0, i1); String s2 = src.substring(i1 + 2, i2).trim(); @@ -5605,7 +5611,7 @@ else if (com[0].equals("sct-vs-list")) else if (com[0].equals("sct-concept-list")) src = s1+getSnomedCTConceptList()+s3; else if (com[0].equals("circular-references")) - src = s1+buildCircularReferenceList(com[1].equals("null") ? null : Boolean.valueOf(com[1]))+s3; + src = s1+buildCircularReferenceList(com[1].equals("null") ? null : Boolean.valueOf(com[1]))+s3; else if (com[0].equals("dtusage")) src = s1 + genDataTypeUsage(com[1]) + s3; else if (com[0].equals("w5")) @@ -5623,9 +5629,9 @@ else if (com[0].equals("vs-warning")) else if (com[0].equals("res-status-special")) src = s1 + vsSpecialStatus((DomainResource) resource) + s3; else if (com[0].equals("maponthispage")) - src = s1+s3; + src = s1+s3; else if (com[0].equals("onthispage")) - src = s1+s3; + src = s1+s3; else if (com[0].equals("conceptmaplistvs")) { ValueSet vs = (ValueSet) resource; String ref; @@ -5685,11 +5691,11 @@ else if (com[0].equals("settitle")) { } else if (com[0].equals("search-footer")) { src = s1+searchFooter(level)+s3; } else if (com[0].equals("search-header")) { - src = s1+searchHeader(level)+s3; + src = s1+searchHeader(level)+s3; } else if (com[0].equals("toc")) { src = s1 + generateToc() + s3; } else if (com[0].equals("igregistries")) { - src = s1+igRegistryList(com[1], com[2])+s3; + src = s1+igRegistryList(com[1], com[2])+s3; } else if (com[0].equals("ig.registry")) { src = s1+buildIgRegistry(ig, com[1])+s3; } else if (com[0].equals("dtprofiles")) { @@ -5703,10 +5709,10 @@ else if (com[0].equals("settitle")) { } else if (com[0].equals("profile-diff")) { ConstraintStructure p = definitions.findProfile(com[1]); src = s1 + generateProfileStructureTable(p, true, com[1]+".html", com[1], genlevel(level)) + s3; -// } else if (com[0].equals("example")) { -// String[] parts = com[1].split("\\/"); -// Example e = findExample(parts[0], parts[1]); -// src = s1+genExample(e, com.length > 2 ? Integer.parseInt(com[2]) : 0, genlevel(level))+s3; + // } else if (com[0].equals("example")) { + // String[] parts = com[1].split("\\/"); + // Example e = findExample(parts[0], parts[1]); + // src = s1+genExample(e, com.length > 2 ? Integer.parseInt(com[2]) : 0, genlevel(level))+s3; } else if (com[0].equals("extension-diff")) { StructureDefinition ed = workerContext.fetchResource(StructureDefinition.class, com[1]); src = s1+generateExtensionTable(ed, "extension-"+com[1], "false", genlevel(level))+s3; @@ -5744,7 +5750,7 @@ else if (com[0].equals("settitle")) { } else if (com[0].equals("ig")) { src = s1+igLink(com[1])+s3; } else if (com[0].equals("dtxheader")) { - src = s1+dtxHeader(com.length > 1 ? com[1] : null, com.length > 2 ? com[2] : null)+s3; + src = s1+dtxHeader(com.length > 1 ? com[1] : null, com.length > 2 ? com[2] : null)+s3; } else if (com[0].equals("diff-analysis")) { if ("*".equals(com[1])) { updateDiffEngineDefinitions(); @@ -5797,8 +5803,8 @@ else if (com[0].equals("enteredInErrorTable")) src = s1+enteredInErrorTable()+s3; else if (com[0].equals("datatypecodes")) src = s1 + genDTCodes() + s3; -// else if (com[0].equals("bindingtable-codelists")) -// src = s1 + genBindingTable(true) + s3; + // else if (com[0].equals("bindingtable-codelists")) + // src = s1 + genBindingTable(true) + s3; else if (com[0].equals("codeslist")) src = s1 + genCodeSystemsTable() + s3; else if (com[0].equals("valuesetslist")) @@ -5809,10 +5815,10 @@ else if (com[0].equals("namespacelist")) src = s1 + s3; else if (com[0].equals("conceptmapslist")) src = s1 + genConceptMapsTable() + s3; -// else if (com[0].equals("bindingtable")) -// src = s1 + genBindingsTable() + s3; -// else if (com[0].equals("bindingtable-others")) -// src = s1 + genBindingTable(false) + s3; + // else if (com[0].equals("bindingtable")) + // src = s1 + genBindingsTable() + s3; + // else if (com[0].equals("bindingtable-others")) + // src = s1 + genBindingTable(false) + s3; else if (com[0].equals("vsxref")) src = s1 + xreferencesForFhir(name) + s3; else if (com[0].equals("resimplall")) @@ -5871,8 +5877,8 @@ else if (com[0].equals("csnamed")) { CanonicalResource cr = (CanonicalResource) resource; src = s1 + cr.getVersion() + s3; } else if (com[0].equals("csver")) { - CanonicalResource cr = (CanonicalResource) resource; - src = s1 + cr.getVersion() + s3; + CanonicalResource cr = (CanonicalResource) resource; + src = s1 + cr.getVersion() + s3; } else if (com[0].equals("vsref")) { src = s1 + Utilities.fileTitle((String) resource.getUserData("filename")) + s3; } else if (com[0].equals("vsdesc")) @@ -5885,8 +5891,8 @@ else if (com[0].equals("csusage")) src = s1 + generateCSUsage((CodeSystem) resource, genlevel(level)) + s3; else if (com[0].equals("mappings-table")) src = s1+genMappingsTable()+s3; -// else if (com[0].equals("vssummary")) -// src = s1 + "todo" + s3; + // else if (com[0].equals("vssummary")) + // src = s1 + "todo" + s3; else if (com[0].equals("compartmentlist")) src = s1 + compartmentlist() + s3; else if (com[0].equals("comp-title")) @@ -5938,8 +5944,8 @@ else if (com[0].equals("status-codes")) src = s1 + genStatusCodes() + s3; else if (com[0].equals("dictionary.name")) src = s1 + definitions.getDictionaries().get(name) + s3; -// else if (com[0].equals("dictionary.view")) -// src = s1 + ResourceUtilities.representDataElementCollection(this.workerContext, (Bundle) resource, true, "hspc-QuantitativeLab-dataelements") + s3; + // else if (com[0].equals("dictionary.view")) + // src = s1 + ResourceUtilities.representDataElementCollection(this.workerContext, (Bundle) resource, true, "hspc-QuantitativeLab-dataelements") + s3; else if (com[0].startsWith("!")) src = s1 + s3; else if (com[0].equals("identifierlist")) @@ -6025,7 +6031,7 @@ else if (com[0].equals("special-search-parameters")) { } else if (macros.containsKey(com[0])) { src = s1+macros.get(com[0])+s3; } else if (com[0].equals("extensions-location")) { - src = s1+extensionsLocation+s3; + src = s1+extensionsLocation+s3; } else throw new Exception("Instruction <%"+s2+"%> not understood parsing page "+file); } @@ -6439,7 +6445,7 @@ else if (com[0].equals("normative")) { else if (com[0].equals("pageheader")) src = s1+pageHeader(resource.getName())+s3; else if (com[0].equals("maponthispage")) - src = s1+mapOnThisPage(mappingsList)+s3; + src = s1+mapOnThisPage(mappingsList)+s3; else if (com[0].equals("newheader")) src = s1+TextFile.fileToString(folders.srcDir + "newheader.html")+s3; else if (com[0].equals("newheader1")) @@ -6529,9 +6535,9 @@ else if (com[0].equals("resource-table-all")) else if (com[0].equals("plural")) src = s1+Utilities.pluralizeMe(name)+s3; else if (com[0].equals("mappings")) - src = s1+mappings+s3; + src = s1+mappings+s3; else if (com[0].equals("mappingslist")) - src = s1+mappingsList+s3; + src = s1+mappingsList+s3; else if (com[0].equals("breadcrumb")) src = s1 + breadCrumbManager.make(name) + s3; else if (com[0].equals("ext-link")) @@ -6685,7 +6691,7 @@ private String genImplementationList(ResourceDefn logical) throws FHIRException } } } - + b.append(""); return b.toString(); } @@ -6784,7 +6790,7 @@ private String genLogicalMappings(ResourceDefn logical, String genlevel) throws if (unknownMappings) { // If need be, we can comment this out for the short term. getValidationErrors().add( - new ValidationMessage(Source.Publisher, IssueType.INFORMATIONAL, -1, -1, sd.getName(), "Resource contains differences from the "+logical.getName()+" pattern that have an 'Unknown' reason in the "+exceptionsFile+" file.", IssueSeverity.INFORMATION)); + new ValidationMessage(Source.Publisher, IssueType.INFORMATIONAL, -1, -1, sd.getName(), "Resource contains differences from the "+logical.getName()+" pattern that have an 'Unknown' reason in the "+exceptionsFile+" file.", IssueSeverity.INFORMATION)); } for (String logicalPath : unmappedLogicalElements.keySet()) { @@ -6880,7 +6886,7 @@ private String genLogicalAnalysis(ResourceDefn logical, String genlevel) throws throw e; } } -/* Map divergents = new HashMap(); + /* Map divergents = new HashMap(); NodeList divergentElements = exceptionsDoc.getElementsByTagName("divergentElement"); for (int i = 0; i < divergentElements.getLength(); i++) { org.w3c.dom.Element divergent = (org.w3c.dom.Element)divergentElements.item(i); @@ -6914,7 +6920,7 @@ private String genLogicalAnalysis(ResourceDefn logical, String genlevel) throws else return ""; } - + private void listAllElements(List elements, String path, ElementDefn logical) { for (ElementDefn c : logical.getElements()) { c.setPath(path+"."+c.getName()); @@ -6953,17 +6959,17 @@ TypeMappingStatus typeMismatch() { } boolean hasUnknown() { return (nameReason!=null && nameReason.equals(REASON_UNKNOWN)) - || (extraTypesReason!=null && extraTypesReason.equals(REASON_UNKNOWN)) - || (missingTypesReason!=null && missingTypesReason.equals(REASON_UNKNOWN)) - || (lowerCardReason!=null && lowerCardReason.equals(REASON_UNKNOWN)) - || (upperCardReason!=null && upperCardReason.equals(REASON_UNKNOWN)) - || (shortReason!=null && shortReason.equals(REASON_UNKNOWN)) - || (definitionReason!=null && definitionReason.equals(REASON_UNKNOWN)) - || (requirementsReason!=null && requirementsReason.equals(REASON_UNKNOWN)) - || (commentReason!=null && commentReason.equals(REASON_UNKNOWN)) - || (modifierReason!=null && modifierReason.equals(REASON_UNKNOWN)) - || (summaryReason!=null && summaryReason.equals(REASON_UNKNOWN)) - || (bindingReason!=null && bindingReason.equals(REASON_UNKNOWN)); + || (extraTypesReason!=null && extraTypesReason.equals(REASON_UNKNOWN)) + || (missingTypesReason!=null && missingTypesReason.equals(REASON_UNKNOWN)) + || (lowerCardReason!=null && lowerCardReason.equals(REASON_UNKNOWN)) + || (upperCardReason!=null && upperCardReason.equals(REASON_UNKNOWN)) + || (shortReason!=null && shortReason.equals(REASON_UNKNOWN)) + || (definitionReason!=null && definitionReason.equals(REASON_UNKNOWN)) + || (requirementsReason!=null && requirementsReason.equals(REASON_UNKNOWN)) + || (commentReason!=null && commentReason.equals(REASON_UNKNOWN)) + || (modifierReason!=null && modifierReason.equals(REASON_UNKNOWN)) + || (summaryReason!=null && summaryReason.equals(REASON_UNKNOWN)) + || (bindingReason!=null && bindingReason.equals(REASON_UNKNOWN)); } boolean cardinalityProblem() { return lowerCardReason!=null || upperCardReason!=null; @@ -6975,10 +6981,10 @@ boolean cardinalityProblem() { private final static String LOGICAL_MAPPING_EXTENSION_COLOR = "#ffffe6"; private final static String LOGICAL_MAPPING_MAPPED_COLOR = "#ffffff"; private final static String LOGICAL_MAPPING_NOTMAPPED_COLOR = "#f2f2f2"; - + private LogicalModelSupportInformation populateLogicalMappingColumn(StringBuilder b, String n, String page, ElementDefn e, boolean light, StructureDefinition sd, String rn, String code, String url, StringBuilder b2, IniFile ini, String iniPath, - org.w3c.dom.Element rootException, org.w3c.dom.Document newExceptionsDoc, Map divergents, Map doubleMaps, Map unmapped, - File exceptionsFile) throws Exception { + org.w3c.dom.Element rootException, org.w3c.dom.Document newExceptionsDoc, Map divergents, Map doubleMaps, Map unmapped, + File exceptionsFile) throws Exception { LogicalModelSupportInformation info = new LogicalModelSupportInformation(); List otherPatterns = new ArrayList(); @@ -7008,8 +7014,8 @@ private LogicalModelSupportInformation populateLogicalMappingColumn(StringBuilde inOtherPattern = true; } if (!inOtherPattern) - getValidationErrors().add( - new ValidationMessage(Source.Publisher, IssueType.NOTFOUND, -1, -1, ed.getPath(), code + " pattern mapping to path that doesn't exist in pattern - "+f, IssueSeverity.WARNING)); + getValidationErrors().add( + new ValidationMessage(Source.Publisher, IssueType.NOTFOUND, -1, -1, ed.getPath(), code + " pattern mapping to path that doesn't exist in pattern - "+f, IssueSeverity.WARNING)); } String cm = p.contains("{") ? p.substring(p.indexOf("{")) : null; if (cm != null) { @@ -7025,12 +7031,12 @@ private LogicalModelSupportInformation populateLogicalMappingColumn(StringBuilde if (newDivergent.hasChildNodes()) rootException.appendChild(newDivergent); elementMatch = true; - } + } } } } } - + boolean extensionMatch = false; for (StructureDefinition ext : workerContext.getExtensionDefinitions()) { boolean ok = false; @@ -7050,11 +7056,11 @@ private LogicalModelSupportInformation populateLogicalMappingColumn(StringBuilde checkExtMapping(info, light, e, ext, divergent, newDivergent, newExceptionsDoc, sd.getName()); extensionMatch = true; } - } } } } } + } if (elementMatch && extensionMatch) { addMappingIssue(e.getPath(), doubleMaps, "doubleMappedElement", rootException, newExceptionsDoc); @@ -7076,7 +7082,7 @@ else if (info.elementcount> 0) color = LOGICAL_MAPPING_MAPPED_COLOR; else color = LOGICAL_MAPPING_NOTMAPPED_COLOR; - + if (b != null) { StringBuilder ns = new StringBuilder(); for (String s : info.notes) { @@ -7107,7 +7113,7 @@ else if (info.elementcount> 0) for (String s : info.notes) { ns.append(s); } - + String tasks = ini == null ? null : ini.getStringProperty(iniPath, sd.getName()+".tasks"); String status = ini == null ? null : ini.getStringProperty(iniPath, sd.getName()+".status"); String notes = ini == null ? null : ini.getStringProperty(iniPath, sd.getName()+".notes"); @@ -7150,7 +7156,7 @@ else if (info.elementcount> 0) b2.append(""); if (!Utilities.noString(notes)) b2.append(Utilities.escapeXml(notes)); - + b2.append("\r\n"); } @@ -7210,13 +7216,13 @@ private void checkMapping(LogicalModelSupportInformation info, boolean light, El if (!info.notes.contains(s)) { info.notes.add(s); } -/* Grahame - not sure what this was doing + /* Grahame - not sure what this was doing if (cm != null && cm.startsWith("{map:")) info.typeMismatch = TypeMappingStatus.NEEDS_MAPPING; else info.typeMismatch = TypeMappingStatus.OK;*/ - } + } private String checkText(String logicalText, String resourceText, String issueName, org.w3c.dom.Element exception, org.w3c.dom.Element newException, org.w3c.dom.Document doc, String name, StringJoiner sj, String elementName, String resourceName) { String adjustLogical = replaceTitle(trimBracketedText(logicalText), resourceName).trim(); @@ -7281,7 +7287,7 @@ private String checkElements(org.w3c.dom.Element exception, org.w3c.dom.Element nameException.appendChild(doc.createComment(((Comment)n).getNodeValue())); } } else if (((patternValue == null && oldPattern.isEmpty()) || patternValue.equals(oldPattern)) - && ((resourceValue == null && oldResource.isEmpty()) || resourceValue.equals(oldResource))) { + && ((resourceValue == null && oldResource.isEmpty()) || resourceValue.equals(oldResource))) { // We've got a reason *and* the pattern and resource values match what's in the current patterns and resources reason = oldNameException.getAttribute("reason"); managed = true; @@ -7431,7 +7437,7 @@ private void checkType(ElementDefn logical, boolean light, ElementDefinition res } else { lTypes.add(lt); } -/* lTypes.add() + /* lTypes.add() if (!checkType(logical, rt, cm, resource)) { String m = "The type '"+rt.getWorkingCode()+"' is not legal according to the pattern ("+resource.typeSummary()+" vs "+logical.typeCode()+") "; s = Utilities.noString(s) ? m : s + ", "+m; @@ -7505,7 +7511,7 @@ private boolean canBeType(ConceptMap map, String name) { private ConceptMap parseConceptMapMapping(ElementDefn logical, ElementDefinition resource, String src) throws FHIRException { if (!src.startsWith("{map:")) return null; - + ConceptMap map = new ConceptMap(); KindlingUtilities.makeUniversal(map); @@ -7529,7 +7535,7 @@ private ConceptMap parseConceptMapMapping(ElementDefn logical, ElementDefinition } return map; } - + private void checkCardinality(ElementDefn logical, boolean light, ElementDefinition resource, LogicalModelSupportInformation info, org.w3c.dom.Element exception, org.w3c.dom.Element newException, org.w3c.dom.Document doc, StringJoiner sj) { if (!light || !(logical.getMinCardinality()==0 && resource.getMin()==1)) info.lowerCardReason = checkElements(exception, newException, true, doc, "lowerCardinality", logical.getMinCardinality().toString(), Integer.toString(resource.getMin()), "Minimum Cardinality differs", sj); @@ -7549,7 +7555,7 @@ private void checkBinding(ElementDefn logical, ElementDefinition resource, Logic info.bindingReason = checkElements(exception, newException, true, doc, "bindingExistence", Boolean.toString(logical.hasBinding()), Boolean.toString(resource.hasBinding()), "Only one element has bindings", sj); } else if (logical.getBinding().getStrength() != resource.getBinding().getStrength()) { if ((logical.getBinding().getStrength()== Enumerations.BindingStrength.PREFERRED || logical.getBinding().getStrength()==Enumerations.BindingStrength.EXAMPLE) - && (resource.getBinding().getStrength()==Enumerations.BindingStrength.PREFERRED || resource.getBinding().getStrength()==Enumerations.BindingStrength.EXAMPLE)) { + && (resource.getBinding().getStrength()==Enumerations.BindingStrength.PREFERRED || resource.getBinding().getStrength()==Enumerations.BindingStrength.EXAMPLE)) { // Do nothing - we don't care if there are different strangths for 'week' bindings } else { info.bindingReason = checkElements(exception, newException, true, doc, "bindingStrength", logical.getBinding().getStrength().toCode(), resource.getBinding().getStrength().toCode(), "Binding strengths differ", sj); @@ -7581,14 +7587,14 @@ private boolean hasLogicalMapping(StructureDefinition sd, ResourceDefn logical, if (aMap.equals(logical.getRoot().getName()) || aMap.startsWith(logical.getRoot().getName()+".")) { if (ed.getPath().contains(".") && !code.equals("w5")) { getValidationErrors().add( - new ValidationMessage(Source.Publisher, IssueType.INFORMATIONAL, -1, -1, ed.getPath(), "Mapping to " + code + " pattern found, when no mapping for that pattern defined on the resource base element", IssueSeverity.WARNING)); + new ValidationMessage(Source.Publisher, IssueType.INFORMATIONAL, -1, -1, ed.getPath(), "Mapping to " + code + " pattern found, when no mapping for that pattern defined on the resource base element", IssueSeverity.WARNING)); } - return true; + return true; + } + } } } - } - } } return false; } @@ -7646,7 +7652,7 @@ private String fmmBarColorStyle(ResourceDefn resource) { if (resource.getNormativePackage() != null || resource.getNormativeVersion() != null) return "colsn"; else { - return fmmBarColorStyle(resource.getStatus(), resource.getFmmLevel()); + return fmmBarColorStyle(resource.getStatus(), resource.getFmmLevel()); } } @@ -7671,7 +7677,7 @@ private String getR3r4transformNote(String name) throws IOException { String st = r4r5StatusForResource(name); return "

    See R4 <--> R5 Conversion Maps (status = "+st+")

    \r\n"; } else - return ""; + return ""; } private String getCompLinks(ResourceDefn resource, String param) { @@ -7748,7 +7754,7 @@ private String genOperationsSummary(List oplist, ResourceDefn resourc else b.append(""+op.getStandardsStatus().toDisplay()+""); } - + b.append("\r\n"); } b.append("\r\n"); @@ -7773,23 +7779,23 @@ private String genOperationsSummary(List oplist, ResourceDefn resourc } return b.toString(); } - + private String genOperation1(Operation op, String n, String id, boolean mixed, StandardsStatus resStatus, String prefix, String np) throws Exception { - + StringBuilder b = new StringBuilder(); genOperationInner1(n, id, mixed, resStatus, prefix, np, b, op, false); return b.toString(); } private String genOperation2(Operation op, String n, String id, boolean mixed, StandardsStatus resStatus, String prefix, String np) throws Exception { - + StringBuilder b = new StringBuilder(); genOperationInner2(n, id, mixed, resStatus, prefix, np, b, op, false); return b.toString(); } private String genOperations(List oplist, String n, String id, boolean mixed, StandardsStatus resStatus, String prefix, String np) throws Exception { - + StringBuilder b = new StringBuilder(); for (Operation op : oplist) { genOperationInner1(n, id, mixed, resStatus, prefix, np, b, op, true); @@ -7886,17 +7892,17 @@ public void genOperationInner2(String n, String id, boolean mixed, StandardsStat private String opStandardsStatusNotice(String n, StandardsStatus opStatus, StandardsStatus resStatus, String pack, String prefix) { if (resStatus == StandardsStatus.NORMATIVE && opStatus == StandardsStatus.TRIAL_USE) return "

    \r\n" + - "Normative Candidate Note: Though the resource is a candidate for normative for R4, this operation is not included. It's status will remain 'Trial Use' while more experience is gathered.\r\n" + - "

    \r\n"; + "Normative Candidate Note: Though the resource is a candidate for normative for R4, this operation is not included. It's status will remain 'Trial Use' while more experience is gathered.\r\n" + + "

    \r\n"; if (resStatus == StandardsStatus.NORMATIVE && opStatus == null) return ansiNote("This operation has", pack, ""); else return ""; -// return "

    \r\n" + -// "ANSI Note: This operation is normative content in the "+Utilities.capitalize(pack)+" Package.\r\n" + -// "

    \r\n" + -// ""; - } + // return "

    \r\n" + + // "ANSI Note: This operation is normative content in the "+Utilities.capitalize(pack)+" Package.\r\n" + + // "

    \r\n" + + // ""; + } private String checkWrap(String n) { if (n.equals("Resource")) @@ -7932,18 +7938,14 @@ private void renderExample(StringBuilder b, OperationExample ex, String type) th b.append("\r\n"); } - private void addExample(StringBuilder b, Example x) throws TransformerFactoryConfigurationError, TransformerConfigurationException, TransformerException { + private void addExample(StringBuilder b, Example x) throws TransformerFactoryConfigurationError, Exception { b.append(Utilities.escapeXml(" \r\n")); b.append(Utilities.escapeXml(" \r\n")); b.append(Utilities.escapeXml(" \r\n")); + ByteArrayOutputStream bo = new ByteArrayOutputStream(); - TransformerFactory transformerFactory = TransformerFactory.newInstance(); - Transformer transformer = transformerFactory.newTransformer(); - transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); - DOMSource source = new DOMSource(x.getXml()); - StringWriter writer = new StringWriter(); - transformer.transform(source, new StreamResult(writer)); - String[] lines = writer.getBuffer().toString().split("\\n"); + Manager.compose(getWorkerContext(), x.getElement(), bo, FhirFormat.XML, OutputStyle.PRETTY, "http://hl7.org/fhir"); + String[] lines = bo.toString(StandardCharsets.UTF_8).split("\\n"); for (String l : lines) { b.append(" "); if (l.contains("xmlns:xsi=")) { @@ -8185,7 +8187,7 @@ public void checkPatternReferences(List names, ReferenceTracker refs, St refs.link(RefType.PATTERN_IMPL, rn, definitions.getSrcFile(rn)+".html#"+rn, rn); } } - + public void checkReferences(String name, ReferenceTracker refs, String rn, ElementDefn r) throws FHIRException { usesReference(r, name, refs, rn); if (name.equals("CodeSystem") && Utilities.existsInList(rn, "ValueSet", "ConceptMap", "Coding") && !refs.hasLink(RefType.RESOURCE_REF, rn)) { @@ -8199,12 +8201,12 @@ private boolean followsPattern(ElementDefn e, List names, String url) { return true; return false; } - + private void usesReference(ElementDefn e, String name, ReferenceTracker refs, String rn) { if (usesReference(e.getTypes(), name)) - refs.link(RefType.RESOURCE_REF, rn, definitions.getSrcFile(rn)+".html#"+rn, rn, e.getPath()); + refs.link(RefType.RESOURCE_REF, rn, definitions.getSrcFile(rn)+".html#"+rn, rn, e.getPath()); for (ElementDefn c : e.getElements()) { - usesReference(c, name, refs, rn); + usesReference(c, name, refs, rn); } } @@ -8224,17 +8226,17 @@ private boolean usesReference(List types, String name) { private String prepWikiName(String name) { return Utilities.noString(name) ? "Index" : Utilities.capitalize(Utilities.fileTitle(name)); } - */ + */ private String getSearchParamTable(ResourceDefn resource, String searchAdditions) throws Exception { if (resource.getSearchParams().size() == 0) return "

    (No search parameters for this resource)

    "; else { StandardsStatus st = resource.getStatus(); - + StringBuilder b = new StringBuilder(); b.append("\r\n"); -// b.append("\r\n"); + // b.append("\r\n"); Map spmap = new HashMap<>(); for (String n : resource.getSearchParams().keySet()) { spmap.put(n, resource.getSearchParams().get(n).getResource()); @@ -8258,8 +8260,8 @@ private String getSearchParamTable(ResourceDefn resource, String searchAdditions b.append(""); b.append(""); b.append(""); @@ -8269,14 +8271,14 @@ private String getSearchParamTable(ResourceDefn resource, String searchAdditions // expression + usage + targets (+components) // base resources - -// b.append(""); -// -// String md = stripSimplePara(processMarkdown("SearchParameter.description", p.getDescription(), "")); -// -// b.append("\r\n"); + + // b.append(""); + // + // String md = stripSimplePara(processMarkdown("SearchParameter.description", p.getDescription(), "")); + // + // b.append("\r\n"); } b.append(searchAdditions); b.append("
    NameTypeDescriptionExpressionIn Common
    NameTypeDescriptionExpressionIn Common
    "); XhtmlNode div = new XhtmlNode(NodeType.Element, "div"); - RenderingContext lrc = rc.copy().setDefaultStandardsStatus(st); - RendererFactory.factory(pp, lrc).render(div, pp); + RenderingContext lrc = rc.copy(false).setDefaultStandardsStatus(st); + RendererFactory.factory(pp, lrc).buildNarrative(new RenderingStatus(), div, ResourceWrapper.forResource(lrc.getContextUtilities(), pp)); b.append(new XhtmlComposer(false).compose(div)); b.append("
    ").append(p.getCode()).append(sst).append("").append(p.getType()).append("") -// .append(md).append("").append(p.getType() == SearchType.composite ? getCompositeExpression(p) : Utilities.escapeXml(p.getExpression())).append(p.getType() == SearchType.reference ? p.getTargetTypesAsText() : "") -// .append("").append(presentOthers(p)).append("
    ").append(p.getCode()).append(sst).append("").append(p.getType()).append("") + // .append(md).append("").append(p.getType() == SearchType.composite ? getCompositeExpression(p) : Utilities.escapeXml(p.getExpression())).append(p.getType() == SearchType.reference ? p.getTargetTypesAsText() : "") + // .append("").append(presentOthers(p)).append("
    \r\n"); @@ -8288,8 +8290,8 @@ private String getSearch(ResourceDefn resource, String searchAdditions) throws E if (resource.getSearchParams().size() == 0) return "

    (No search parameters for this resource)

    "; else { - StandardsStatus st = resource.getStatus(); - + StandardsStatus st = resource.getStatus(); + StringBuilder b = new StringBuilder(); b.append("\r\n"); b.append("\r\n"); @@ -8313,13 +8315,13 @@ private void genSearchParams(ResourceDefn resource, StandardsStatus st, StringBu SearchParameterDefn p = resource.getSearchParams().get(name); String pp = presentPaths(p.getPaths()); String sst = (p.getStandardsStatus() == null || p.getStandardsStatus() == st) ? "" : makeStandardsStatusRef(p.getStandardsStatus()); - + String md = stripSimplePara(processMarkdown("SearchParameter.description", p.getDescription(), "")); - + b.append("\r\n"); + .append("\">").append(p.getCode()).append("").append(sst).append("\r\n"); } } @@ -8395,7 +8397,7 @@ private void genAbstractSearchParams(ResourceDefn resource, StringBuilder b) { for (String name : names) { SearchParameterDefn p = resource.getSearchParams().get(name); b.append("\r\n"); + .append("\r\n"); } } @@ -8418,7 +8420,7 @@ private String getSearch(Profile pack) { if (t.getName().equals(name)) p = t; b.append("\r\n"); + .append("\r\n"); } b.append("
    NameTypeDescriptionExpressionIn Common
    ").append(p.getCode()).append("").append(sst).append("").append(p.getType()).append("") - .append(md).append("").append(p.getType() == SearchType.composite ? getCompositeExpression(p) : Utilities.escapeXml(p.getExpression())).append(p.getType() == SearchType.reference ? p.getTargetTypesAsText() : "") - .append("").append(presentOthers(p)).append("
    ").append(p.getType()).append("") + .append(md).append("").append(p.getType() == SearchType.composite ? getCompositeExpression(p) : Utilities.escapeXml(p.getExpression())).append(p.getType() == SearchType.reference ? p.getTargetTypesAsText() : "") + .append("").append(presentOthers(p)).append("
    ").append(p.getCode()).append("").append(p.getType()) - .append("").append(Utilities.escapeXml(p.getDescription())).append("").append(presentPaths(p.getPaths())).append(p.getType() == SearchType.reference ? p.getTargetTypesAsText() : "").append("
    ").append(Utilities.escapeXml(p.getDescription())).append("").append(presentPaths(p.getPaths())).append(p.getType() == SearchType.reference ? p.getTargetTypesAsText() : "").append("
    ").append(p.getName()).append("").append(p.getType().toCode()) - .append("").append(Utilities.escapeXml(p.getDescription())).append("").append(p.getExpression() == null ? "" : p.getExpression()).append("
    ").append(Utilities.escapeXml(p.getDescription())).append("").append(p.getExpression() == null ? "" : p.getExpression()).append("
    \r\n"); return b.toString(); @@ -8442,8 +8444,8 @@ private String presentPaths(List paths) { private String produceExamples(ResourceDefn resource) { StringBuilder s = new StringBuilder(); for (Example e: resource.getExamples()) { - s.append("").append(Utilities.escapeXml(e.getDescription())).append("sourceformatted"); + s.append("").append(Utilities.escapeXml(e.getDescription())).append("sourceformatted"); } return s.toString(); } @@ -8495,10 +8497,10 @@ private String produceProfiles(ResourceDefn resource, String datatype) { if (count == 0) return "

    No Profiles defined for this "+(datatype == null ? "resource" : "data type")+"

    "; return - "\r\n"+ - " \r\n"+ - b.toString()+ - "
    ProfileDescriptionContext
    \r\n"; + "\r\n"+ + " \r\n"+ + b.toString()+ + "
    ProfileDescriptionContext
    \r\n"; } @@ -8539,7 +8541,7 @@ private String produceExtensions(ResourceDefn resource) { b.append("No Extensions defined for this resource"); map.clear(); - + for (StructureDefinition sd : workerContext.getExtensionDefinitions()) { boolean inc = false; for (StructureDefinitionContextComponent ec : sd.getContext()) @@ -8574,11 +8576,11 @@ private Object presentContext(StructureDefinition cs, String resource) { StringBuilder b = new StringBuilder(); boolean first = true; for (StructureDefinitionContextComponent c : cs.getContext()) { - if (appliesTo(c, resource)) { - if (first) first = false; else b.append(", "); - if (c.getType() != ExtensionContextType.ELEMENT) - b.append(""+c.getType().toCode()+": "); - b.append(""+c.getExpression()+""); + if (appliesTo(c, resource)) { + if (first) first = false; else b.append(", "); + if (c.getType() != ExtensionContextType.ELEMENT) + b.append(""+c.getType().toCode()+": "); + b.append(""+c.getExpression()+""); } } return b.toString(); @@ -8761,7 +8763,7 @@ private boolean matchesType(String tn, String context) { private boolean coversType(ConstraintStructure item, String tn) { return matchesType(tn, item.getResource().getType()); -} + } private String produceSearchExtensions(ResourceDefn resource) { @@ -8780,17 +8782,17 @@ private String produceSearchExtensions(ResourceDefn resource) { SearchParameter sp = map.get(s); count++; b.append(""+ - ""+sp.getCode()+""+ - ""+sp.getType().toCode()+""+ - ""+Utilities.escapeXml(sp.getDescription())+"
    "+ - "Expression: "+Utilities.escapeXml(sp.getExpression())+"\r\n"); + ""+sp.getCode()+""+ + ""+sp.getType().toCode()+""+ + ""+Utilities.escapeXml(sp.getDescription())+"
    "+ + "Expression: "+Utilities.escapeXml(sp.getExpression())+"\r\n"); } if (count == 0) b.append("No Search Extensions defined for this resource"); return b.toString(); } - + public String produceExtensionsSearch(StructureDefinition sd) { int count = 0; Map map = new HashMap(); @@ -8809,10 +8811,10 @@ public String produceExtensionsSearch(StructureDefinition sd) { SearchParameter sp = map.get(s); count++; b.append(""+ - ""+sp.getCode()+""+ - ""+sp.getType().toCode()+""+ - ""+Utilities.escapeXml(sp.getDescription())+"
    "+ - "Expression: "+Utilities.escapeXml(sp.getExpression())+"\r\n"); + ""+sp.getCode()+""+ + ""+sp.getType().toCode()+""+ + ""+Utilities.escapeXml(sp.getDescription())+"
    "+ + "Expression: "+Utilities.escapeXml(sp.getExpression())+"\r\n"); } if (count == 0) b.append("No Search Extensions defined for this resource"); @@ -8834,7 +8836,7 @@ private boolean coversResource(ConstraintStructure item, String rn) { if (item.getDefn() == null && item.getResource() != null && item.getResource().getType().equals(rn)) return true; return false; -} + } private void produceProfileLine(StringBuilder s, ImplementationGuideDefn ig, boolean started, Profile ap) { if (!started) @@ -8869,7 +8871,7 @@ private String produceExampleList(ResourceDefn resource) throws Exception { for (Example e: p.getExamples()) { String rn = e.getResourceName(); if (Utilities.noString(rn)) - rn = e.getXml().getDocumentElement().getNodeName(); + rn = e.getElement().fhirType(); if (rn.equals(resource.getName())) produceExampleListEntry(s, e, p, ig); } @@ -9045,7 +9047,7 @@ private String produceStructureDefinitionExamples(ResourceDefn resource) throws for (Example e: p.getExamples()) { String rn = e.getResourceName(); if (Utilities.noString(rn)) - rn = e.getXml().getDocumentElement().getNodeName(); + rn = e.getElement().fhirType(); if (rn.equals(resource.getName())) produceExampleListEntry(s, e, p, ig); } @@ -9159,65 +9161,65 @@ private void checkFormat(String filename, String res, ResourceDefn r) throws FHI else if (!doc.getFirstElement().getName().equals("div")) log("file \""+filename+"\": root element should be 'div' not '"+doc.getFirstElement().getName()+"'", LogMessageType.Error); else if (doc.getFirstElement() == null) { - log("file \""+filename+"\": there is no 'Scope and Usage'", LogMessageType.Error); - } else { - XhtmlNode scope = null; - XhtmlNode context = null; - for (XhtmlNode x : doc.getChildNodes()) { - if (x.getNodeType() == NodeType.Element) { - if (!x.getName().equals("div")) { - log("file \""+filename+"\": all child elements of the root div should be 'div's too (found '"+x.getName()+"')", LogMessageType.Error); - return; - } else if (x.getChildNodes().isEmpty()) { - log("file \""+filename+"\": div/div["+Integer.toString(doc.getChildNodes().indexOf(x))+"] must have at least an h2", LogMessageType.Error); - return; - } else if (!isFirstChildElementH2(x)) { - log("file \""+filename+"\": div/div["+Integer.toString(doc.getChildNodes().indexOf(x))+"] must start with an h2", LogMessageType.Error); - return; - } else { - XhtmlNode fn = getH2Element(x); - String s = fn.allText(); - if (! ((s.equals("Scope and Usage")) || (s.equals("Boundaries and Relationships")) || (s.equals("Background and Context")) ) ) { - log("file \""+filename+"\": div/div["+Integer.toString(doc.getChildNodes().indexOf(x))+"]/h2 must be either 'Scope and Usage', 'Boundaries and Relationships', or 'Background and Context'", LogMessageType.Error); + log("file \""+filename+"\": there is no 'Scope and Usage'", LogMessageType.Error); + } else { + XhtmlNode scope = null; + XhtmlNode context = null; + for (XhtmlNode x : doc.getChildNodes()) { + if (x.getNodeType() == NodeType.Element) { + if (!x.getName().equals("div")) { + log("file \""+filename+"\": all child elements of the root div should be 'div's too (found '"+x.getName()+"')", LogMessageType.Error); + return; + } else if (x.getChildNodes().isEmpty()) { + log("file \""+filename+"\": div/div["+Integer.toString(doc.getChildNodes().indexOf(x))+"] must have at least an h2", LogMessageType.Error); + return; + } else if (!isFirstChildElementH2(x)) { + log("file \""+filename+"\": div/div["+Integer.toString(doc.getChildNodes().indexOf(x))+"] must start with an h2", LogMessageType.Error); return; } else { - if (scope == null) { - if (s.equals("Scope and Usage")) { - scope = x; - if (r != null) - r.setRequirements(new XhtmlComposer(XhtmlComposer.HTML).composePlainText(x)); - } else { - log("file \""+filename+"\": 'Scope and Usage' must come first", LogMessageType.Error); - return; - } - if (s.equals("Boundaries and Relationships")) { - if (context != null) { - log("file \""+filename+"\": 'Boundaries and Relationships' must come first before 'Background and Context'", LogMessageType.Error); + XhtmlNode fn = getH2Element(x); + String s = fn.allText(); + if (! ((s.equals("Scope and Usage")) || (s.equals("Boundaries and Relationships")) || (s.equals("Background and Context")) ) ) { + log("file \""+filename+"\": div/div["+Integer.toString(doc.getChildNodes().indexOf(x))+"]/h2 must be either 'Scope and Usage', 'Boundaries and Relationships', or 'Background and Context'", LogMessageType.Error); + return; + } else { + if (scope == null) { + if (s.equals("Scope and Usage")) { + scope = x; + if (r != null) + r.setRequirements(new XhtmlComposer(XhtmlComposer.HTML).composePlainText(x)); + } else { + log("file \""+filename+"\": 'Scope and Usage' must come first", LogMessageType.Error); return; } - } + if (s.equals("Boundaries and Relationships")) { + if (context != null) { + log("file \""+filename+"\": 'Boundaries and Relationships' must come first before 'Background and Context'", LogMessageType.Error); + return; + } + } - if (s.equals("Background and Context")) - context = x; + if (s.equals("Background and Context")) + context = x; + } } - } - boolean found = false; - for (XhtmlNode n : x.getChildNodes()) { - if (!found) - found = n == fn; - else { - if ("h1".equals(n.getName()) || "h2".equals(n.getName())) { - log("file \""+filename+"\": content of a
    inner section cannot contain h1 or h2 headings", LogMessageType.Error); - return; + boolean found = false; + for (XhtmlNode n : x.getChildNodes()) { + if (!found) + found = n == fn; + else { + if ("h1".equals(n.getName()) || "h2".equals(n.getName())) { + log("file \""+filename+"\": content of a
    inner section cannot contain h1 or h2 headings", LogMessageType.Error); + return; + } } } } } } } - } - List allowed = Arrays.asList("div", "h2", "h3", "h4", "h5", "i", "b", "code", "pre", "blockquote", "p", "a", "img", "table", "thead", "tbody", "tr", "th", "td", "ol", "ul", "li", "br", "span", "em", "strong", "sup", "sub"); - iterateAllChildNodes(doc, allowed); + List allowed = Arrays.asList("div", "h2", "h3", "h4", "h5", "i", "b", "code", "pre", "blockquote", "p", "a", "img", "table", "thead", "tbody", "tr", "th", "td", "ol", "ul", "li", "br", "span", "em", "strong", "sup", "sub"); + iterateAllChildNodes(doc, allowed); } catch (Exception e) { throw new FHIRException("Error processing "+filename+": "+e.getMessage(), e); } @@ -9370,10 +9372,10 @@ else if (com[0].equals("inv")) src = s1+genProfileConstraints(profile.getResource())+s3; else if (com[0].equals("plural")) src = s1+Utilities.pluralizeMe(filename)+s3; -// else if (com[0].equals("notes")) -// src = s1+"todo" /*Utilities.fileToString(folders.srcDir + filename+File.separatorChar+filename+".html")*/ +s3; -// else if (com[0].equals("dictionary")) -// src = s1+"todo"+s3; + // else if (com[0].equals("notes")) + // src = s1+"todo" /*Utilities.fileToString(folders.srcDir + filename+File.separatorChar+filename+".html")*/ +s3; + // else if (com[0].equals("dictionary")) + // src = s1+"todo"+s3; else if (com[0].equals("breadcrumb")) src = s1 + breadCrumbManager.make(filename) + s3; else if (com[0].equals("navlist")) @@ -9424,7 +9426,7 @@ else if (com[0].equals("rellink")) { if (!filename.contains(".html")) src = s1+filename+".html"+s3; else - src = s1+filename+s3; + src = s1+filename+s3; } else if (com[0].equals("schematron")) src = s1+(isDict ? "None" : "Schematron")+s3; else if (com[0].equals("summary")) @@ -9462,7 +9464,7 @@ else if (com[0].equals("wg")) { } else if (com[0].equals("fmm")) { String fmm = profile.getFmm(); if (Utilities.noString(fmm)) - fmm = pack.getFmmLevel(); + fmm = pack.getFmmLevel(); src = s1+getFmmFromlevel(genlevel(level), fmm)+s3; } else if (com[0].equals("profile-context")) src = s1+getProfileContext(pack.getCandidateResource(), genlevel(level))+s3; @@ -9479,27 +9481,27 @@ else if (com[0].equals("sstatus")) { src = s1 + s3; else src = s1 + "

    Jump past Narrative

    " + s3; - } else if (com[0].equals("resurl")) { - if (Utilities.noString(pack.metadata("id"))) - src = s1+s3; - else - src = s1+"The id of this profile is "+pack.metadata("id")+s3; - } else if (com[0].equals("res-type-count")) { - src = s1+definitions.getResources().size()+s3; - } else if (com[0].equals("search-location")) { - src = s1+searchLocation+s3; - } else if (com[0].equals("extensions-location")) { - src = s1+extensionsLocation+s3; - } else if (com[0].equals("profile.intro.include")) { - src = s1+includeProfileFile(pack, profile, "introduction")+s3; - } else if (com[0].equals("profile.notes.include")) { - src = s1+includeProfileFile(pack, profile, "notes")+s3; - } else if (macros.containsKey(com[0])) { - src = s1+macros.get(com[0])+s3; - } else if (com[0].equals("jira-link")) { - src = s1+genJiralink(filename, profile.getDefn() != null ? profile.getDefn().getName() : null)+s3; - } else - throw new Exception("Instruction <%"+s2+"%> not understood parsing resource "+filename); + } else if (com[0].equals("resurl")) { + if (Utilities.noString(pack.metadata("id"))) + src = s1+s3; + else + src = s1+"The id of this profile is "+pack.metadata("id")+s3; + } else if (com[0].equals("res-type-count")) { + src = s1+definitions.getResources().size()+s3; + } else if (com[0].equals("search-location")) { + src = s1+searchLocation+s3; + } else if (com[0].equals("extensions-location")) { + src = s1+extensionsLocation+s3; + } else if (com[0].equals("profile.intro.include")) { + src = s1+includeProfileFile(pack, profile, "introduction")+s3; + } else if (com[0].equals("profile.notes.include")) { + src = s1+includeProfileFile(pack, profile, "notes")+s3; + } else if (macros.containsKey(com[0])) { + src = s1+macros.get(com[0])+s3; + } else if (com[0].equals("jira-link")) { + src = s1+genJiralink(filename, profile.getDefn() != null ? profile.getDefn().getName() : null)+s3; + } else + throw new Exception("Instruction <%"+s2+"%> not understood parsing resource "+filename); } return src; } @@ -9528,12 +9530,13 @@ private String getProfileContext(CanonicalResource mr, String prefix) throws Def DataRenderer gen = new DataRenderer(workerContext); CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder(); for (UsageContext uc : mr.getUseContext()) { - String vs = gen.display(uc.getValue()); - if (vs != null) - b.append(gen.display(uc.getCode())+": "+vs); + String vs = gen.displayDataType(uc.getValue()); + if (vs != null) { + b.append(gen.displayDataType(uc.getCode())+": "+vs); + } } for (CodeableConcept cc : mr.getJurisdiction()) { - b.append("Country: "+gen.displayCodeableConcept(cc)); + b.append("Country: "+gen.displayCodeableConcept(ResourceWrapper.forType(getRc().getContextUtilities(), cc))); } if (mr.getExperimental()) { if (isTrialUse(mr)) @@ -9704,7 +9707,7 @@ private boolean parentChainHasOptional(ElementDefinition ed, StructureDefinition ElementDefinition match = (ElementDefinition) ed.getUserData(ProfileUtilities.UD_DERIVATION_POINTER); if (match == null) return true; // really, we shouldn't get here, but this appears to be common in the existing profiles? - // throw new Error("no matches for "+ed.getPath()+"/"+ed.getName()+" in "+profile.getUrl()); + // throw new Error("no matches for "+ed.getPath()+"/"+ed.getName()+" in "+profile.getUrl()); while (match.getPath().contains(".")) { if (match.getMin() == 0) { @@ -9918,8 +9921,8 @@ else if (com[0].equals("inv")) src = s1+genExtensionConstraints(ed)+s3; else if (com[0].equals("plural")) src = s1+Utilities.pluralizeMe(filename)+s3; -// else if (com[0].equals("notes")) -// src = s1+"todo" /*Utilities.fileToString(folders.srcDir + filename+File.separatorChar+filename+".html")*/ +s3; + // else if (com[0].equals("notes")) + // src = s1+"todo" /*Utilities.fileToString(folders.srcDir + filename+File.separatorChar+filename+".html")*/ +s3; else if (com[0].equals("dictionary")) src = s1+definitionsProfile(ed, genlevel(level))+s3; else if (com[0].equals("breadcrumb")) @@ -10085,10 +10088,10 @@ private String describeExtensionSearchParameters(StructureDefinition ed) { for (SearchParameter sp : extensionSearchParameterMap.get(ed.getUrl())) { b.append("

    Search parameters for this extension. See Searching for more information about searching in REST, messaging, and services.

    "); b.append(""+ - ""+ - ""+ - "\r\n"); + ""+ + ""+ + "\r\n"); } b.append("
    "+sp.getCode()+""+sp.getType().toCode()+""+Utilities.escapeXml(sp.getDescription())+"
    "+ - "Expression: "+Utilities.escapeXml(sp.getExpression())+"
    "+sp.getCode()+""+sp.getType().toCode()+""+Utilities.escapeXml(sp.getDescription())+"
    "+ + "Expression: "+Utilities.escapeXml(sp.getExpression())+"
    "); } else { @@ -10101,7 +10104,7 @@ private void addExtensionSearchParams(Profile cp) { for (SearchParameter spd : cp.getSearchParameters()) { addExtensionSearchParams(spd); } - + } private void addExtensionSearchParams(ResourceDefn rd) { @@ -10139,7 +10142,7 @@ private String describeExtensionContext(StructureDefinition ed) { private String generateExtensionTable(StructureDefinition ed, String filename, String full, String prefix) throws Exception { StructureDefinitionRenderer sdr = new StructureDefinitionRenderer(rc); - return new XhtmlComposer(XhtmlComposer.HTML).compose(sdr.generateExtensionTable(filename, ed, folders.dstDir, false, full.equals("true"), prefix, prefix, null, getRc())); + return new XhtmlComposer(XhtmlComposer.HTML).compose(sdr.generateExtensionTable(new RenderingStatus(), filename, ed, folders.dstDir, false, full.equals("true"), prefix, prefix, null, getRc(), null, null, ResourceWrapper.forResource(rc.getContextUtilities(), ed))); } @@ -10196,8 +10199,8 @@ public void txItem(int level, Map txm if (vsn.equals("?ext")) System.out.println("No value set at "+path); b.append("").append(path).append("").append(Utilities.escapeXml(vsn)).append("").append(tx.getStrength() == null ? "" : tx.getStrength().toCode()).append("").append(vss).append("\r\n"); + append(genlevel(level)).append("terminologies.html#").append(tx.getStrength() == null ? "" : tx.getStrength().toCode()). + append("\">").append(tx.getStrength() == null ? "" : tx.getStrength().toCode()).append("").append(vss).append("\r\n"); } private String getInvariantList(StructureDefinition profile) throws FHIRException, Exception { @@ -10228,10 +10231,10 @@ private String getInvariantList(StructureDefinition profile) throws FHIRExceptio List invs = txmap.get(path); for (ElementDefinitionConstraintComponent inv : invs) { b.append(""+presentLevel(inv)+" ").append(inv.getKey()).append("").append(path).append("").append(Utilities.escapeXml(inv.getHuman())) - .append("
    Expression: ").append(Utilities.escapeXml(inv.getExpression())).append("").append(Utilities.escapeXml(inv.getRequirements())); - if (inv.hasExtension(ToolingExtensions.EXT_BEST_PRACTICE_EXPLANATION)) - b.append(". This is (only) a best practice guideline because:
    "+processMarkdown("best practice guideline", inv.getExtensionString(ToolingExtensions.EXT_BEST_PRACTICE_EXPLANATION), "")+"
    "); - + .append("
    Expression: ").append(Utilities.escapeXml(inv.getExpression())).append("").append(Utilities.escapeXml(inv.getRequirements())); + if (inv.hasExtension(ToolingExtensions.EXT_BEST_PRACTICE_EXPLANATION)) + b.append(". This is (only) a best practice guideline because:
    "+processMarkdown("best practice guideline", inv.getExtensionString(ToolingExtensions.EXT_BEST_PRACTICE_EXPLANATION), "")+"
    "); + b.append("\r\n"); } } @@ -10295,7 +10298,7 @@ else if (examples.size() == 1) return s.toString(); } } - */ + */ private String mappingsProfile(StructureDefinition source) throws IOException { MappingsGenerator m = new MappingsGenerator(definitions); @@ -10370,7 +10373,7 @@ else if (definitions.hasElementDefn(name)) private String generateProfileStructureTable(ConstraintStructure profile, boolean diff, String filename, String baseName, String prefix) throws Exception { String fn = filename.contains(".") ? filename.substring(0, filename.indexOf('.')) : filename; String deffile = fn+"-definitions.html"; - return new XhtmlComposer(XhtmlComposer.HTML).compose(new StructureDefinitionRenderer(rc).generateTable(deffile, profile.getResource(), diff, folders.dstDir, false, baseName, !diff, prefix, prefix, false, false, null, false, getRc(), "")); + return new XhtmlComposer(XhtmlComposer.HTML).compose(new StructureDefinitionRenderer(rc).generateTable(new RenderingStatus(), deffile, profile.getResource(), diff, folders.dstDir, false, baseName, !diff, prefix, prefix, false, false, null, false, getRc(), "", ResourceWrapper.forResource(rc.getContextUtilities(), profile.getResource()))); } private boolean isAggregationEndpoint(String name) { @@ -10386,7 +10389,7 @@ private String makeArchives() throws Exception { if (ini.getPropertyNames("Archives") != null) { for (String v : ini.getPropertyNames("Archives")) { s.append("
  • Version ").append(v).append(", ") - .append(ini.getStringProperty("Archives", v)).append("
  • "); + .append(ini.getStringProperty("Archives", v)).append(""); if (!definitions.getPastVersions().contains(v)) definitions.getPastVersions().add(v); } @@ -10458,13 +10461,13 @@ public void setDefinitions(Definitions definitions) throws Exception { log("Load IHE Format Codes", LogMessageType.Process); NpmPackage ihe = new FilesystemPackageCacheManager.Builder().build().loadPackage("ihe.formatcode.fhir"); workerContext.loadFromPackage(ihe, new R4ToR5Loader(BuildWorkerContext.defaultTypesToLoad(), new IHELoader(), workerContext.getVersion())); - + Map packages = new HashMap<>(); packages.put("http://temrinology.hl7.org", loadSpecMap(utg)); packages.put("http://dicom.nema.org/", loadSpecMap(dicom)); packages.put(extensionsLocation, loadSpecMap(ext)); htmlchecker = new HTMLLinkChecker(this, validationErrors, webLocation, extensionsLocation, packages); - + log(" .. loaded", LogMessageType.Process); vsValidator = new ValueSetValidator(workerContext, definitions.getVsFixups(), definitions.getStyleExemptions()); breadCrumbManager.setContext(workerContext); @@ -10476,7 +10479,7 @@ public void setVersion(FHIRVersion version) { workerContext.setVersion(version.toCode()); htmlchecker.setVersion(version); uml.setVersion(version.toCode()); - + webLocation = webLocation.replace("{version}", version == FHIRVersion._5_0_0 ? "R5" : version.toCode()); } @@ -10488,7 +10491,7 @@ private org.hl7.fhir.tools.publisher.SpecMapManager loadSpecMap(NpmPackage npm) public void setFolders(FolderManager folders) throws Exception { this.folders = folders; r4r5Outcomes = (JsonObject) new com.google.gson.JsonParser().parse(TextFile.fileToString(Utilities.path(folders.rootDir, "implementations", "r4maps", "outcomes.json"))); - + for (File f : new File(Utilities.path(folders.rootDir, "tools", "macros")).listFiles()) { if (f.getAbsolutePath().endsWith(".html")) { macros.put(Utilities.fileTitle(f.getName()), TextFile.fileToString(f)); @@ -10532,7 +10535,7 @@ public void log(String content, LogMessageType type) { System.out.println(String.format("%1$-74s", content)+" "+String.format("%1$8s", Float.toString(gap))+" "+String.format("%1$3s", Long.toString(secs))+"sec "+String.format("%1$4s", Long.toString(used))+"MB"); } else System.out.println(content); - + Runtime runtime = Runtime.getRuntime(); long totalMemory = runtime.totalMemory(); @@ -10541,13 +10544,13 @@ public void log(String content, LogMessageType type) { if (usedMemory > maxMemory) { maxMemory = usedMemory; } - + } -// public void logNoEoln(String content) { -// System.out.print(content); -// notime = true; -// } + // public void logNoEoln(String content) { + // System.out.print(content); + // notime = true; + // } public List getOrderedResources() { @@ -10699,7 +10702,7 @@ public void setTranslations(Translations translations) { public String processMarkdown(String location, String text, String prefix) throws Exception { return processMarkdown(location, text, prefix, false); } - + public String processMarkdown(String location, String text, String prefix, boolean enforceFullStop) throws Exception { if (text == null) return ""; @@ -10718,7 +10721,7 @@ private String checkEscape(String text) { return ""; if (text.startsWith("```")) return text.substring(3); - + StringBuilder b = new StringBuilder(); boolean escaping = true; for (int i = 0; i < text.length(); i++) { @@ -10758,11 +10761,11 @@ public BindingResolution resolveBinding(StructureDefinition profile, ElementDefi return resolveBinding(profile, binding.getValueSet(), binding.getDescription(), path); } } - + public BindingResolution resolveBinding(StructureDefinition profile, String ref, String path) throws FHIRException { return resolveBinding(profile, ref, null, path); } - + public BindingResolution resolveBinding(StructureDefinition profile, String ref, String description, String path) throws FHIRException { BindingResolution br = new BindingResolution(); if (ref.contains("|")) @@ -10816,7 +10819,7 @@ public BindingResolution resolveBinding(StructureDefinition profile, String ref, System.out.println("Unresolved Value set "+ref+"@"+path+" in "+profile.getUrl()); br.url = ref; br.display = "????"; - + getValidationErrors().add( new ValidationMessage(Source.Publisher, IssueType.NOTFOUND, -1, -1, path, "Unresolved Value set "+ref, IssueSeverity.WARNING)); } @@ -10874,8 +10877,8 @@ public String getLinkForProfile(StructureDefinition profile, String url) { if (!url.startsWith("#")) { String[] path = url.split("#"); profile = new ProfileUtilities(workerContext, null, null).getProfile(null, path[0]); -// if (profile == null && url.startsWith("StructureDefinition/")) -// return "hspc-"+url.substring(8)+".html|"+url.substring(8); + // if (profile == null && url.startsWith("StructureDefinition/")) + // return "hspc-"+url.substring(8)+".html|"+url.substring(8); } if (profile != null) { fn = profile.getWebPath(); @@ -10979,24 +10982,24 @@ else if (com[0].equals("datatypecodes")) src = s1 + genDTCodes() + s3; else if (com[0].equals("allparams")) src = s1 + allParamlist() + s3; -// else if (com[0].equals("bindingtable-codelists")) -// src = s1 + genBindingTable(true) + s3; -// else if (com[0].equals("bindingtable")) -// src = s1 + genBindingsTable() + s3; + // else if (com[0].equals("bindingtable-codelists")) + // src = s1 + genBindingTable(true) + s3; + // else if (com[0].equals("bindingtable")) + // src = s1 + genBindingsTable() + s3; else if (com[0].equals("codeslist")) src = s1 + genCodeSystemsTable() + s3; -// else if (com[0].equals("valuesetslist")) -// src = s1 + genValueSetsTable() + s3; + // else if (com[0].equals("valuesetslist")) + // src = s1 + genValueSetsTable() + s3; else if (com[0].equals("igvaluesetslist")) src = s1 + genIGValueSetsTable() + s3; else if (com[0].equals("namespacelist")) src = s1 + genNSList() + s3; else if (com[0].equals("conceptmapslist")) src = s1 + genConceptMapsTable() + s3; -// else if (com[0].equals("bindingtable-others")) -// src = s1 + genBindingTable(false) + s3; + // else if (com[0].equals("bindingtable-others")) + // src = s1 + genBindingTable(false) + s3; else if (com[0].equals("resimplall")) - src = s1 + genResImplList() + s3; + src = s1 + genResImplList() + s3; else if (com[0].equals("breadcrumb")) src = s1 + breadCrumbManager.make(pack.getId()) + s3; else if (com[0].equals("navlist")) @@ -11066,19 +11069,19 @@ private String getPackageContent(Profile pack, String prefix) throws Exception { s.append("Profiles: "); for (ConstraintStructure p : pack.getProfiles()) s.append("").append(Utilities.escapeXml(p.getTitle())) - .append("").append(Utilities.escapeXml(p.getResource().getDescription())).append(""); + .append("").append(Utilities.escapeXml(p.getResource().getDescription())).append(""); } if (pack.getExtensions().size() > 0) { s.append("Extensions: "); for (StructureDefinition ed : pack.getExtensions()) s.append(" ").append(Utilities.escapeXml(ed.getId())) - .append("").append(Utilities.escapeXml(ed.getName())).append(" : ").append(processMarkdown(pack.getId(), ed.getDescription(), prefix)).append(""); + .append("").append(Utilities.escapeXml(ed.getName())).append(" : ").append(processMarkdown(pack.getId(), ed.getDescription(), prefix)).append(""); } if (pack.getExamples().size() > 0) { s.append("Examples: "); for (Example ex : pack.getExamples()) s.append("").append(Utilities.escapeXml(Utilities.changeFileExt(ex.getName(), ""))) - .append("").append(processMarkdown(pack.getId(), ex.getDescription(), prefix)).append(""); + .append("").append(processMarkdown(pack.getId(), ex.getDescription(), prefix)).append(""); } s.append(""); @@ -11121,7 +11124,7 @@ private String asText(List> list final String value = rn.getCode(); if ("Any".equals(value)) b.append("Any"); - else + else b.append("").append(value).append(""); } if (!first) @@ -11157,7 +11160,7 @@ private String genW5(boolean types) throws Exception { private void processW5(StringBuilder b, List items, String cat, boolean types) throws Exception { b.append("") - .append(Utilities.escapeXml(definitions.getW5s().get(cat).getDescription())).append("\r\n"); + .append(Utilities.escapeXml(definitions.getW5s().get(cat).getDescription())).append("
    \r\n"); for (String rn : definitions.sortedResourceNames()) { ResourceDefn r = definitions.getResourceByName(rn); if (r.getRoot().getW5().startsWith(cat)) { @@ -11212,15 +11215,15 @@ private String genStatusCodes() throws Exception { if (rc > colcount) colcount = rc; } -// b.append(""); -// b.append("Path"); -// for (int i = 0; i < colcount; i++) -// b.append("c").append(Integer.toString(i + 1)).append(""); -// b.append("\r\n"); + // b.append(""); + // b.append("Path"); + // for (int i = 0; i < colcount; i++) + // b.append("c").append(Integer.toString(i + 1)).append(""); + // b.append("\r\n"); List names = new ArrayList(); for (String n : definitions.getStatusCodes().keySet()) - names.add(n); + names.add(n); Collections.sort(names); ArrayList row = definitions.getStatusCodes().get("@code"); @@ -11261,7 +11264,7 @@ private String genStatusCodes() throws Exception { b.append("").append(s).append(""); } b.append("\r\n"); - + for (String n : names) { if (!n.startsWith("@")) { b.append(""); @@ -11302,7 +11305,7 @@ private String genStatusCodes() throws Exception { b.append("
  • ").append(Utilities.escapeXml(s)).append("
  • \r\n"); b.append("\r\n"); } - + return b.toString(); } @@ -11379,8 +11382,8 @@ public String expandVS(ValueSet vs, String prefix, String base) { IniFile sini = new IniFile(Utilities.path(folders.rootDir, "temp", "stats.ini")); sini.setIntegerProperty("valuesets", vs.getId(), i, null); sini.save(); - RenderingContext lrc = rc.copy().setLocalPrefix(prefix); - RendererFactory.factory(exp, lrc).render(exp); + RenderingContext lrc = rc.copy(false).setLocalPrefix(prefix); + RendererFactory.factory(exp, lrc).renderResource(ResourceWrapper.forResource(lrc.getContextUtilities(), exp)); return "
    \r\n"+VS_INC_START+""+new XhtmlComposer(XhtmlComposer.HTML).compose(exp.getText().getDiv())+VS_INC_END; } catch (Exception e) { // e.printStackTrace(); @@ -11389,7 +11392,7 @@ public String expandVS(ValueSet vs, String prefix, String base) { } } -private int countContains(List list) { + private int countContains(List list) { int i = list.size(); for (ValueSetExpansionContainsComponent c : list) { if (c.hasContains()) @@ -11398,9 +11401,9 @@ private int countContains(List list) { return i; } -// public List getCollectedValidationErrors() { -// return collectedValidationErrors; -// } + // public List getCollectedValidationErrors() { + // return collectedValidationErrors; + // } public List getValidationErrors() { return validationErrors; @@ -11459,7 +11462,7 @@ private String getFmm(String resourceName, boolean hideNormative) throws Excepti } else return " "+rd.getFmmLevel()+""; } - + private String getNormativePackageRef(String resourceName) throws Exception { ResourceDefn rd = definitions.getResourceByName(resourceName); if (rd == null) @@ -11469,7 +11472,7 @@ private String getNormativePackageRef(String resourceName) throws Exception { else return " N"; } - + private String getFmmShort(String resourceName) throws Exception { ResourceDefn rd = definitions.getResourceByName(resourceName); if (rd == null) @@ -11479,7 +11482,7 @@ private String getFmmShort(String resourceName) throws Exception { else return ""+rd.getFmmLevel()+""; } - + private String getFmmFromlevel(String prefix, String level) throws Exception { return " Maturity Level: "+(Utilities.noString(level) ? "0" : level); } @@ -11540,8 +11543,8 @@ private String genCSList() throws FHIRException { b.append("\r\n"); b.append(" "+Utilities.escapeXml(cs.present())+"\r\n"); b.append(" "+(cs.hasTitle() ? cs.getTitle()+": " : "")+Utilities.escapeXml(cs.getDescription())+"\r\n"); -// String oid = CodeSystemUtilities.getOID(cs); -// b.append(" "+(oid == null ? "" : oid)+"\r\n"); + // String oid = CodeSystemUtilities.getOID(cs); + // b.append(" "+(oid == null ? "" : oid)+"\r\n"); b.append(" \r\n"); } } @@ -11580,7 +11583,7 @@ public ValueSetValidator getVsValidator() { public void clean() { // recover some memory. Keep only what is needed for validation -// definitions = null; + // definitions = null; ini = null; prevSidebars.clear(); orderedResources.clear(); @@ -11595,7 +11598,7 @@ public void clean() { vsValidator = null; suppressedMessages.clear(); definitions.clean(); - + conceptMaps = null; profiles = null; igResources = null; @@ -11607,7 +11610,7 @@ public void clean() { normativePackages = null; processor = null; - + System.gc(); } @@ -11663,9 +11666,9 @@ private String genNSList() throws Exception { for (StructureDefinition sd : profiles.getList()) if (sd.getUrl().startsWith("http://hl7.org/fhir") && !definitions.getResourceTemplates().containsKey(sd.getName())) definitions.addNs(sd.getUrl(), "Profile "+sd.getName(), sd.getWebPath()); -// for (StructureDefinition sd : workerContext.getExtensionDefinitions()) -// if (sd.getUrl().startsWith("http://hl7.org/fhir")) -// definitions.addNs(sd.getUrl(), "Profile "+sd.getName(), sd.getWebPath()); + // for (StructureDefinition sd : workerContext.getExtensionDefinitions()) + // if (sd.getUrl().startsWith("http://hl7.org/fhir")) + // definitions.addNs(sd.getUrl(), "Profile "+sd.getName(), sd.getWebPath()); for (NamingSystem nss : definitions.getNamingSystems()) { String url = null; definitions.addNs("http://hl7.org/fhir/NamingSystem/"+nss.getId(), "System "+nss.getName(), nss.getWebPath()); @@ -11723,7 +11726,7 @@ public boolean prependLinks() { return true; } - + private String genModifierList() { StringBuilder b = new StringBuilder(); for (String s : sorted(definitions.getTypes().keySet())) @@ -11776,9 +11779,9 @@ private void checkForMeaningWhenMissing(StringBuilder b, String path, ElementDef if (e.hasMeaningWhenMissing()) { b.append("
  • "+path+": "+Utilities.escapeXml(e.getMeaningWhenMissing())+"
  • \r\n"); } -// if (e.getDefaultValue() != null) { -// b.append("
  • "+path+": "+renderType(e.getDefaultValue())+"
  • \r\n"); -// } + // if (e.getDefaultValue() != null) { + // b.append("
  • "+path+": "+renderType(e.getDefaultValue())+"
  • \r\n"); + // } for (ElementDefn c : e.getElements()) checkForMeaningWhenMissing(b, path+"."+c.getName(), c); } @@ -11911,23 +11914,6 @@ private void addExtSearchParams(Map spmap, Profile conf } } - @Override - public ResourceWithReference resolve(RenderingContext context, String url) { - String[] parts = url.split("\\/"); - - if (parts.length == 2 && definitions.hasResource(parts[0]) && parts[1].matches(FormatUtilities.ID_REGEX)) { - Example ex = null; - try { - ex = findExample(parts[0], parts[1]); - } catch (Exception e) { - } - if (ex != null) - return new ResourceWithReference(ex.getTitle()+".html", new DOMWrappers.ResourceWrapperElement(context, ex.getXml().getDocumentElement(), definitions.getResourceByName(ex.getResourceName()).getProfile())); - } -// System.out.println("Reference to undefined resource: \""+url+"\""); - return new ResourceWithReference("broken-link.html", null); - } - public SpecDifferenceEvaluator getDiffEngine() { if (diffEngine == null) diffEngine = new SpecDifferenceEvaluator(workerContext); @@ -11969,7 +11955,7 @@ public void logMessage(String message) { @Override public void logDebugMessage(LogCategory category, String message) { -// System.out.println(message); + // System.out.println(message); } @@ -12034,25 +12020,25 @@ public int r4ValidPct() { private String genR3MapsSummary() throws IOException { StringBuilder b = new StringBuilder(); -// for (String n : definitions.sortedResourceNames()) { -// ResourceSummary rs = getResourceSummary(n); -// if (rs.isMapped()) { -// b.append(""+n+""); -// b.append(""+Integer.toString(rs.getTestCount())+""); -// b.append(""+Integer.toString(rs.executePct())+""); -// b.append(""+Integer.toString(rs.roundTripPct())+""); -// b.append(""+Integer.toString(rs.r4ValidPct())+""); -// if (rs.getR5ValidationErrors() > 0) -// b.append(""+Integer.toString(rs.getR5ValidationErrors())+""); -// else -// b.append(""); -// -// } else { -// b.append(""+n+""); -// b.append("No r4:r5 maps available"); -// } -// b.append(""); -// } + // for (String n : definitions.sortedResourceNames()) { + // ResourceSummary rs = getResourceSummary(n); + // if (rs.isMapped()) { + // b.append(""+n+""); + // b.append(""+Integer.toString(rs.getTestCount())+""); + // b.append(""+Integer.toString(rs.executePct())+""); + // b.append(""+Integer.toString(rs.roundTripPct())+""); + // b.append(""+Integer.toString(rs.r4ValidPct())+""); + // if (rs.getR5ValidationErrors() > 0) + // b.append(""+Integer.toString(rs.getR5ValidationErrors())+""); + // else + // b.append(""); + // + // } else { + // b.append(""+n+""); + // b.append("No r4:r5 maps available"); + // } + // b.append(""); + // } return b.toString(); } @@ -12087,28 +12073,28 @@ private String mapsBckColor(int pct, String badColor, String goodColor) { } public String r4r5StatusForResource(String name) throws IOException { -// ResourceSummary rs = getResourceSummary(name); -// if (!rs.isMapped()) -// return "Not Mapped"; -// -// StringBuilder b = new StringBuilder(); -// b.append(rs.getTestCount()); -// b.append(rs.getTestCount() == 1 ? " test" : " tests"); -// if (rs.getExecuteFailCount() == 0) -// b.append(" that all execute ok."); -// else -// b.append(" of which "+Integer.toString(rs.getExecuteFailCount())+" fail to execute."); -// if (rs.getTestCount() - rs.getExecuteFailCount() > 0) { -// if (rs.getRoundTripFailCount() == 0) -// b.append(" All tests pass round-trip testing "); -// else -// b.append(" "+Integer.toString(rs.getRoundTripFailCount())+" fail round-trip testing"); -// if (rs.getR5ValidationFailCount() == 0) -// b.append(" and all r4 resources are valid."); -// else -// b.append(" and "+Integer.toString(rs.getR5ValidationFailCount())+" r4 resources are invalid ("+Integer.toString(rs.getR5ValidationErrors())+" errors)."); -// } -// return b.toString(); + // ResourceSummary rs = getResourceSummary(name); + // if (!rs.isMapped()) + // return "Not Mapped"; + // + // StringBuilder b = new StringBuilder(); + // b.append(rs.getTestCount()); + // b.append(rs.getTestCount() == 1 ? " test" : " tests"); + // if (rs.getExecuteFailCount() == 0) + // b.append(" that all execute ok."); + // else + // b.append(" of which "+Integer.toString(rs.getExecuteFailCount())+" fail to execute."); + // if (rs.getTestCount() - rs.getExecuteFailCount() > 0) { + // if (rs.getRoundTripFailCount() == 0) + // b.append(" All tests pass round-trip testing "); + // else + // b.append(" "+Integer.toString(rs.getRoundTripFailCount())+" fail round-trip testing"); + // if (rs.getR5ValidationFailCount() == 0) + // b.append(" and all r4 resources are valid."); + // else + // b.append(" and "+Integer.toString(rs.getR5ValidationFailCount())+" r4 resources are invalid ("+Integer.toString(rs.getR5ValidationErrors())+" errors)."); + // } + // return b.toString(); return "See Conversions Summary."; } @@ -12163,7 +12149,7 @@ public String getR4R5ValidationErrors(String name) { public Map> getNormativePackages() { return normativePackages; } - + private String genWildcardTypeList() { StringBuilder b = new StringBuilder(); TypeClassification tc = null; @@ -12187,7 +12173,7 @@ private String genWildcardTypeList() { b.append("\r\n"); return b.toString(); } - + private String genExtensionTypeList() { StringBuilder b = new StringBuilder(); for (WildcardInformation wi : TypesUtilities.wildcards(version.toCode())) { @@ -12218,25 +12204,25 @@ private String listCanonicalResources() throws FHIRException { StringBuilder b = new StringBuilder(); b.append("
      \r\n"); for (String rn : definitions.sortedResourceNames()) { - if (definitions.getResourceByName(rn).getTemplate() != null) + if (definitions.getResourceByName(rn).getTemplate() != null) b.append("
    • "+rn+"
    • \r\n"); } b.append("
    \r\n"); return b.toString(); } - + private String listMetadataResources() throws FHIRException { StringBuilder b = new StringBuilder(); b.append("
      \r\n"); for (String rn : definitions.sortedResourceNames()) { - if (definitions.getResourceByName(rn).getTemplate() != null && definitions.getResourceByName(rn).getTemplate().getName().equals("MetadataResource")) + if (definitions.getResourceByName(rn).getTemplate() != null && definitions.getResourceByName(rn).getTemplate().getName().equals("MetadataResource")) b.append("
    • "+rn+"
    • \r\n"); } b.append("
    \r\n"); return b.toString(); } - - private String listContainedExamples() throws FHIRException { + + private String listContainedExamples() throws FileNotFoundException, UnsupportedEncodingException, IOException, Exception { StringBuilder b = new StringBuilder(); b.append("
      \r\n"); for (String rn : definitions.sortedResourceNames()) { @@ -12250,7 +12236,7 @@ private String listContainedExamples() throws FHIRException { b.append("
    \r\n"); return b.toString(); } - + private String getExtensionsLink(ResourceDefn res) { if (res.getRoot().typeCode().equals("DomainResource")) return " + see the extensions"; @@ -12325,7 +12311,7 @@ private String getMultiLanguageResourceList() { } return b.toString(); } - + private boolean hasMultiLanguageDesignations(ValueSet vs) { for (ConceptSetComponent inc : vs.getCompose().getInclude()) { for (ConceptReferenceComponent cc : inc.getConcept()) { @@ -12376,6 +12362,8 @@ public void makeRenderingContext() { rc.setDestDir(folders.dstDir); rc.setTemplateProvider(new BuildTemplateProvider(definitions)); rc.setPkp(this); + rc.setQuestionnaireMode(QuestionnaireRendererMode.TREE); + rc.setRules(GenerationRules.VALID_RESOURCE); } @Override @@ -12394,12 +12382,7 @@ public Base parseType(Element e) throws FHIRFormatError, IOException, FHIRExcept public void commitTerminologyCache(String token) throws IOException { tcm.commit(token); - - } - @Override - public String urlForContained(RenderingContext context, String containingType, String containingId, String containedType, String containedId) { - return null; } @Override @@ -12423,7 +12406,7 @@ public void setSearchLocation(String searchLocation) { this.searchLocation = searchLocation; } - + public String getExtensionsLocation() { return extensionsLocation; } @@ -12458,6 +12441,37 @@ public String processMarkdown(String location, String text) throws FHIRException public long getMaxMemory() { return maxMemory; } - - + + @Override + public String resolveUri(RenderingContext context, String uri) { + return null; + } + + @Override + public ResourceWithReference resolve(RenderingContext context, String url, String version) { + String[] parts = url.split("\\/"); + + if (parts.length == 2 && definitions.hasResource(parts[0]) && parts[1].matches(FormatUtilities.ID_REGEX)) { + Example ex = null; + try { + ex = findExample(parts[0], parts[1]); + } catch (Exception e) { + } + if (ex != null) { + try { + return new ResourceWithReference(ResourceReferenceKind.EXTERNAL, url, ex.getTitle()+".html", + ResourceWrapper.forResource(rc.getContextUtilities(), ex.getElement())); + } catch (Exception e) { + } + } + } + return new ResourceWithReference(ResourceReferenceKind.UNKNOWN, url, "broken-link.html", null); + } + + @Override + public String getCanonicalForDefaultContext() { + return "http://hl7.org/fhir"; + } + + } diff --git a/src/main/java/org/hl7/fhir/tools/publisher/Publisher.java b/src/main/java/org/hl7/fhir/tools/publisher/Publisher.java index 8f6db9c1..3196900d 100644 --- a/src/main/java/org/hl7/fhir/tools/publisher/Publisher.java +++ b/src/main/java/org/hl7/fhir/tools/publisher/Publisher.java @@ -235,11 +235,9 @@ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWIS import org.hl7.fhir.r5.renderers.ResourceRenderer; import org.hl7.fhir.r5.renderers.ResourceRenderer.RendererType; import org.hl7.fhir.r5.renderers.spreadsheets.StructureDefinitionSpreadsheetGenerator; -import org.hl7.fhir.r5.renderers.utils.BaseWrappers.ResourceWrapper; -import org.hl7.fhir.r5.renderers.utils.DOMWrappers; -import org.hl7.fhir.r5.renderers.utils.ElementWrappers; import org.hl7.fhir.r5.renderers.utils.RenderingContext; import org.hl7.fhir.r5.renderers.utils.RenderingContext.GenerationRules; +import org.hl7.fhir.r5.renderers.utils.ResourceWrapper; import org.hl7.fhir.r5.terminologies.CodeSystemUtilities; import org.hl7.fhir.r5.terminologies.ValueSetUtilities; import org.hl7.fhir.r5.terminologies.expansion.ValueSetExpansionOutcome; @@ -259,12 +257,12 @@ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWIS import org.hl7.fhir.tools.converters.DSTU3ValidationConvertor; import org.hl7.fhir.tools.converters.SpecNPMPackageGenerator; import org.hl7.fhir.tools.publisher.ExampleInspector.EValidationFailed; -import org.hl7.fhir.utilities.CSFile; -import org.hl7.fhir.utilities.CSFileInputStream; import org.hl7.fhir.utilities.CloseProtectedZipInputStream; import org.hl7.fhir.utilities.CommaSeparatedStringBuilder; import org.hl7.fhir.utilities.IniFile; import org.hl7.fhir.utilities.Logger.LogMessageType; +import org.hl7.fhir.utilities.filesystem.CSFile; +import org.hl7.fhir.utilities.filesystem.CSFileInputStream; import org.hl7.fhir.utilities.NDJsonWriter; import org.hl7.fhir.utilities.PathBuilder; import org.hl7.fhir.utilities.SIDUtilities; @@ -318,7 +316,7 @@ public enum ValidationMode { static ValidationMode fromCode(String v) { if (v == null) { - return NORMAL; + return NORMAL; } switch (v.toLowerCase()) { case "extended": return EXTENDED; @@ -800,8 +798,8 @@ public void execute(String folder, String[] args) throws IOException { loadValueSets1(); generateSCMaps(); - validate(); processProfiles(); + validate(); checkAllOk(); startValidation(); @@ -924,7 +922,7 @@ private void loadMappingExceptionsSchema(String folder) throws IOException { } } - private void checkOids() { + private void checkOids() throws FileNotFoundException, UnsupportedEncodingException, IOException, Exception { boolean allGood = true; for (CanonicalResource cr : page.getWorkerContext().fetchResourcesByType(CanonicalResource.class)) { if (page.isLocalResource(cr)) { @@ -1402,7 +1400,7 @@ private void processProfiles() throws Exception { page.getProfiles().see(r.getProfile(), page.packageInfo()); ResourceTableGenerator rtg = new ResourceTableGenerator(page.getFolders().dstDir, page, null, true, page.getVersion(), ""); r.getProfile().getText().setDiv(new XhtmlNode(NodeType.Element, "div")); - r.getProfile().getText().getDiv().getChildNodes().add(rtg.generate(r, "", false)); + r.getProfile().getText().getDiv().addChildNode(rtg.generate(r, "", false)); } for (String rn : page.getDefinitions().sortedResourceNames()) { @@ -1412,7 +1410,7 @@ private void processProfiles() throws Exception { page.getProfiles().see(r.getProfile(), page.packageInfo()); ResourceTableGenerator rtg = new ResourceTableGenerator(page.getFolders().dstDir, page, null, true, page.getVersion(), ""); r.getProfile().getText().setDiv(new XhtmlNode(NodeType.Element, "div")); - r.getProfile().getText().getDiv().getChildNodes().add(rtg.generate(r, "", false)); + r.getProfile().getText().getDiv().addChildNode(rtg.generate(r, "", false)); } for (ResourceDefn r : page.getDefinitions().getResourceTemplates().values()) { @@ -1420,7 +1418,7 @@ private void processProfiles() throws Exception { r.setProfile(new ProfileGenerator(page.getDefinitions(), page.getWorkerContext(), page, page.getGenDate(), page.getVersion(), dataElements, fpUsages, page.getFolders().rootDir, page.getUml(), page.getRc()).generate(r.getConformancePack(), r, "core", true)); ResourceTableGenerator rtg = new ResourceTableGenerator(page.getFolders().dstDir, page, null, true, page.getVersion(), ""); r.getProfile().getText().setDiv(new XhtmlNode(NodeType.Element, "div")); - r.getProfile().getText().getDiv().getChildNodes().add(rtg.generate(r, "", true)); + r.getProfile().getText().getDiv().addChildNode(rtg.generate(r, "", true)); page.getProfiles().see(r.getProfile(), page.packageInfo()); } @@ -1482,6 +1480,10 @@ private void processProfiles() throws Exception { } TextFile.stringToFile(b.toString(), Utilities.path(page.getFolders().dstDir, "fhirpaths.txt")); + for (StructureDefinition sd : page.getProfiles().getList()) { + page.getWorkerContext().cacheResource(sd); + } + checkAllOk(); } @@ -1546,7 +1548,7 @@ private void genXhtmlProfile() throws Exception { // DataTypeTableGenerator dtg = new DataTypeTableGenerator(page.getFolders().dstDir, page, t.getCode(), true); // t.setProfile(profile); // t.getProfile().getText().setDiv(new XhtmlNode(NodeType.Element, "div")); - // t.getProfile().getText().getDiv().getChildNodes().add(dtg.generate(t)); + // t.getProfile().getText().getDiv().addChildNode(dtg.generate(t)); } private void genPrimitiveTypeProfile(PrimitiveType t) throws Exception { @@ -1557,7 +1559,7 @@ private void genPrimitiveTypeProfile(PrimitiveType t) throws Exception { // DataTypeTableGenerator dtg = new DataTypeTableGenerator(page.getFolders().dstDir, page, t.getCode(), true); // t.setProfile(profile); // t.getProfile().getText().setDiv(new XhtmlNode(NodeType.Element, "div")); - // t.getProfile().getText().getDiv().getChildNodes().add(dtg.generate(t)); + // t.getProfile().getText().getDiv().addChildNode(dtg.generate(t)); } @@ -1568,7 +1570,7 @@ private void genPrimitiveTypeProfile(DefinedStringPattern t) throws Exception { // DataTypeTableGenerator dtg = new DataTypeTableGenerator(page.getFolders().dstDir, page, t.getCode(), true); // t.setProfile(profile); // t.getProfile().getText().setDiv(new XhtmlNode(NodeType.Element, "div")); - // t.getProfile().getText().getDiv().getChildNodes().add(dtg.generate(t)); + // t.getProfile().getText().getDiv().addChildNode(dtg.generate(t)); } @@ -1580,7 +1582,7 @@ private void genTypeProfile(TypeDefn t) throws Exception { t.setProfile(profile); DataTypeTableGenerator dtg = new DataTypeTableGenerator(page.getFolders().dstDir, page, t.getName(), true, page.getVersion(), ""); t.getProfile().getText().setDiv(new XhtmlNode(NodeType.Element, "div")); - t.getProfile().getText().getDiv().getChildNodes().add(dtg.generate(t, null, false)); + t.getProfile().getText().getDiv().addChildNode(dtg.generate(t, null, false)); } catch (Exception e) { throw new Exception("Error generating profile for '"+t.getName()+"': "+e.getMessage(), e); } @@ -2198,8 +2200,8 @@ private void generateCompartmentDefinition(Compartment c) throws Exception { } } cpd.setWebPath("compartmentdefinition-"+c.getName()+".html"); - RenderingContext lrc = page.getRc().copy().setLocalPrefix(""); - RendererFactory.factory(cpd, lrc).render(cpd); + RenderingContext lrc = page.getRc().copy(false).setLocalPrefix(""); + RendererFactory.factory(cpd, lrc).renderResource(ResourceWrapper.forResource(lrc.getContextUtilities(), cpd)); serializeResource(cpd, "compartmentdefinition-" + c.getName().toLowerCase(), "Compartment Definition for "+c.getName(), "resource-instance:CompartmentDefinition", wg("fhir")); Utilities.copyFile(new CSFile(page.getFolders().dstDir + "compartmentdefinition-" + c.getName().toLowerCase() + ".xml"), new CSFile(page.getFolders().dstDir + "examples" + File.separator @@ -2346,9 +2348,9 @@ private void generateConformanceStatement(boolean full, String name, boolean reg } if (register) { - RenderingContext lrc = page.getRc().copy().setLocalPrefix(""); + RenderingContext lrc = page.getRc().copy(false).setLocalPrefix(""); lrc.setRules(GenerationRules.VALID_RESOURCE); - RendererFactory.factory(cpbs, lrc).render(cpbs); + RendererFactory.factory(cpbs, lrc).renderResource(ResourceWrapper.forResource(lrc.getContextUtilities(), cpbs)); String fName = "capabilitystatement-" + name; fixCanonicalResource(cpbs, fName); serializeResource(cpbs, fName, "Base Capability Statement", "resource-instance:CapabilityStatement", wg("fhir")); @@ -2357,9 +2359,9 @@ private void generateConformanceStatement(boolean full, String name, boolean reg + "capabilitystatement-" + name + ".xml")); } if (buildFlags.get("all")) { - RenderingContext lrc = page.getRc().copy().setLocalPrefix(""); + RenderingContext lrc = page.getRc().copy(false).setLocalPrefix(""); lrc.setRules(GenerationRules.VALID_RESOURCE); - RendererFactory.factory(cpbs, lrc).render(cpbs); + RendererFactory.factory(cpbs, lrc).renderResource(ResourceWrapper.forResource(lrc.getContextUtilities(), cpbs)); deletefromFeed(ResourceType.CapabilityStatement, name, page.getResourceBundle()); addToResourceFeed(cpbs, page.getResourceBundle()); } @@ -2661,34 +2663,34 @@ private boolean wantBuild(String rname) { private void checkExampleLinks(List errors, ResourceDefn r) throws Exception { for (Example e : r.getExamples()) { try { - if (e.getXml() != null) { + if (e.getElement() != null) { List refs = new ArrayList(); - listLinks(e.getXml().getDocumentElement(), refs); - for (ExampleReference ref : refs) { - if (!ref.isExempt() && !resolveLink(ref, e)) { - String path = ref.getPath().replace("/f:", ".").substring(1)+" (example "+e.getTitle()+")"; - if (ref.hasType() && page.getDefinitions().hasResource(ref.getType())) { - errors.add(new ValidationMessage(Source.ExampleValidator, IssueType.BUSINESSRULE, -1, -1, path, - "Unable to resolve example reference to " + ref.getRef() + " in " + e.getTitle() + " (Possible Ids: " + listTargetIds(ref.getType())+")", - "Unable to resolve example reference to " + ref.getRef() + " in " + e.getTitle() + " (Possible Ids: " + listTargetIds(ref.getType())+")", - IssueSeverity.INFORMATION/*WARNING*/)); - } else { - String regex = "((http|https)://([A-Za-z0-9\\\\\\/\\.\\:\\%\\$])*)?("+page.pipeResources()+")\\/"+FormatUtilities.ID_REGEX+"(\\/_history\\/"+FormatUtilities.ID_REGEX+")?"; - if (ref.getRef().matches(regex)) { - errors.add(new ValidationMessage(Source.ExampleValidator, IssueType.BUSINESSRULE, -1, -1, path, - "Unable to resolve example reference " + ref.getRef() + " in " + e.getTitle(), - "Unable to resolve example reference " + ref.getRef() + " in " + e.getTitle() + "", - IssueSeverity.INFORMATION/*WARNING*/)); - } else { - errors.add(new ValidationMessage(Source.ExampleValidator, IssueType.BUSINESSRULE, -1, -1, path, - "Unable to resolve invalid example reference " + ref.getRef() + " in " + e.getTitle(), - "Unable to resolve invalid example reference " + ref.getRef() + " in " + e.getTitle() + "", - IssueSeverity.WARNING)); - } - } -// System.out.println("unresolved reference "+ref.getRef()+" at "+path); - } - } + listLinks(e.getElement(), refs); +// for (ExampleReference ref : refs) { +// if (!ref.isExempt() && !resolveLink(ref, e)) { +// String path = ref.getPath().replace("/f:", ".").substring(1)+" (example "+e.getTitle()+")"; +// if (ref.hasType() && page.getDefinitions().hasResource(ref.getType())) { +// errors.add(new ValidationMessage(Source.ExampleValidator, IssueType.BUSINESSRULE, -1, -1, path, +// "Unable to resolve example reference to " + ref.getRef() + " in " + e.getTitle() + " (Possible Ids: " + listTargetIds(ref.getType())+")", +// "Unable to resolve example reference to " + ref.getRef() + " in " + e.getTitle() + " (Possible Ids: " + listTargetIds(ref.getType())+")", +// IssueSeverity.INFORMATION/*WARNING*/)); +// } else { +// String regex = "((http|https)://([A-Za-z0-9\\\\\\/\\.\\:\\%\\$])*)?("+page.pipeResources()+")\\/"+FormatUtilities.ID_REGEX+"(\\/_history\\/"+FormatUtilities.ID_REGEX+")?"; +// if (ref.getRef().matches(regex)) { +// errors.add(new ValidationMessage(Source.ExampleValidator, IssueType.BUSINESSRULE, -1, -1, path, +// "Unable to resolve example reference " + ref.getRef() + " in " + e.getTitle(), +// "Unable to resolve example reference " + ref.getRef() + " in " + e.getTitle() + "", +// IssueSeverity.INFORMATION/*WARNING*/)); +// } else { +// errors.add(new ValidationMessage(Source.ExampleValidator, IssueType.BUSINESSRULE, -1, -1, path, +// "Unable to resolve invalid example reference " + ref.getRef() + " in " + e.getTitle(), +// "Unable to resolve invalid example reference " + ref.getRef() + " in " + e.getTitle() + "", +// IssueSeverity.WARNING)); +// } +// } +//// System.out.println("unresolved reference "+ref.getRef()+" at "+path); +// } +// } } } catch (Exception ex) { throw new Exception("Error checking example " + e.getTitle() + ":" + ex.getMessage(), ex); @@ -2696,159 +2698,159 @@ private void checkExampleLinks(List errors, ResourceDefn r) t } } - private String listTargetIds(String type) throws Exception { - StringBuilder b = new StringBuilder(); - ResourceDefn r = page.getDefinitions().getResourceByName(type); - if (r != null) { - for (Example e : r.getExamples()) { - if (!Utilities.noString(e.getId())) - b.append(e.getId()).append(", "); - if (e.getXml() != null) { - if (e.getXml().getDocumentElement().getLocalName().equals("feed")) { - List entries = new ArrayList(); - XMLUtil.getNamedChildren(e.getXml().getDocumentElement(), "entry", entries); - for (Element c : entries) { - String id = XMLUtil.getNamedChild(c, "id").getTextContent(); - if (id.startsWith("http://hl7.org/fhir/") && id.contains("@")) - b.append(id.substring(id.indexOf("@") + 1)).append(", "); - else - b.append(id).append(", "); - } - } - } - } - } else - b.append("(unknown resource type)"); - return b.toString(); - } - - private boolean resolveLink(ExampleReference ref, Example src) throws Exception { - if (!ref.hasType() && ref.getId() == null) - return false; - if (!ref.hasType() && ref.getId().startsWith("#")) - return true; - if (!ref.hasType() || !page.getDefinitions().hasResource(ref.getType())) - return false; - if (ref.getId().startsWith("#")) - return false; - String id = ref.getId(); - ResourceDefn r = page.getDefinitions().getResourceByName(ref.getType()); - for (Example e : r.getExamples()) { - if (id.equals(e.getId())) { - e.getInbounds().add(src); - return true; - } - if (e.getXml() != null) { - if (resolveLinkInBundle(ref, src, e, id)) - return true; - } - } - // didn't find it? well, we'll look through all the other examples looking for bundles that contain it - for (ResourceDefn rt : page.getDefinitions().getResources().values()) { - for (Example e : rt.getExamples()) { - if (e.getXml() != null) { - if (resolveLinkInBundle(ref, src, e, id)) - return true; - } - } - } - // still not found? - if (ref.type.equals("ConceptMap")) - return page.getConceptMaps().has("http://hl7.org/fhir/"+ref.type+"/"+ref.getId()); - if (ref.type.equals("StructureDefinition")) { - if (page.getDefinitions().hasResource(ref.getId())) - return true; - if (page.getProfiles().has("http://hl7.org/fhir/"+ref.type+"/"+ref.getId()) || page.getWorkerContext().hasResource(StructureDefinition.class, "http://hl7.org/fhir/"+ref.type+"/"+ref.getId())) - return true; - for (Profile cp : page.getDefinitions().getPackList()) - for (ConstraintStructure p : cp.getProfiles()) - if (p.getId().equals(id)) - return true; - for (ResourceDefn rd : page.getDefinitions().getResources().values()) - for (Profile cp : rd.getConformancePackages()) - for (ConstraintStructure p : cp.getProfiles()) - if (p.getId().equals(id)) - return true; - } - if (page.getWorkerContext().hasResource(Resource.class, ref.ref)) { - return true; - } - return false; - } - - private boolean resolveLinkInBundle(ExampleReference ref, Example src, Example e, String id) { - if (e.getXml().getDocumentElement().getLocalName().equals("Bundle")) { - List entries = new ArrayList(); - XMLUtil.getNamedChildren(e.getXml().getDocumentElement(), "entry", entries); - for (Element c : entries) { - Element resh = XMLUtil.getNamedChild(c, "resource"); - if (resh != null) { - Element res = XMLUtil.getFirstChild(resh); - String _id = XMLUtil.getNamedChildValue(res, "id"); - if (id.equals(_id) && ref.getType().equals(res.getLocalName())) { - e.getInbounds().add(src); - return true; - } - } - } - } - return false; - } +// private String listTargetIds(String type) throws Exception { +// StringBuilder b = new StringBuilder(); +// ResourceDefn r = page.getDefinitions().getResourceByName(type); +// if (r != null) { +// for (Example e : r.getExamples()) { +// if (!Utilities.noString(e.getId())) +// b.append(e.getId()).append(", "); +// if (e.getXml() != null) { +// if (e.getXml().getDocumentElement().getLocalName().equals("feed")) { +// List entries = new ArrayList(); +// XMLUtil.getNamedChildren(e.getXml().getDocumentElement(), "entry", entries); +// for (Element c : entries) { +// String id = XMLUtil.getNamedChild(c, "id").getTextContent(); +// if (id.startsWith("http://hl7.org/fhir/") && id.contains("@")) +// b.append(id.substring(id.indexOf("@") + 1)).append(", "); +// else +// b.append(id).append(", "); +// } +// } +// } +// } +// } else +// b.append("(unknown resource type)"); +// return b.toString(); +// } - private void listLinks(Element xml, List refs) throws Exception { - if (xml.getLocalName().equals("feed")) { - Element n = XMLUtil.getFirstChild(xml); - while (n != null) { - if (n.getLocalName().equals("entry")) { - Element c = XMLUtil.getNamedChild(n, "content"); - listLinks(XMLUtil.getFirstChild(c), refs); - } - n = XMLUtil.getNextSibling(n); - } - } else { - String n = xml.getLocalName(); - if (!n.equals("Binary")) { - ResourceDefn r = page.getDefinitions().getResourceByName(n); - if (r == null) - throw new Exception("Unable to find resource definition for " + n); - List nodes = new ArrayList(); - nodes.add(xml); - listLinks("/f:" + n, r.getRoot(), nodes, refs); - - Element e = XMLUtil.getFirstChild(xml); - while (e != null) { - if (e.getNodeName().equals("contained")) { - listLinks(XMLUtil.getFirstChild(e), refs); - } - e = XMLUtil.getNextSibling(e); - } +// private boolean resolveLink(ExampleReference ref, Example src) throws Exception { +// if (!ref.hasType() && ref.getId() == null) +// return false; +// if (!ref.hasType() && ref.getId().startsWith("#")) +// return true; +// if (!ref.hasType() || !page.getDefinitions().hasResource(ref.getType())) +// return false; +// if (ref.getId().startsWith("#")) +// return false; +// String id = ref.getId(); +// ResourceDefn r = page.getDefinitions().getResourceByName(ref.getType()); +// for (Example e : r.getExamples()) { +// if (id.equals(e.getId())) { +// e.getInbounds().add(src); +// return true; +// } +// if (e.getXml() != null) { +// if (resolveLinkInBundle(ref, src, e, id)) +// return true; +// } +// } +// // didn't find it? well, we'll look through all the other examples looking for bundles that contain it +// for (ResourceDefn rt : page.getDefinitions().getResources().values()) { +// for (Example e : rt.getExamples()) { +// if (e.getXml() != null) { +// if (resolveLinkInBundle(ref, src, e, id)) +// return true; +// } +// } +// } +// // still not found? +// if (ref.type.equals("ConceptMap")) +// return page.getConceptMaps().has("http://hl7.org/fhir/"+ref.type+"/"+ref.getId()); +// if (ref.type.equals("StructureDefinition")) { +// if (page.getDefinitions().hasResource(ref.getId())) +// return true; +// if (page.getProfiles().has("http://hl7.org/fhir/"+ref.type+"/"+ref.getId()) || page.getWorkerContext().hasResource(StructureDefinition.class, "http://hl7.org/fhir/"+ref.type+"/"+ref.getId())) +// return true; +// for (Profile cp : page.getDefinitions().getPackList()) +// for (ConstraintStructure p : cp.getProfiles()) +// if (p.getId().equals(id)) +// return true; +// for (ResourceDefn rd : page.getDefinitions().getResources().values()) +// for (Profile cp : rd.getConformancePackages()) +// for (ConstraintStructure p : cp.getProfiles()) +// if (p.getId().equals(id)) +// return true; +// } +// if (page.getWorkerContext().hasResource(Resource.class, ref.ref)) { +// return true; +// } +// return false; +// } - } - } - } +// private boolean resolveLinkInBundle(ExampleReference ref, Example src, Example e, String id) { +// if (e.getXml().getDocumentElement().getLocalName().equals("Bundle")) { +// List entries = new ArrayList(); +// XMLUtil.getNamedChildren(e.getXml().getDocumentElement(), "entry", entries); +// for (Element c : entries) { +// Element resh = XMLUtil.getNamedChild(c, "resource"); +// if (resh != null) { +// Element res = XMLUtil.getFirstChild(resh); +// String _id = XMLUtil.getNamedChildValue(res, "id"); +// if (id.equals(_id) && ref.getType().equals(res.getLocalName())) { +// e.getInbounds().add(src); +// return true; +// } +// } +// } +// } +// return false; +// } - private void listLinks(String path, org.hl7.fhir.definitions.model.ElementDefn d, List set, List refs) throws Exception { - if (d.typeCode().startsWith("Reference")) { - for (Element m : set) { - if (XMLUtil.getNamedChild(m, "reference") != null) { - refs.add(new ExampleReference(XMLUtil.getNamedChildValue(m, "reference"), path)); - } - } - } - if (d.typeCode().startsWith("canonical")) { - for (Element m : set) { - if (!Utilities.noString(m.getAttribute("value"))) { - refs.add(new ExampleReference(m.getAttribute("value"), path)); - } - } - } - for (org.hl7.fhir.definitions.model.ElementDefn c : d.getElements()) { - List cset = new ArrayList(); - for (Element p : set) - XMLUtil.getNamedChildren(p, c.getName(), cset); - listLinks(path + "/f:" + c.getName(), c, cset, refs); - } + private void listLinks(org.hl7.fhir.r5.elementmodel.Element element, List refs) throws Exception { +// if (element.getLocalName().equals("feed")) { +// Element n = XMLUtil.getFirstChild(element); +// while (n != null) { +// if (n.getLocalName().equals("entry")) { +// Element c = XMLUtil.getNamedChild(n, "content"); +// listLinks(XMLUtil.getFirstChild(c), refs); +// } +// n = XMLUtil.getNextSibling(n); +// } +// } else { +// String n = element.getLocalName(); +// if (!n.equals("Binary")) { +// ResourceDefn r = page.getDefinitions().getResourceByName(n); +// if (r == null) +// throw new Exception("Unable to find resource definition for " + n); +// List nodes = new ArrayList(); +// nodes.add(element); +// listLinks("/f:" + n, r.getRoot(), nodes, refs); +// +// Element e = XMLUtil.getFirstChild(element); +// while (e != null) { +// if (e.getNodeName().equals("contained")) { +// listLinks(XMLUtil.getFirstChild(e), refs); +// } +// e = XMLUtil.getNextSibling(e); +// } +// +// } +// } } +// +// private void listLinks(String path, org.hl7.fhir.definitions.model.ElementDefn d, List set, List refs) throws Exception { +// if (d.typeCode().startsWith("Reference")) { +// for (Element m : set) { +// if (XMLUtil.getNamedChild(m, "reference") != null) { +// refs.add(new ExampleReference(XMLUtil.getNamedChildValue(m, "reference"), path)); +// } +// } +// } +// if (d.typeCode().startsWith("canonical")) { +// for (Element m : set) { +// if (!Utilities.noString(m.getAttribute("value"))) { +// refs.add(new ExampleReference(m.getAttribute("value"), path)); +// } +// } +// } +// for (org.hl7.fhir.definitions.model.ElementDefn c : d.getElements()) { +// List cset = new ArrayList(); +// for (Element p : set) +// XMLUtil.getNamedChildren(p, c.getName(), cset); +// listLinks(path + "/f:" + c.getName(), c, cset, refs); +// } +// } // private List xPathQuery(String path, Element e) throws Exception { // NamespaceContext context = new NamespaceContextMap("f", @@ -3699,8 +3701,8 @@ private void produceUml() throws IOException { } private void produceConceptMap(ConceptMap cm, ResourceDefn rd, SectionTracker st) throws Exception { - RenderingContext lrc = page.getRc().copy().setLocalPrefix(""); - RendererFactory.factory(cm, lrc).render(cm); + RenderingContext lrc = page.getRc().copy(false).setLocalPrefix(""); + RendererFactory.factory(cm, lrc).renderResource(ResourceWrapper.forResource(lrc.getContextUtilities(), cm)); String n = cm.getWebPath(); String fName = Utilities.changeFileExt(n,""); fixCanonicalResource(cm, fName); @@ -4348,7 +4350,7 @@ private void produceExtensionDefinition(StructureDefinition ed) throws FileNotFo } } - private String getExtensionExamples(StructureDefinition ed) { + private String getExtensionExamples(StructureDefinition ed) throws FileNotFoundException, UnsupportedEncodingException, IOException, Exception { List refs = new ArrayList<>(); for (CanonicalResource cr : page.getWorkerContext().fetchResourcesByType(CanonicalResource.class)) { if (ToolingExtensions.usesExtension(ed.getUrl(), cr) && page.isLocalResource(cr)) { @@ -4359,7 +4361,7 @@ private String getExtensionExamples(StructureDefinition ed) { for (String rn : page.getDefinitions().sortedResourceNames()) { ResourceDefn rd = page.getDefinitions().getResourceByName(rn); for (Example e : rd.getExamples()) { - if (usesExtension(ed.getUrl(), e.getXml())) { + if (usesExtension(ed.getUrl(), e.getElement())) { refs.add(new StringPair(e.getName()+": "+rd.getName()+"/"+e.getId(), e.getTitle()+".html")); } } @@ -4378,26 +4380,16 @@ private String getExtensionExamples(StructureDefinition ed) { } } - - - private boolean usesExtension(String url, Document xml) { - if (xml == null) { - return false; - } - Element e = xml.getDocumentElement(); - return usesExtension(url, e); - } - - private boolean usesExtension(String url, Element e) { - if (url.equals(e.getAttribute("url"))) { + private boolean usesExtension(String url, org.hl7.fhir.r5.elementmodel.Element element) { + if ("Extension".equals(element.fhirType()) && url.equals(element.getNamedChildValue("url"))) { return true; } - Element c = XMLUtil.getFirstChild(e); - while (c != null) { - if (usesExtension(url, c)) { - return true; + if (element.hasChildren()) { + for (org.hl7.fhir.r5.elementmodel.Element c : element.getChildren()) { + if (usesExtension(url, c)) { + return true; + } } - c = XMLUtil.getNextSibling(c); } return false; } @@ -4824,6 +4816,7 @@ private void produceResource2(ResourceDefn resource, boolean isAbstract, String } } } + src = TextFile.fileToString(page.getFolders().templateDir + template+"-definitions.html"); TextFile.stringToFile( insertSectionNumbers(page.processResourceIncludes(n, resource, xml, json, ttl, tx, dict, src, mappings, mappingsList, "res-Detailed Descriptions", n + "-definitions.html", null, values, resource.getWg(), null), st, n @@ -4923,7 +4916,7 @@ private void produceResource2(ResourceDefn resource, boolean isAbstract, String doc.appendChild(element); page.getDiffEngine().getDiffAsXml(doc, element, p, false); prettyPrint(doc, Utilities.path(page.getFolders().dstDir, resource.getName().toLowerCase() + ".r4b.diff.xml")); -} + } public void prettyPrint(Document xml, String filename) throws Exception { Transformer tf = TransformerFactory.newInstance().newTransformer(); @@ -5123,40 +5116,33 @@ private String loadHtmlForm(String path) throws Exception { private void processExample(Example e, ResourceDefn resn, StructureDefinition profile, Profile pack, ImplementationGuideDefn ig) throws Exception { if (e.getType() == ExampleType.Tool) return; - long time = System.currentTimeMillis(); +// long time = System.currentTimeMillis(); int level = (ig == null || ig.isCore()) ? 0 : 1; String prefix = (ig == null || ig.isCore()) ? "" : ig.getCode() + File.separator; - - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setNamespaceAware(true); - DocumentBuilder builder = factory.newDocumentBuilder(); - Document xdoc; String narrative = null; String n = e.getTitle(); - if (examplesProcessed.contains(prefix+n)) + if (examplesProcessed.contains(prefix+n)) { return; + } examplesProcessed.add(prefix+n); // strip the xsi: stuff. seems to need double processing in order to // delete namespace crap - xdoc = e.getXml(); - - CanonicalResourceUtilities.setHl7WG(xdoc.getDocumentElement(), resn.getWg().getCode()); + + CanonicalResourceUtilities.setHl7WG(e.getElement(), resn.getWg().getCode()); XmlGenerator xmlgen = new XmlGenerator(); CSFile file = new CSFile(page.getFolders().dstDir + prefix +n + ".xml"); - xmlgen.generate(xdoc.getDocumentElement(), file, "http://hl7.org/fhir", xdoc.getDocumentElement() - .getLocalName()); + Manager.compose(page.getWorkerContext(), e.getElement(), new FileOutputStream(file), FhirFormat.XML, OutputStyle.PRETTY, "http://hl7.org/fhir"); // check the narrative. We generate auto-narrative. If the resource didn't // have it's own original narrative, then we save it anyway // n String rt = null; try { - RenderingContext lrc = page.getRc().copy().setLocalPrefix(""); - xdoc = loadDom(new FileInputStream(file), true); - rt = xdoc.getDocumentElement().getNodeName(); - String id = XMLUtil.getNamedChildValue(xdoc.getDocumentElement(), "id"); + RenderingContext lrc = page.getRc().copy(false).setLocalPrefix(""); + rt = e.getElement().fhirType(); + String id = e.getElement().getIdBase(); if (!page.getDefinitions().getBaseResources().containsKey(rt) && !id.equals(e.getId())) throw new Error("Resource in "+prefix +n + ".xml needs an id of value=\""+e.getId()+"\""); page.getDefinitions().addNs("http://hl7.org/fhir/"+rt+"/"+id, "Example", prefix +n + ".html"); @@ -5182,7 +5168,7 @@ private void processExample(Example e, ResourceDefn resn, StructureDefinition pr wantSave = updateVersion(((CapabilityStatement) res).getText().getDiv()); } if (!res.hasText() || !res.getText().hasDiv()) { - RendererFactory.factory(res, lrc.copy().setRules(GenerationRules.VALID_RESOURCE)).render(res); + RendererFactory.factory(res, lrc.copy(false).setRules(GenerationRules.VALID_RESOURCE)).renderResource(ResourceWrapper.forResource(lrc.getContextUtilities(), res)); } if (wantSave) { if (VersionUtilities.isR4BVer(page.getVersion().toCode())) { @@ -5195,27 +5181,26 @@ private void processExample(Example e, ResourceDefn resn, StructureDefinition pr narrative = new XhtmlComposer(XhtmlComposer.HTML).compose(res.getText().getDiv()); } else { if (rt.equals("Bundle")) { - List entries = new ArrayList(); - XMLUtil.getNamedChildren(xdoc.getDocumentElement(), "entry", entries); + List entries = e.getElement().getChildren("entry"); boolean wantSave = false; - for (Element entry : entries) { - Element ers = XMLUtil.getFirstChild(XMLUtil.getNamedChild(entry, "resource")); + for (org.hl7.fhir.r5.elementmodel.Element entry : entries) { + org.hl7.fhir.r5.elementmodel.Element ers = entry.getNamedChild("resource"); if (ers != null) { CanonicalResourceUtilities.setHl7WG(ers, resn.getWg().getCode()); } - id = XMLUtil.getNamedChildValue(ers, "id"); + id = ers == null ? null : ers.getIdBase(); if (id != null) - page.getDefinitions().addNs("http://hl7.org/fhir/"+ers.getLocalName()+"/"+id, "Example", prefix +n + ".html", true); + page.getDefinitions().addNs("http://hl7.org/fhir/"+ers.fhirType()+"/"+id, "Example", prefix +n + ".html", true); if (ers != null) { - String ert = ers.getLocalName(); + String ert = ers.fhirType(); String s = null; if (!page.getDefinitions().getBaseResources().containsKey(ert) && !ert.equals("Binary") && !ert.equals("Parameters") && !ert.equals("Bundle")) { - ResourceRenderer r = RendererFactory.factory(ers.getLocalName(), lrc); - ResourceWrapper rw = new DOMWrappers.ResourceWrapperElement(lrc, ers, page.getDefinitions().getResourceByName(ers.getLocalName()).getProfile()); + ResourceRenderer r = RendererFactory.factory(ers.fhirType(), lrc); + ResourceWrapper rw =ResourceWrapper.forResource(lrc.getContextUtilities(), ers); XhtmlNode div = rw.getNarrative(); if (div == null || div.isEmpty()) { wantSave = true; - r.render(rw); + r.renderResource(rw); } else s = new XhtmlComposer(true).compose(div); if (s != null) @@ -5223,7 +5208,7 @@ private void processExample(Example e, ResourceDefn resn, StructureDefinition pr } if (ert.equals("NamingSystem")) { ByteArrayOutputStream bs = new ByteArrayOutputStream(); - new XmlGenerator().generate(ers, bs); + Manager.compose(page.getWorkerContext(), ers, bs, FhirFormat.XML, OutputStyle.PRETTY, "http://hl7.org/fhir"); bs.close(); NamingSystem ns = (NamingSystem) new XmlParser().parse(new ByteArrayInputStream(bs.toByteArray())); if (!ns.hasUrl() || ns.getUrl().startsWith("http://hl7.org/fhir")) @@ -5234,38 +5219,23 @@ private void processExample(Example e, ResourceDefn resn, StructureDefinition pr } } } - if (wantSave) - new XmlGenerator().generate(xdoc.getDocumentElement(), file, "http://hl7.org/fhir", xdoc.getDocumentElement().getLocalName()); + if (wantSave) { + Manager.compose(page.getWorkerContext(), e.getElement(), new FileOutputStream(file), FhirFormat.XML, OutputStyle.PRETTY, "http://hl7.org/fhir"); + } } else { if (!page.getDefinitions().getBaseResources().containsKey(rt) && !rt.equals("Binary") && !rt.equals("Parameters")) { - - ResourceRenderer r = RendererFactory.factory(xdoc.getDocumentElement().getLocalName(), lrc); - - if (r.getRendererType() == RendererType.LIQUID) { - // really, we could do everything this way, but this change was introduced close to ballot, so we only do it when we're doing liquid. To be reviewed - org.hl7.fhir.r5.elementmodel.Element ex = e.getElement(); - if (ex == null) { - e.setElement(new org.hl7.fhir.r5.elementmodel.XmlParser(page.getWorkerContext()).parse(null, e.getXml())); - ex = e.getElement(); - } - CanonicalResourceUtilities.setHl7WG(ex, resn.getWg().getCode()); - ResourceWrapper rw = new ElementWrappers.ResourceWrapperMetaElement(lrc, ex); - XhtmlNode div = rw.getNarrative(); - if (div == null || div.isEmpty()) { - narrative = new XhtmlComposer(true).compose(r.render(rw)); - new org.hl7.fhir.r5.elementmodel.XmlParser(page.getWorkerContext()).compose(ex, new FileOutputStream(file), OutputStyle.PRETTY, null); - } else { - narrative = new XhtmlComposer(true).compose(div); - } - } else { - ResourceWrapper rw = new DOMWrappers.ResourceWrapperElement(lrc, xdoc.getDocumentElement(), page.getDefinitions().getResourceByName(xdoc.getDocumentElement().getLocalName()).getProfile()); - XhtmlNode div = rw.getNarrative(); - if (div == null || div.isEmpty()) { - narrative = new XhtmlComposer(true).compose(r.render(rw)); - new XmlGenerator().generate(xdoc.getDocumentElement(), file, "http://hl7.org/fhir", xdoc.getDocumentElement().getLocalName()); - } else { - narrative = new XhtmlComposer(true).compose(div); - } + + ResourceRenderer r = RendererFactory.factory(ResourceWrapper.forResource(lrc.getContextUtilities(), e.getElement()), lrc); + + CanonicalResourceUtilities.setHl7WG(e.getElement(), resn.getWg().getCode()); + ResourceWrapper rw = ResourceWrapper.forResource(lrc.getContextUtilities(), e.getElement()); + XhtmlNode div = rw.getNarrative(); + if (div == null || div.isEmpty()) { + narrative = new XhtmlComposer(true).compose(r.buildNarrative(rw)); + new org.hl7.fhir.r5.elementmodel.XmlParser(page.getWorkerContext()).compose(e.getElement(), new FileOutputStream(file), OutputStyle.PRETTY, null); + } else { + narrative = new XhtmlComposer(true).compose(div); + } } } @@ -5279,15 +5249,6 @@ private void processExample(Example e, ResourceDefn resn, StructureDefinition pr xhtml.addTag("p").setAttribute("style", "color: maroon").addText(errors.toString()); narrative = new XhtmlComposer(XhtmlComposer.HTML).compose(xhtml); } - try { - if (e.getResource() == null && e.getElement() == null) { - String xml = XMLUtil.elementToString(e.getXml().getDocumentElement()).replace("", "").trim(); - e.setElement(new Manager().parseSingle(page.getWorkerContext(), new StringInputStream(xml), FhirFormat.XML)); - e.setResource(new XmlParser().parse(xml)); - } - } catch (Throwable ex) { - System.out.println("Error reparsing example "+e.getName()+": "+ex.getMessage()); - } if (rt.equals("ValueSet")) { try { ValueSet vs = (ValueSet) loadExample(file); @@ -5397,8 +5358,11 @@ private void processExample(Example e, ResourceDefn resn, StructureDefinition pr page.getHTMLChecker().registerExternal(prefix+n + ".ttl.html"); // reload it now, xml to xhtml of xml - builder = factory.newDocumentBuilder(); - xdoc = builder.parse(new CSFileInputStream(file)); + + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(true); + DocumentBuilder builder = factory.newDocumentBuilder(); + Document xdoc = builder.parse(new CSFileInputStream(file)); XhtmlGenerator xhtml = new XhtmlGenerator(new ExampleAdorner(page.getDefinitions(), page.genlevel(level))); ByteArrayOutputStream b = new ByteArrayOutputStream(); xhtml.generate(xdoc, b, n.toUpperCase().substring(0, 1) + n.substring(1), Utilities.noString(e.getId()) ? e.getDescription() : e.getDescription() @@ -5419,7 +5383,7 @@ private void processExample(Example e, ResourceDefn resn, StructureDefinition pr else { Element pid = XMLUtil.getNextSibling(id); if (pid == null) - throw new Exception("not handled - id is last child in "+n); + meta = XMLUtil.addChild(xdoc, root, "meta", FormatUtilities.FHIR_NS, 2); else meta = XMLUtil.insertChild(xdoc, root, "meta", FormatUtilities.FHIR_NS, pid, 2); } @@ -5620,7 +5584,7 @@ private void saveAsPureHtml(DomainResource resource, FileOutputStream stream, bo work = doc.addTag("body"); if ((resource.hasText()) && (resource.getText().hasDiv())) { work.getAttributes().putAll(resource.getText().getDiv().getAttributes()); - work.getChildNodes().addAll(resource.getText().getDiv().getChildNodes()); + work.addChildNodes(resource.getText().getDiv().getChildNodes()); } XhtmlComposer xml = new XhtmlComposer(XhtmlComposer.HTML, isPretty); xml.compose(stream, html); @@ -5638,7 +5602,7 @@ private void addToResourceFeed(DomainResource resource, Bundle dest, String file ResourceUtilities.meta(resource).setLastUpdated(page.getGenDate().getTime()); if (!resource.hasText() || !resource.getText().hasDiv()) { - RendererFactory.factory(resource, page.getRc().copy()).render(resource); + RendererFactory.factory(resource, page.getRc().copy(false)).renderResource(ResourceWrapper.forResource(page.getRc().getContextUtilities(), resource)); } if (resource.getText() == null || resource.getText().getDiv() == null) throw new Exception("Example Resource " + resource.getId() + " does not have any narrative"); @@ -5661,7 +5625,7 @@ private void addToResourceFeed(ValueSet vs, Bundle dest, String filename) throws throw new Exception("Attempt to add duplicate value set " + vs.getId()+" ("+vs.getName()+")"); } if (!vs.hasText() || !vs.getText().hasDiv()) { - RendererFactory.factory(vs, page.getRc().copy()).render(vs); + RendererFactory.factory(vs, page.getRc().copy(false)).renderResource(ResourceWrapper.forResource(page.getRc().getContextUtilities(), vs)); } if (!vs.hasText() || vs.getText().getDiv() == null) throw new Exception("Example Value Set " + vs.getId() + " does not have any narrative"); @@ -5678,7 +5642,7 @@ private void addToResourceFeed(ConceptMap cm, Bundle dest) throws Exception { if (ResourceUtilities.getById(dest, ResourceType.ValueSet, cm.getId()) != null) throw new Exception("Attempt to add duplicate Concept Map " + cm.getId()); if (!cm.hasText() || !cm.getText().hasDiv()) { - RendererFactory.factory(cm, page.getRc().copy()).render(cm); + RendererFactory.factory(cm, page.getRc().copy(false)).renderResource(ResourceWrapper.forResource(page.getRc().getContextUtilities(), cm)); } if (cm.getText() == null || cm.getText().getDiv() == null) throw new Exception("Example Concept Map " + cm.getId() + " does not have any narrative"); @@ -5695,7 +5659,7 @@ private void addToResourceFeed(CompartmentDefinition cd, Bundle dest) throws Exc if (ResourceUtilities.getById(dest, ResourceType.CompartmentDefinition, cd.getId()) != null) throw new Exception("Attempt to add duplicate Compartment Definition " + cd.getId()); if (!cd.hasText() || !cd.getText().hasDiv()) { - RendererFactory.factory(cd, page.getRc().copy()).render(cd); + RendererFactory.factory(cd, page.getRc().copy(false)).renderResource(ResourceWrapper.forResource(page.getRc().getContextUtilities(), cd)); } if (cd.getText() == null || cd.getText().getDiv() == null) throw new Exception("Example Compartment Definition " + cd.getId() + " does not have any narrative"); @@ -5712,7 +5676,7 @@ private void addToResourceFeed(CapabilityStatement cs, Bundle dest) throws Excep if (ResourceUtilities.getById(dest, ResourceType.ValueSet, cs.getId()) != null) throw new Exception("Attempt to add duplicate Conformance " + cs.getId()); if (!cs.hasText() || !cs.getText().hasDiv()) { - RendererFactory.factory(cs, page.getRc().copy()).render(cs); + RendererFactory.factory(cs, page.getRc().copy(false)).renderResource(ResourceWrapper.forResource(page.getRc().getContextUtilities(),cs)); } if (!cs.hasText() || cs.getText().getDiv() == null) System.out.println("WARNING: Example CapabilityStatement " + cs.getId() + " does not have any narrative"); @@ -6795,8 +6759,8 @@ private void generateIGValueSetsPart2(ImplementationGuideDefn ig) throws Excepti if (vs.getText() == null || vs.getText().getDiv() == null || vs.getText().getDiv().allChildrenAreText() && (Utilities.noString(vs.getText().getDiv().allText()) || !vs.getText().getDiv().allText().matches(".*\\w.*"))) { - RenderingContext lrc = page.getRc().copy().setLocalPrefix(""); - RendererFactory.factory(vs, lrc).render(vs); + RenderingContext lrc = page.getRc().copy(false).setLocalPrefix(""); + RendererFactory.factory(vs, lrc).renderResource(ResourceWrapper.forResource(lrc.getContextUtilities(), vs)); } page.getVsValidator().validate(page.getValidationErrors(), name, vs, true, false); @@ -6913,8 +6877,8 @@ private void generateValueSetPart2(ValueSet vs) throws Exception { if (!vs.hasText() || (vs.getText().getDiv().allChildrenAreText() && (Utilities.noString(vs.getText().getDiv().allText()) || !vs.getText().getDiv().allText().matches(".*\\w.*")))) { - RenderingContext lrc = page.getRc().copy().setLocalPrefix(ig != null ? "../" : ""); - RendererFactory.factory(vs, lrc).render(vs); + RenderingContext lrc = page.getRc().copy(false).setLocalPrefix(ig != null ? "../" : ""); + RendererFactory.factory(vs, lrc).renderResource(ResourceWrapper.forResource(lrc.getContextUtilities(), vs)); } page.getVsValidator().validate(page.getValidationErrors(), n, vs, true, false); @@ -6975,8 +6939,8 @@ private void generateCodeSystemPart2(CodeSystem cs) throws Exception { if (cs.getText().getDiv().allChildrenAreText() && (Utilities.noString(cs.getText().getDiv().allText()) || !cs.getText().getDiv().allText().matches(".*\\w.*"))) { - RenderingContext lrc = page.getRc().copy().setLocalPrefix(ig != null ? "../" : ""); - RendererFactory.factory(cs, lrc).render(cs); + RenderingContext lrc = page.getRc().copy(false).setLocalPrefix(ig != null ? "../" : ""); + RendererFactory.factory(cs, lrc).renderResource(ResourceWrapper.forResource(lrc.getContextUtilities(), cs)); } page.getVsValidator().validate(page.getValidationErrors(), n, cs, true, false); @@ -7085,8 +7049,8 @@ private void generateConceptMaps() throws Exception { private void generateConceptMap(ConceptMap cm) throws Exception { String filename = cm.getWebPath(); - RenderingContext lrc = page.getRc().copy().setLocalPrefix(""); - RendererFactory.factory(cm, lrc).render(cm); + RenderingContext lrc = page.getRc().copy(false).setLocalPrefix(""); + RendererFactory.factory(cm, lrc).renderResource(ResourceWrapper.forResource(lrc.getContextUtilities(), cm)); String n = Utilities.changeFileExt(filename, ""); fixCanonicalResource(cm, n);