Search in sources :

Example 21 with XhtmlParser

use of org.hl7.fhir.utilities.xhtml.XhtmlParser in project kindling by HL7.

the class Publisher method produceResource2.

private void produceResource2(ResourceDefn resource, boolean isAbstract, String extraTypeForDefn, boolean logicalOnly) throws Exception {
    File tmp = Utilities.createTempFile("tmp", ".tmp");
    String n = resource.getName().toLowerCase();
    String xml = xmls.get(n);
    String json = jsons.get(n);
    String ttl = ttls.get(n);
    TerminologyNotesGenerator tgen = new TerminologyNotesGenerator(new FileOutputStream(tmp), page);
    tgen.generate("", resource.getRoot());
    tgen.close();
    String tx = TextFile.fileToString(tmp.getAbsolutePath());
    DictHTMLGenerator dgen = new DictHTMLGenerator(new FileOutputStream(tmp), page, "");
    dgen.generate(resource.getRoot());
    dgen.close();
    String dict = TextFile.fileToString(tmp.getAbsolutePath());
    if (extraTypeForDefn != null) {
        dgen = new DictHTMLGenerator(new FileOutputStream(tmp), page, "");
        dgen.generate(page.getDefinitions().getElementDefn(extraTypeForDefn));
        dgen.close();
        dict = dict + "\r\n" + TextFile.fileToString(tmp.getAbsolutePath());
    }
    Map<String, String> values = new HashMap<String, String>();
    MappingsGenerator mgen = new MappingsGenerator(page.getDefinitions());
    mgen.generate(resource);
    String mappings = mgen.getMappings();
    String mappingsList = mgen.getMappingsList();
    if (!logicalOnly) {
        SvgGenerator svg = new SvgGenerator(page, "", resource.getLayout(), true, false, page.getVersion());
        svg.generate(resource, page.getFolders().dstDir + n + ".svg", "1");
        svg.generate(resource, Utilities.path(page.getFolders().srcDir, n, n + ".gen.svg"), "1");
        String prefix = page.getBreadCrumbManager().getIndexPrefixForReference(resource.getName());
        SectionTracker st = new SectionTracker(prefix, false);
        st.start("");
        page.getSectionTrackerCache().put(n, st);
        String template = isAbstract ? "template-abstract" : "template";
        String src = TextFile.fileToString(page.getFolders().templateDir + template + ".html");
        src = insertSectionNumbers(page.processResourceIncludes(n, resource, xml, json, ttl, tx, dict, src, mappings, mappingsList, "resource", n + ".html", null, values, resource.getWg(), null), st, n + ".html", 0, null);
        TextFile.stringToFile(src, page.getFolders().dstDir + n + ".html");
        scanForFragments(n + ".html", new XhtmlParser().parseFragment(src));
        page.getHTMLChecker().registerFile(n + ".html", "Base Page for " + resource.getName(), HTMLLinkChecker.XHTML_TYPE, true);
        StructureDefinition profile = (StructureDefinition) ResourceUtilities.getById(page.getResourceBundle(), ResourceType.StructureDefinition, resource.getName());
        String pages = page.getIni().getStringProperty("resource-pages", n);
        if (!Utilities.noString(pages)) {
            for (String p : pages.split(",")) {
                producePage(p, n);
            }
        }
        try {
            if (!isAbstract)
                processQuestionnaire(resource, profile, st, true, "", null);
        } catch (Exception e) {
            // e.printStackTrace();
            page.log("Questionnaire Generation Failed: " + e.getMessage(), LogMessageType.Error);
        }
        if (!isAbstract || !resource.getExamples().isEmpty()) {
            src = TextFile.fileToString(page.getFolders().templateDir + template + "-examples.html");
            TextFile.stringToFile(insertSectionNumbers(page.processResourceIncludes(n, resource, xml, json, ttl, tx, dict, src, mappings, mappingsList, "res-Examples", n + "-examples.html", null, values, resource.getWg(), null), st, n + "-examples.html", 0, null), page.getFolders().dstDir + n + "-examples.html");
            page.getHTMLChecker().registerFile(n + "-examples.html", "Examples for " + resource.getName(), HTMLLinkChecker.XHTML_TYPE, true);
            for (Example e : resource.getExamples()) {
                try {
                    processExample(e, resource, profile, null, e.getIg() == null ? null : page.getDefinitions().getIgs().get(e.getIg()));
                } catch (Exception ex) {
                    throw new Exception("processing " + e.getTitle(), ex);
                // throw new Exception(ex.getMessage()+" processing "+e.getFileTitle());
                }
            }
        }
        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 + "-definitions.html", 0, null), page.getFolders().dstDir + n + "-definitions.html");
        page.getHTMLChecker().registerFile(n + "-definitions.html", "Detailed Descriptions for " + resource.getName(), HTMLLinkChecker.XHTML_TYPE, true);
        if (!isAbstract) {
            src = TextFile.fileToString(page.getFolders().templateDir + "template-mappings.html");
            TextFile.stringToFile(insertSectionNumbers(page.processResourceIncludes(n, resource, xml, json, ttl, tx, dict, src, mappings, mappingsList, "res-Mappings", n + "-mappings.html", null, values, resource.getWg(), null), st, n + "-mappings.html", 0, null), page.getFolders().dstDir + n + "-mappings.html");
            page.getHTMLChecker().registerFile(n + "-mappings.html", "Formal Mappings for " + resource.getName(), HTMLLinkChecker.XHTML_TYPE, true);
            src = TextFile.fileToString(page.getFolders().templateDir + "template-profiles.html");
            TextFile.stringToFile(insertSectionNumbers(page.processResourceIncludes(n, resource, xml, json, ttl, tx, dict, src, mappings, mappingsList, "res-Profiles", n + "-profiles.html", null, values, resource.getWg(), null), st, n + "-profiles.html", 0, null), page.getFolders().dstDir + n + "-profiles.html");
            page.getHTMLChecker().registerFile(n + "-profiles.html", "Profiles for " + resource.getName(), HTMLLinkChecker.XHTML_TYPE, true);
        }
        if (!resource.getOperations().isEmpty()) {
            src = TextFile.fileToString(page.getFolders().templateDir + "template-operations.html");
            TextFile.stringToFile(insertSectionNumbers(page.processResourceIncludes(n, resource, xml, json, ttl, tx, dict, src, mappings, mappingsList, "res-Operations", n + "-operations.html", null, values, resource.getWg(), null), st, n + "-operations.html", 0, null), page.getFolders().dstDir + n + "-operations.html");
            page.getHTMLChecker().registerFile(n + "-operations.html", "Operations for " + resource.getName(), HTMLLinkChecker.XHTML_TYPE, true);
            for (Operation t : resource.getOperations()) {
                produceOperation(null, resource.getName().toLowerCase() + "-" + t.getName(), resource.getName() + "-" + t.getName(), resource, t, st);
            }
        }
        produceMap(resource.getName(), st, resource);
        for (Profile ap : resource.getConformancePackages()) produceConformancePackage(resource, ap, st);
        src = TextFile.fileToString(page.getFolders().templateDir + "template-json-schema.html");
        TextFile.stringToFile(insertSectionNumbers(page.processResourceIncludes(n, resource, xml, json, ttl, tx, dict, src, mappings, mappingsList, "res-schema", n + ".schema.json.html", null, values, resource.getWg(), null), st, n + ".schema.json.html", 0, null), page.getFolders().dstDir + n + ".schema.json.html");
        page.getHTMLChecker().registerFile(n + ".schema.json.html", "Json Schema for " + resource.getName(), HTMLLinkChecker.XHTML_TYPE, true);
        src = TextFile.fileToString(page.getFolders().templateDir + "template-dependencies.html");
        TextFile.stringToFile(insertSectionNumbers(page.processResourceIncludes(n, resource, xml, json, ttl, tx, dict, src, mappings, mappingsList, "res-Dependencies", n + "-dependencies.html", null, values, resource.getWg(), null), st, n + "-dependencies.html", 0, null), page.getFolders().dstDir + n + "-dependencies.html");
        page.getHTMLChecker().registerFile(n + "-dependencies.html", "Dependency graph for " + resource.getName(), HTMLLinkChecker.XHTML_TYPE, true);
        for (ConceptMap cm : statusCodeConceptMaps) if (cm.getUserData("resource-definition") == resource)
            produceConceptMap(cm, resource, st);
    // xml to json
    // todo - fix this up
    // JsonGenerator jsongen = new JsonGenerator();
    // jsongen.generate(new CSFile(page.getFolders().dstDir+n+".xml"), new
    // File(page.getFolders().dstDir+n+".json"));
    }
    tmp.delete();
    new ProfileUtilities(page.getWorkerContext(), page.getValidationErrors(), page).generateXlsx(new FileOutputStream(Utilities.path(page.getFolders().dstDir, n + ".xlsx")), resource.getProfile(), false, false);
    // because we'll pick up a little more information as we process the
    // resource
    StructureDefinition p = generateProfile(resource, n, xml, json, ttl, !logicalOnly);
    com.google.gson.JsonObject diff = new com.google.gson.JsonObject();
    page.getDiffEngine().getDiffAsJson(diff, p);
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    json = gson.toJson(diff);
    TextFile.stringToFile(json, Utilities.path(page.getFolders().dstDir, resource.getName().toLowerCase() + ".diff.json"));
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = dbf.newDocumentBuilder();
    Document doc = builder.newDocument();
    Element element = doc.createElement("difference");
    doc.appendChild(element);
    page.getDiffEngine().getDiffAsXml(doc, element, p);
    prettyPrint(doc, Utilities.path(page.getFolders().dstDir, resource.getName().toLowerCase() + ".diff.xml"));
}
Also used : JsonObject(com.google.gson.JsonObject) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) XhtmlParser(org.hl7.fhir.utilities.xhtml.XhtmlParser) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) DictHTMLGenerator(org.hl7.fhir.definitions.generators.specification.DictHTMLGenerator) Element(org.w3c.dom.Element) JsonObject(com.google.gson.JsonObject) Gson(com.google.gson.Gson) MappingsGenerator(org.hl7.fhir.definitions.generators.specification.MappingsGenerator) Operation(org.hl7.fhir.definitions.model.Operation) Document(org.w3c.dom.Document) XhtmlDocument(org.hl7.fhir.utilities.xhtml.XhtmlDocument) Profile(org.hl7.fhir.definitions.model.Profile) StructureDefinition(org.hl7.fhir.r5.model.StructureDefinition) Example(org.hl7.fhir.definitions.model.Example) ConceptMap(org.hl7.fhir.r5.model.ConceptMap) GsonBuilder(com.google.gson.GsonBuilder) TerminologyNotesGenerator(org.hl7.fhir.definitions.generators.specification.TerminologyNotesGenerator) TransformerException(javax.xml.transform.TransformerException) IOException(java.io.IOException) FHIRException(org.hl7.fhir.exceptions.FHIRException) FileNotFoundException(java.io.FileNotFoundException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) SvgGenerator(org.hl7.fhir.definitions.generators.specification.SvgGenerator) ProfileUtilities(org.hl7.fhir.r5.conformance.ProfileUtilities) DocumentBuilder(javax.xml.parsers.DocumentBuilder) FileOutputStream(java.io.FileOutputStream) IniFile(org.hl7.fhir.utilities.IniFile) File(java.io.File) CSFile(org.hl7.fhir.utilities.CSFile) TextFile(org.hl7.fhir.utilities.TextFile)

Example 22 with XhtmlParser

use of org.hl7.fhir.utilities.xhtml.XhtmlParser in project kindling by HL7.

the class Publisher method processExample.

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();
    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))
        return;
    examplesProcessed.add(prefix + n);
    // strip the xsi: stuff. seems to need double processing in order to
    // delete namespace crap
    xdoc = e.getXml();
    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());
    // 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("").setTooCostlyNoteEmpty(PageProcessor.TOO_MANY_CODES_TEXT_EMPTY).setTooCostlyNoteNotEmpty(PageProcessor.TOO_MANY_CODES_TEXT_NOT_EMPTY);
        xdoc = loadDom(new FileInputStream(file), true);
        rt = xdoc.getDocumentElement().getNodeName();
        String id = XMLUtil.getNamedChildValue(xdoc.getDocumentElement(), "id");
        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");
        if (rt.equals("ValueSet") || rt.equals("CodeSystem") || rt.equals("ConceptMap") || rt.equals("CapabilityStatement") || rt.equals("Library")) {
            // for these, we use the reference implementation directly
            CanonicalResource res = (CanonicalResource) loadExample(file);
            if (res.getUrl() != null && res.getUrl().startsWith("http://hl7.org/fhir"))
                res.setVersion(page.getVersion().toCode());
            boolean wantSave = false;
            if (res instanceof CapabilityStatement) {
                ((CapabilityStatement) res).setFhirVersion(page.getVersion());
                if (res.hasText() && res.getText().hasDiv())
                    wantSave = updateVersion(((CapabilityStatement) res).getText().getDiv());
            }
            if (!res.hasText() || !res.getText().hasDiv()) {
                RendererFactory.factory(res, lrc).render(res);
                wantSave = true;
            }
            if (wantSave) {
                if (page.getVersion().isR4B()) {
                    org.hl7.fhir.r4.model.Resource r4 = new org.hl7.fhir.r4.formats.XmlParser().parse(new FileInputStream(file));
                    new org.hl7.fhir.r4.formats.XmlParser().setOutputStyle(org.hl7.fhir.r4.formats.IParser.OutputStyle.PRETTY).compose(new FileOutputStream(file), r4);
                } else {
                    new XmlParser().setOutputStyle(OutputStyle.PRETTY).compose(new FileOutputStream(file), res);
                }
            }
            narrative = new XhtmlComposer(XhtmlComposer.HTML).compose(res.getText().getDiv());
        } else {
            if (rt.equals("Bundle")) {
                List<Element> entries = new ArrayList<Element>();
                XMLUtil.getNamedChildren(xdoc.getDocumentElement(), "entry", entries);
                boolean wantSave = false;
                for (Element entry : entries) {
                    Element ers = XMLUtil.getFirstChild(XMLUtil.getNamedChild(entry, "resource"));
                    id = XMLUtil.getNamedChildValue(ers, "id");
                    if (id != null)
                        page.getDefinitions().addNs("http://hl7.org/fhir/" + ers.getLocalName() + "/" + id, "Example", prefix + n + ".html", true);
                    if (ers != null) {
                        String ert = ers.getLocalName();
                        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());
                            XhtmlNode div = rw.getNarrative();
                            if (div == null || div.isEmpty()) {
                                wantSave = true;
                                r.render(rw);
                            } else
                                s = new XhtmlComposer(true).compose(div);
                            if (s != null)
                                narrative = narrative == null ? s : narrative + "<hr/>\r\n" + s;
                        }
                        if (ert.equals("NamingSystem")) {
                            ByteArrayOutputStream bs = new ByteArrayOutputStream();
                            new XmlGenerator().generate(ers, bs);
                            bs.close();
                            NamingSystem ns = (NamingSystem) new XmlParser().parse(new ByteArrayInputStream(bs.toByteArray()));
                            if (!ns.hasUrl() || ns.getUrl().startsWith("http://hl7.org/fhir"))
                                ns.setVersion(page.getVersion().toCode());
                            ns.setUserData("path", prefix + n + ".html");
                            page.getDefinitions().getNamingSystems().add(ns);
                        }
                    }
                }
                if (wantSave)
                    new XmlGenerator().generate(xdoc.getDocumentElement(), file, "http://hl7.org/fhir", xdoc.getDocumentElement().getLocalName());
            } else {
                if (!page.getDefinitions().getBaseResources().containsKey(rt) && !rt.equals("Binary") && !rt.equals("Parameters")) {
                    ResourceRenderer r = RendererFactory.factory(xdoc.getDocumentElement().getLocalName(), lrc);
                    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);
                    }
                }
            }
        }
    } catch (Exception ex) {
        StringWriter errors = new StringWriter();
        ex.printStackTrace();
        XhtmlNode xhtml = new XhtmlNode(NodeType.Element, "div");
        xhtml.addTag("p").setAttribute("style", "color: maroon").addText("Error processing narrative: " + ex.getMessage());
        xhtml.addTag("p").setAttribute("style", "color: maroon").addText(errors.toString());
        narrative = new XhtmlComposer(XhtmlComposer.HTML).compose(xhtml);
    }
    if (rt.equals("ValueSet")) {
        try {
            ValueSet vs = (ValueSet) loadExample(file);
            vs.setUserData("filename", Utilities.changeFileExt(file.getName(), ""));
            vs.addExtension().setUrl(ToolingExtensions.EXT_WORKGROUP).setValue(new CodeType("fhir"));
            if (vs.getUrl().startsWith("http://hl7.org/fhir"))
                vs.setVersion(page.getVersion().toCode());
            page.getVsValidator().validate(page.getValidationErrors(), "Value set Example " + prefix + n, vs, false, false);
            if (vs.getUrl() == null)
                throw new Exception("Value set example " + e.getTitle() + " has no url");
            vs.setUserData("path", prefix + n + ".html");
            if (vs.getUrl().startsWith("http:"))
                page.getValueSets().see(vs, page.packageInfo());
            addToResourceFeed(vs, valueSetsFeed, file.getName());
            page.getDefinitions().getValuesets().see(vs, page.packageInfo());
        } catch (Exception ex) {
            if (page.getVersion().isR4B()) {
                System.out.println("Value set " + file.getAbsolutePath() + " couldn't be parsed - ignoring! msg = " + ex.getMessage());
            } else {
                throw new FHIRException("Unable to parse " + file.getAbsolutePath() + ": " + ex.getMessage(), ex);
            }
        }
    } else if (rt.equals("CodeSystem")) {
        CodeSystem cs = (CodeSystem) loadExample(file);
        if (cs.getUrl().startsWith("http://hl7.org/fhir"))
            cs.setVersion(page.getVersion().toCode());
        cs.setUserData("example", "true");
        cs.setUserData("filename", Utilities.changeFileExt(file.getName(), ""));
        cs.addExtension().setUrl(ToolingExtensions.EXT_WORKGROUP).setValue(new CodeType("fhir"));
        cs.setUserData("path", prefix + n + ".html");
        addToResourceFeed(cs, valueSetsFeed, file.getName());
        page.getCodeSystems().see(cs, page.packageInfo());
    } else if (rt.equals("ConceptMap") && !page.getVersion().isR4B()) {
        ConceptMap cm = (ConceptMap) loadExample(file);
        new ConceptMapValidator(page.getDefinitions(), e.getTitle()).validate(cm, false);
        if (cm.getUrl() == null)
            throw new Exception("Value set example " + e.getTitle() + " has no identifier");
        if (cm.getUrl().startsWith("http://hl7.org/fhir"))
            cm.setVersion(page.getVersion().toCode());
        addToResourceFeed(cm, conceptMapsFeed, file.getName());
        page.getDefinitions().getConceptMaps().see(cm, page.packageInfo());
        cm.setUserData("path", prefix + n + ".html");
        page.getConceptMaps().see(cm, page.packageInfo());
    } else if (rt.equals("Library")) {
        try {
            Library lib = (Library) loadExample(file);
            if (lib.hasUrl() && lib.getUrl().startsWith("http://hl7.org/fhir"))
                lib.setVersion(page.getVersion().toCode());
            lib.setUserData("example", "true");
            lib.setUserData("filename", Utilities.changeFileExt(file.getName(), ""));
            lib.setUserData("path", prefix + n + ".html");
            page.getWorkerContext().cacheResource(lib);
        } catch (Exception ex) {
            System.out.println("Internal exception processing Library " + file.getName() + ": " + ex.getMessage() + ". Does the libary code need regenerating?");
            ex.printStackTrace();
        }
    }
    // queue for json and canonical XML generation processing
    e.setResourceName(resn.getName());
    String canonical = "http://hl7.org/fhir/";
    org.hl7.fhir.r5.elementmodel.Element ex = Manager.parse(page.getWorkerContext(), new CSFileInputStream(page.getFolders().dstDir + prefix + n + ".xml"), FhirFormat.XML);
    new DefinitionsUsageTracker(page.getDefinitions()).updateUsage(ex);
    Manager.compose(page.getWorkerContext(), ex, new FileOutputStream(page.getFolders().dstDir + prefix + n + ".json"), FhirFormat.JSON, OutputStyle.PRETTY, canonical);
    // Manager.compose(page.getWorkerContext(), ex, new FileOutputStream(Utilities.changeFileExt(destName, ".canonical.json")), FhirFormat.JSON, OutputStyle.CANONICAL);
    // Manager.compose(page.getWorkerContext(), ex, new FileOutputStream(Utilities.changeFileExt(destName, ".canonical.xml")), FhirFormat.XML, OutputStyle.CANONICAL);
    Manager.compose(page.getWorkerContext(), ex, new FileOutputStream(page.getFolders().dstDir + prefix + n + ".ttl"), FhirFormat.TURTLE, OutputStyle.PRETTY, resn.getName().equals("Parameters") || resn.getName().equals("OperationOutcome") ? null : canonical);
    String json = TextFile.fileToString(page.getFolders().dstDir + prefix + n + ".json");
    // String json2 = "<div class=\"example\">\r\n<p>" + Utilities.escapeXml(e.getDescription()) + "</p>\r\n<p><a href=\""+ n + ".json\">Raw JSON</a> (<a href=\""+n + ".canonical.json\">Canonical</a>)</p>\r\n<pre class=\"json\">\r\n" + Utilities.escapeXml(json)
    // + "\r\n</pre>\r\n</div>\r\n";
    json = "<div class=\"example\">\r\n<p>" + Utilities.escapeXml(e.getDescription()) + "</p>\r\n<pre class=\"json\">\r\n" + Utilities.escapeXml(json) + "\r\n</pre>\r\n</div>\r\n";
    String html = TextFile.fileToString(page.getFolders().templateDir + "template-example-json.html").replace("<%example%>", json);
    html = page.processPageIncludes(n + ".json.html", html, e.getResourceName() == null ? "profile-instance:resource:" + e.getResourceName() : "resource-instance:" + e.getResourceName(), null, null, null, "Example", null, resn, resn.getWg());
    TextFile.stringToFile(html, page.getFolders().dstDir + prefix + n + ".json.html");
    page.getHTMLChecker().registerExternal(prefix + n + ".json.html");
    String ttl = TextFile.fileToString(page.getFolders().dstDir + prefix + n + ".ttl");
    ttl = "<div class=\"example\">\r\n<p>" + Utilities.escapeXml(e.getDescription()) + "</p>\r\n<pre class=\"rdf\">\r\n" + Utilities.escapeXml(ttl) + "\r\n</pre>\r\n</div>\r\n";
    html = TextFile.fileToString(page.getFolders().templateDir + "template-example-ttl.html").replace("<%example%>", ttl);
    html = page.processPageIncludes(n + ".ttl.html", html, e.getResourceName() == null ? "profile-instance:resource:" + e.getResourceName() : "resource-instance:" + e.getResourceName(), null, null, null, "Example", null, resn, resn.getWg());
    TextFile.stringToFile(html, page.getFolders().dstDir + prefix + n + ".ttl.html");
    page.getHTMLChecker().registerExternal(prefix + n + ".ttl.html");
    // reload it now, xml to xhtml of xml
    builder = factory.newDocumentBuilder();
    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() + " (id = \"" + e.getId() + "\")", 0, true, n + ".xml.html");
    html = TextFile.fileToString(page.getFolders().templateDir + "template-example-xml.html").replace("<%example%>", b.toString());
    html = page.processPageIncludes(n + ".xml.html", html, resn == null ? "profile-instance:resource:" + rt : "resource-instance:" + resn.getName(), null, n + ".xml.html", profile, null, "Example", (hasNarrative(xdoc)) ? new Boolean(true) : null, ig, resn, resn.getWg());
    TextFile.stringToFile(html, page.getFolders().dstDir + prefix + n + ".xml.html");
    XhtmlDocument d = new XhtmlParser().parse(new CSFileInputStream(page.getFolders().dstDir + prefix + n + ".xml.html"), "html");
    XhtmlNode pre = d.getElement("html").getElement("body").getElement("div");
    e.setXhtm(b.toString());
    Element root = xdoc.getDocumentElement();
    Element meta = XMLUtil.getNamedChild(root, "meta");
    if (meta == null) {
        Element id = XMLUtil.getNamedChild(root, "id");
        if (id == null)
            meta = XMLUtil.insertChild(xdoc, root, "meta", FormatUtilities.FHIR_NS, 2);
        else {
            Element pid = XMLUtil.getNextSibling(id);
            if (pid == null)
                throw new Exception("not handled - id is last child in " + n);
            else
                meta = XMLUtil.insertChild(xdoc, root, "meta", FormatUtilities.FHIR_NS, pid, 2);
        }
    }
    Element tag = XMLUtil.getNamedChild(meta, "tag");
    Element label = XMLUtil.insertChild(xdoc, meta, "security", FormatUtilities.FHIR_NS, tag, 4);
    XMLUtil.addTextTag(xdoc, label, "system", FormatUtilities.FHIR_NS, "http://terminology.hl7.org/CodeSystem/v3-ActReason", 6);
    XMLUtil.addTextTag(xdoc, label, "code", FormatUtilities.FHIR_NS, "HTEST", 6);
    XMLUtil.addTextTag(xdoc, label, "display", FormatUtilities.FHIR_NS, "test health data", 6);
    XMLUtil.spacer(xdoc, label, 4);
    XMLUtil.spacer(xdoc, meta, 2);
    String destf = (!Utilities.noString(e.getId())) ? page.getFolders().dstDir + "examples" + File.separator + n + "(" + e.getId() + ").xml" : page.getFolders().dstDir + "examples" + File.separator + n + ".xml";
    FileOutputStream fs = new FileOutputStream(destf);
    XMLUtil.saveToFile(root, fs);
    fs.close();
    // now, we create an html page from the narrative
    narrative = fixExampleReferences(e.getTitle(), narrative);
    html = TextFile.fileToString(page.getFolders().templateDir + "template-example.html").replace("<%example%>", narrative == null ? "" : narrative).replace("<%example-usage%>", genExampleUsage(e, page.genlevel(level)));
    html = page.processPageIncludes(n + ".html", html, resn == null ? "profile-instance:resource:" + rt : "resource-instance:" + resn.getName(), null, profile, null, "Example", ig, resn, resn.getWg());
    TextFile.stringToFile(html, page.getFolders().dstDir + prefix + n + ".html");
    // head =
    // "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\">\r\n<head>\r\n <title>"+Utilities.escapeXml(e.getDescription())+"</title>\r\n <link rel=\"Stylesheet\" href=\"fhir.css\" type=\"text/css\" media=\"screen\"/>\r\n"+
    // "</head>\r\n<body>\r\n<p>&nbsp;</p>\r\n<p>"+Utilities.escapeXml(e.getDescription())+"</p>\r\n"+
    // "<p><a href=\""+n+".xml.html\">XML</a> <a href=\""+n+".json.html\">JSON</a></p>\r\n";
    // tail = "\r\n</body>\r\n</html>\r\n";
    // TextFile.stringToFile(head+narrative+tail, page.getFolders().dstDir + n +
    // ".html");
    page.getHTMLChecker().registerExternal(prefix + n + ".html");
    page.getHTMLChecker().registerExternal(prefix + n + ".xml.html");
}
Also used : ResourceWrapper(org.hl7.fhir.r5.renderers.utils.BaseWrappers.ResourceWrapper) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) XhtmlParser(org.hl7.fhir.utilities.xhtml.XhtmlParser) ConceptMapValidator(org.hl7.fhir.definitions.validation.ConceptMapValidator) ArrayList(java.util.ArrayList) CSFile(org.hl7.fhir.utilities.CSFile) Document(org.w3c.dom.Document) XhtmlDocument(org.hl7.fhir.utilities.xhtml.XhtmlDocument) XhtmlDocument(org.hl7.fhir.utilities.xhtml.XhtmlDocument) ResourceRenderer(org.hl7.fhir.r5.renderers.ResourceRenderer) CapabilityStatement(org.hl7.fhir.r5.model.CapabilityStatement) ConceptMap(org.hl7.fhir.r5.model.ConceptMap) ValueSet(org.hl7.fhir.r5.model.ValueSet) CodeSystem(org.hl7.fhir.r5.model.CodeSystem) CSFileInputStream(org.hl7.fhir.utilities.CSFileInputStream) FileInputStream(java.io.FileInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) FileOutputStream(java.io.FileOutputStream) Library(org.hl7.fhir.r5.model.Library) Element(org.w3c.dom.Element) XhtmlNode(org.hl7.fhir.utilities.xhtml.XhtmlNode) XhtmlGenerator(org.hl7.fhir.utilities.xml.XhtmlGenerator) StringWriter(java.io.StringWriter) XhtmlComposer(org.hl7.fhir.utilities.xhtml.XhtmlComposer) RenderingContext(org.hl7.fhir.r5.renderers.utils.RenderingContext) XmlParser(org.hl7.fhir.r5.formats.XmlParser) XmlGenerator(org.hl7.fhir.utilities.xml.XmlGenerator) ByteArrayOutputStream(java.io.ByteArrayOutputStream) FHIRException(org.hl7.fhir.exceptions.FHIRException) ContactPoint(org.hl7.fhir.r5.model.ContactPoint) TransformerException(javax.xml.transform.TransformerException) IOException(java.io.IOException) FHIRException(org.hl7.fhir.exceptions.FHIRException) FileNotFoundException(java.io.FileNotFoundException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) NamingSystem(org.hl7.fhir.r5.model.NamingSystem) DocumentBuilder(javax.xml.parsers.DocumentBuilder) CodeType(org.hl7.fhir.r5.model.CodeType) CanonicalResource(org.hl7.fhir.r5.model.CanonicalResource) CSFileInputStream(org.hl7.fhir.utilities.CSFileInputStream)

Example 23 with XhtmlParser

use of org.hl7.fhir.utilities.xhtml.XhtmlParser in project kindling by HL7.

the class Publisher method insertSectionNumbers.

private String insertSectionNumbers(String src, SectionTracker st, String link, int level, DocumentHolder doch) throws Exception {
    try {
        // TextFile.stringToFile(src, "c:\\temp\\text.html");
        XhtmlDocument doc = new XhtmlParser().parse(src, "html");
        insertSectionNumbersInNode(doc, st, link, level, new BooleanHolder(), null);
        if (doch != null)
            doch.doc = doc;
        return new XhtmlComposer(XhtmlComposer.HTML).compose(doc);
    } catch (Exception e) {
        System.out.println(e.getMessage());
        // TextFile.stringToFile(src, "c:\\temp\\dump.html");
        TextFile.stringToFile(src, Utilities.appendSlash(System.getProperty("user.dir")) + "fhir-error-dump.html");
        throw new Exception("Exception inserting section numbers in " + link + ": " + e.getMessage(), e);
    }
}
Also used : XhtmlParser(org.hl7.fhir.utilities.xhtml.XhtmlParser) XhtmlComposer(org.hl7.fhir.utilities.xhtml.XhtmlComposer) TransformerException(javax.xml.transform.TransformerException) IOException(java.io.IOException) FHIRException(org.hl7.fhir.exceptions.FHIRException) FileNotFoundException(java.io.FileNotFoundException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) XhtmlDocument(org.hl7.fhir.utilities.xhtml.XhtmlDocument)

Example 24 with XhtmlParser

use of org.hl7.fhir.utilities.xhtml.XhtmlParser in project org.hl7.fhir.core by hapifhir.

the class XmlParser method parseChildren.

private void parseChildren(String path, org.w3c.dom.Element node, Element context) throws FHIRFormatError, FHIRException, IOException, DefinitionException {
    // this parsing routine retains the original order in a the XML file, to support validation
    reapComments(node, context);
    List<Property> properties = context.getProperty().getChildProperties(context.getName(), XMLUtil.getXsiType(node));
    String text = XMLUtil.getDirectText(node).trim();
    if (!Utilities.noString(text)) {
        Property property = getTextProp(properties);
        if (property != null) {
            context.getChildren().add(new Element(property.getName(), property, property.getType(), text).markLocation(line(node), col(node)));
        } else {
            logError(line(node), col(node), path, IssueType.STRUCTURE, "Text should not be present", IssueSeverity.ERROR);
        }
    }
    for (int i = 0; i < node.getAttributes().getLength(); i++) {
        Node attr = node.getAttributes().item(i);
        if (!(attr.getNodeName().equals("xmlns") || attr.getNodeName().startsWith("xmlns:"))) {
            Property property = getAttrProp(properties, attr.getNodeName());
            if (property != null) {
                String av = attr.getNodeValue();
                if (ToolingExtensions.hasExtension(property.getDefinition(), "http://www.healthintersections.com.au/fhir/StructureDefinition/elementdefinition-dateformat"))
                    av = convertForDateFormatFromExternal(ToolingExtensions.readStringExtension(property.getDefinition(), "http://www.healthintersections.com.au/fhir/StructureDefinition/elementdefinition-dateformat"), av);
                if (property.getName().equals("value") && context.isPrimitive())
                    context.setValue(av);
                else
                    context.getChildren().add(new Element(property.getName(), property, property.getType(), av).markLocation(line(node), col(node)));
            } else {
                boolean ok = false;
                if (FormatUtilities.FHIR_NS.equals(node.getNamespaceURI())) {
                    if (attr.getLocalName().equals("schemaLocation") && FormatUtilities.NS_XSI.equals(attr.getNamespaceURI())) {
                        ok = ok || allowXsiLocation;
                    }
                } else
                    // xsi:schemalocation allowed for non FHIR content
                    ok = ok || (attr.getLocalName().equals("schemaLocation"));
                // xsi:type allowed if element says so
                ok = ok || (hasTypeAttr(context) && attr.getLocalName().equals("type") && FormatUtilities.NS_XSI.equals(attr.getNamespaceURI()));
                if (!ok)
                    logError(line(node), col(node), path, IssueType.STRUCTURE, "Undefined attribute '@" + attr.getNodeName() + "' on " + node.getNodeName() + " for type " + context.fhirType() + " (properties = " + properties + ")", IssueSeverity.ERROR);
            }
        }
    }
    Node child = node.getFirstChild();
    while (child != null) {
        if (child.getNodeType() == Node.ELEMENT_NODE) {
            Property property = getElementProp(properties, child.getLocalName());
            if (property != null) {
                if (!property.isChoice() && "xhtml".equals(property.getType())) {
                    XhtmlNode xhtml;
                    if (property.getDefinition().hasRepresentation(PropertyRepresentation.CDATEXT))
                        xhtml = new CDANarrativeFormat().convert((org.w3c.dom.Element) child);
                    else
                        xhtml = new XhtmlParser().setValidatorMode(true).parseHtmlNode((org.w3c.dom.Element) child);
                    context.getChildren().add(new Element(property.getName(), property, "xhtml", new XhtmlComposer(XhtmlComposer.XML, false).compose(xhtml)).setXhtml(xhtml).markLocation(line(child), col(child)));
                } else {
                    String npath = path + "/" + pathPrefix(child.getNamespaceURI()) + child.getLocalName();
                    Element n = new Element(child.getLocalName(), property).markLocation(line(child), col(child));
                    checkElement((org.w3c.dom.Element) child, npath, n.getProperty());
                    boolean ok = true;
                    if (property.isChoice()) {
                        if (property.getDefinition().hasRepresentation(PropertyRepresentation.TYPEATTR)) {
                            String xsiType = ((org.w3c.dom.Element) child).getAttributeNS(FormatUtilities.NS_XSI, "type");
                            if (Utilities.noString(xsiType)) {
                                logError(line(child), col(child), path, IssueType.STRUCTURE, "No type found on '" + child.getLocalName() + '"', IssueSeverity.ERROR);
                                ok = false;
                            } else {
                                if (xsiType.contains(":"))
                                    xsiType = xsiType.substring(xsiType.indexOf(":") + 1);
                                n.setType(xsiType);
                                n.setExplicitType(xsiType);
                            }
                        } else
                            n.setType(n.getType());
                    }
                    context.getChildren().add(n);
                    if (ok) {
                        if (property.isResource())
                            parseResource(npath, (org.w3c.dom.Element) child, n, property);
                        else
                            parseChildren(npath, (org.w3c.dom.Element) child, n);
                    }
                }
            } else
                logError(line(child), col(child), path, IssueType.STRUCTURE, "Undefined element '" + child.getLocalName() + "'", IssueSeverity.ERROR);
        } else if (child.getNodeType() == Node.CDATA_SECTION_NODE) {
            logError(line(child), col(child), path, IssueType.STRUCTURE, "CDATA is not allowed", IssueSeverity.ERROR);
        } else if (!Utilities.existsInList(child.getNodeType(), 3, 8)) {
            logError(line(child), col(child), path, IssueType.STRUCTURE, "Node type " + Integer.toString(child.getNodeType()) + " is not allowed", IssueSeverity.ERROR);
        }
        child = child.getNextSibling();
    }
}
Also used : XhtmlParser(org.hl7.fhir.utilities.xhtml.XhtmlParser) SpecialElement(org.hl7.fhir.r4.elementmodel.Element.SpecialElement) XhtmlNode(org.hl7.fhir.utilities.xhtml.XhtmlNode) Node(org.w3c.dom.Node) XhtmlNode(org.hl7.fhir.utilities.xhtml.XhtmlNode) XhtmlComposer(org.hl7.fhir.utilities.xhtml.XhtmlComposer) CDANarrativeFormat(org.hl7.fhir.utilities.xhtml.CDANarrativeFormat)

Example 25 with XhtmlParser

use of org.hl7.fhir.utilities.xhtml.XhtmlParser in project org.hl7.fhir.core by hapifhir.

the class GeneratorTestFragments method test.

private void test() throws FHIRFormatError, IOException {
    Observation res = new Observation();
    res.setId("example");
    Narrative n = new Narrative();
    res.setText(n);
    n.setStatus(NarrativeStatus.GENERATED);
    n.setDiv(new XhtmlParser().parse("<div xmlns=\"http://www.w3.org/1999/xhtml\"><p><b>Generated Narrative with Details</b></p><p><b>id</b>: example</p><p><b>status</b>: final</p><p><b>category</b>: Vital Signs <span>(Details : {http://hl7.org/fhir/observation-category code &#39;vital-signs&#39; = &#39;Vital Signs&#39;, given as &#39;Vital Signs&#39;})</span></p><p><b>code</b>: Body Weight <span>(Details : {LOINC code &#39;29463-7&#39; = &#39;Body weight&#39;, given as &#39;Body Weight&#39;}; {LOINC code &#39;3141-9&#39; = &#39;Body weight Measured&#39;, given as &#39;Body weight Measured&#39;}; {SNOMED CT code &#39;27113001&#39; = &#39;Body weight&#39;, given as &#39;Body weight&#39;}; {http://acme.org/devices/clinical-codes code &#39;body-weight&#39; = &#39;body-weight&#39;, given as &#39;Body Weight&#39;})</span></p><p><b>subject</b>: <a>Patient/example</a></p><p><b>context</b>: <a>Encounter/example</a></p><p><b>effective</b>: 28/03/2016</p><p><b>value</b>: 185 lbs<span> (Details: UCUM code [lb_av] = &#39;lb_av&#39;)</span></p></div>", "div"));
    res.setStatus(ObservationStatus.FINAL);
    CodeableConcept cc = res.addCategory();
    Coding c = cc.addCoding();
    c.setSystem("http://hl7.org/fhir/observation-category");
    c.setCode("vital-signs");
    c.setDisplay("Vital Signs");
    cc = new CodeableConcept();
    res.setCode(cc);
    c = cc.addCoding();
    c.setSystem("http://loinc.org");
    c.setCode("29463-7");
    c.setDisplay("Body Weight");
    c = cc.addCoding();
    c.setSystem("http://loinc.org");
    c.setCode("3141-9");
    c.setDisplay("Body weight Measured");
    c = cc.addCoding();
    c.setSystem("http://snomed.info/sct");
    c.setCode("27113001");
    c.setDisplay("Body weight");
    c = cc.addCoding();
    c.setSystem("http://acme.org/devices/clinical-codes");
    c.setCode("body-weight");
    c.setDisplay("Body Weight");
    Reference r = new Reference();
    res.setSubject(r);
    r.setReference("Patient/example");
    r = new Reference();
    res.setEncounter(r);
    r.setReference("Encounter/example");
    res.setEffective(new DateTimeType("2016-03-28"));
    Quantity q = new Quantity();
    res.setValue(q);
    q.setValue(185);
    q.setUnit("lbs");
    q.setSystem("http://unitsofmeasure.org");
    q.setCode("[lb_av]");
}
Also used : DateTimeType(org.hl7.fhir.r4b.model.DateTimeType) XhtmlParser(org.hl7.fhir.utilities.xhtml.XhtmlParser) Narrative(org.hl7.fhir.r4b.model.Narrative) Coding(org.hl7.fhir.r4b.model.Coding) Reference(org.hl7.fhir.r4b.model.Reference) Observation(org.hl7.fhir.r4b.model.Observation) Quantity(org.hl7.fhir.r4b.model.Quantity) CodeableConcept(org.hl7.fhir.r4b.model.CodeableConcept)

Aggregations

XhtmlParser (org.hl7.fhir.utilities.xhtml.XhtmlParser)40 XhtmlNode (org.hl7.fhir.utilities.xhtml.XhtmlNode)25 FHIRException (org.hl7.fhir.exceptions.FHIRException)19 IOException (java.io.IOException)14 XhtmlComposer (org.hl7.fhir.utilities.xhtml.XhtmlComposer)11 DefinitionException (org.hl7.fhir.exceptions.DefinitionException)10 FileNotFoundException (java.io.FileNotFoundException)7 UnsupportedEncodingException (java.io.UnsupportedEncodingException)7 FHIRFormatError (org.hl7.fhir.exceptions.FHIRFormatError)7 XhtmlDocument (org.hl7.fhir.utilities.xhtml.XhtmlDocument)6 TransformerException (javax.xml.transform.TransformerException)5 CommaSeparatedStringBuilder (org.hl7.fhir.utilities.CommaSeparatedStringBuilder)5 CDANarrativeFormat (org.hl7.fhir.utilities.xhtml.CDANarrativeFormat)5 Node (org.w3c.dom.Node)5 NotImplementedException (org.apache.commons.lang3.NotImplementedException)4 MarkDownProcessor (org.hl7.fhir.utilities.MarkDownProcessor)4 FileInputStream (java.io.FileInputStream)3 FileOutputStream (java.io.FileOutputStream)3 ArrayList (java.util.ArrayList)3 DocumentBuilder (javax.xml.parsers.DocumentBuilder)3