Search in sources :

Example 21 with RenderingContext

use of org.hl7.fhir.r5.renderers.utils.RenderingContext in project kindling by HL7.

the class PageProcessor method genExample.

private String genExample(Example example, int headerLevelContext, String genlevel) throws IOException, EOperationOutcome, FHIRException {
    String xml = XMLUtil.elementToString(example.getXml().getDocumentElement());
    Resource res = new XmlParser().parse(xml);
    if (!(res instanceof DomainResource))
        return "";
    DomainResource dr = (DomainResource) res;
    if (!dr.hasText() || !dr.getText().hasDiv()) {
        RenderingContext lrc = rc.copy().setHeaderLevelContext(headerLevelContext);
        RendererFactory.factory(dr, lrc).render(dr);
    }
    return new XhtmlComposer(XhtmlComposer.HTML).compose(dr.getText().getDiv());
}
Also used : XmlParser(org.hl7.fhir.r5.formats.XmlParser) RenderingContext(org.hl7.fhir.r5.renderers.utils.RenderingContext) DomainResource(org.hl7.fhir.r5.model.DomainResource) Resource(org.hl7.fhir.r5.model.Resource) DomainResource(org.hl7.fhir.r5.model.DomainResource) CanonicalResource(org.hl7.fhir.r5.model.CanonicalResource) XhtmlComposer(org.hl7.fhir.utilities.xhtml.XhtmlComposer)

Example 22 with RenderingContext

use of org.hl7.fhir.r5.renderers.utils.RenderingContext 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 RenderingContext

use of org.hl7.fhir.r5.renderers.utils.RenderingContext in project kindling by HL7.

the class Publisher method generateCompartmentDefinition.

private void generateCompartmentDefinition(Compartment c) throws Exception {
    CompartmentDefinition cpd = new CompartmentDefinition();
    cpd.setId(c.getName());
    cpd.setUrl("http://hl7.org/fhir/CompartmentDefinition/" + c.getName());
    cpd.setName("Base FHIR compartment definition for " + c.getTitle());
    cpd.setStatus(PublicationStatus.DRAFT);
    cpd.setDescription(c.getIdentity() + ". " + c.getDescription());
    cpd.setExperimental(true);
    cpd.setVersion(page.getVersion().toCode());
    cpd.setDate(page.getGenDate().getTime());
    cpd.setPublisher("FHIR Project Team");
    cpd.addContact().getTelecom().add(Factory.newContactPoint(ContactPointSystem.URL, "http://hl7.org/fhir"));
    cpd.setCode(CompartmentType.fromCode(c.getTitle()));
    cpd.setSearch(true);
    for (String rn : page.getDefinitions().sortedResourceNames()) {
        ResourceDefn rd = page.getDefinitions().getResourceByName(rn);
        String rules = c.getResources().get(rd);
        CompartmentDefinitionResourceComponent cc = cpd.addResource().setCode(rd.getName());
        if (!Utilities.noString(rules)) {
            for (String p : rules.split("\\|")) cc.addParam(p.trim());
        }
    }
    RenderingContext lrc = page.getRc().copy().setLocalPrefix("").setTooCostlyNoteEmpty(PageProcessor.TOO_MANY_CODES_TEXT_EMPTY).setTooCostlyNoteNotEmpty(PageProcessor.TOO_MANY_CODES_TEXT_NOT_EMPTY);
    RendererFactory.factory(cpd, lrc).render(cpd);
    FileOutputStream s = new FileOutputStream(page.getFolders().dstDir + "compartmentdefinition-" + c.getName().toLowerCase() + ".xml");
    new XmlParser().setOutputStyle(OutputStyle.PRETTY).compose(s, cpd);
    s.close();
    s = new FileOutputStream(page.getFolders().dstDir + "compartmentdefinition-" + c.getName().toLowerCase() + ".canonical.xml");
    new XmlParser().setOutputStyle(OutputStyle.CANONICAL).compose(s, cpd);
    s.close();
    cloneToXhtml("compartmentdefinition-" + c.getName().toLowerCase(), "Compartment Definition for " + c.getName(), true, "resource-instance:CompartmentDefinition", "Compartment Definition for " + c.getName(), null, wg("fhir"));
    s = new FileOutputStream(page.getFolders().dstDir + "compartmentdefinition-" + c.getName().toLowerCase() + ".json");
    new JsonParser().setOutputStyle(OutputStyle.PRETTY).compose(s, cpd);
    s.close();
    s = new FileOutputStream(page.getFolders().dstDir + "compartmentdefinition-" + c.getName().toLowerCase() + ".canonical.json");
    new JsonParser().setOutputStyle(OutputStyle.CANONICAL).compose(s, cpd);
    s.close();
    jsonToXhtml("compartmentdefinition-" + c.getName().toLowerCase(), "Compartment Definition for " + c.getName(), resource2Json(cpd), "resource-instance:CompartmentDefinition", "Compartment Definition for " + c.getName(), null, wg("fhir"));
    s = new FileOutputStream(page.getFolders().dstDir + "compartmentdefinition-" + c.getName().toLowerCase() + ".ttl");
    new RdfParser().setOutputStyle(OutputStyle.PRETTY).compose(s, cpd);
    s.close();
    ttlToXhtml("compartmentdefinition-" + c.getName().toLowerCase(), "Compartment Definition for " + c.getName(), resource2Ttl(cpd), "resource-instance:CompartmentDefinition", "Compartment Definition for " + c.getName(), null, wg("fhir"));
    Utilities.copyFile(new CSFile(page.getFolders().dstDir + "compartmentdefinition-" + c.getName().toLowerCase() + ".xml"), new CSFile(page.getFolders().dstDir + "examples" + File.separator + "compartmentdefinition-" + c.getName().toLowerCase() + ".xml"));
    addToResourceFeed(cpd, page.getResourceBundle());
}
Also used : RenderingContext(org.hl7.fhir.r5.renderers.utils.RenderingContext) XmlParser(org.hl7.fhir.r5.formats.XmlParser) CompartmentDefinitionResourceComponent(org.hl7.fhir.r5.model.CompartmentDefinition.CompartmentDefinitionResourceComponent) CompartmentDefinition(org.hl7.fhir.r5.model.CompartmentDefinition) FileOutputStream(java.io.FileOutputStream) CSFile(org.hl7.fhir.utilities.CSFile) ResourceDefn(org.hl7.fhir.definitions.model.ResourceDefn) JsonParser(org.hl7.fhir.r5.formats.JsonParser) RdfParser(org.hl7.fhir.r5.formats.RdfParser)

Example 24 with RenderingContext

use of org.hl7.fhir.r5.renderers.utils.RenderingContext in project kindling by HL7.

the class Publisher method generateValueSetPart2.

private void generateValueSetPart2(ValueSet vs) throws Exception {
    String n = vs.getUserString("filename");
    if (n == null)
        n = "valueset-" + vs.getId();
    ImplementationGuideDefn ig = (ImplementationGuideDefn) vs.getUserData(ToolResourceUtilities.NAME_RES_IG);
    if (ig != null)
        n = ig.getCode() + File.separator + n;
    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 ? "../" : "").setTooCostlyNoteEmpty(PageProcessor.TOO_MANY_CODES_TEXT_EMPTY).setTooCostlyNoteNotEmpty(PageProcessor.TOO_MANY_CODES_TEXT_NOT_EMPTY);
        RendererFactory.factory(vs, lrc).render(vs);
    }
    page.getVsValidator().validate(page.getValidationErrors(), n, vs, true, false);
    if (isGenerate) {
        // page.log(" ... "+n, LogMessageType.Process);
        addToResourceFeed(vs, valueSetsFeed, null);
        if (vs.getUserData("path") == null)
            vs.setUserData("path", n + ".html");
        page.setId(vs.getId());
        String sf;
        try {
            sf = page.processPageIncludes(n + ".html", TextFile.fileToString(page.getFolders().templateDir + "template-vs.html"), "valueSet", null, n + ".html", vs, null, "Value Set", ig, null, wg(vs, "vocab"));
        } catch (Exception e) {
            throw new Exception("Error processing " + n + ".html: " + e.getMessage(), e);
        }
        sf = addSectionNumbers(n + ".html", "template-valueset", sf, vsCounter(), ig == null ? 0 : 1, null, ig);
        TextFile.stringToFile(sf, page.getFolders().dstDir + n + ".html");
        try {
            String src = page.processPageIncludesForBook(n + ".html", TextFile.fileToString(page.getFolders().templateDir + "template-vs-book.html"), "valueSet", vs, ig, null);
            cachePage(n + ".html", src, "Value Set " + n, false);
            page.setId(null);
        } catch (Exception e) {
            throw new Exception("Error processing " + n + ".html: " + e.getMessage(), e);
        }
        IParser json = new JsonParser().setOutputStyle(OutputStyle.PRETTY);
        FileOutputStream s = new FileOutputStream(page.getFolders().dstDir + n + ".json");
        json.compose(s, vs);
        s.close();
        json = new JsonParser().setOutputStyle(OutputStyle.CANONICAL);
        s = new FileOutputStream(page.getFolders().dstDir + n + ".canonical.json");
        json.compose(s, vs);
        s.close();
        IParser xml = new XmlParser().setOutputStyle(OutputStyle.PRETTY);
        s = new FileOutputStream(page.getFolders().dstDir + n + ".xml");
        xml.compose(s, vs);
        s.close();
        xml = new XmlParser().setOutputStyle(OutputStyle.CANONICAL);
        s = new FileOutputStream(page.getFolders().dstDir + n + ".canonical.xml");
        xml.compose(s, vs);
        s.close();
        // System.out.println(vs.getUrl());
        cloneToXhtml(n, "Definition for Value Set" + vs.present(), false, "valueset-instance", "Value Set", null, wg("vocab"));
        jsonToXhtml(n, "Definition for Value Set" + vs.present(), resource2Json(vs), "valueset-instance", "Value Set", null, wg("vocab"));
        ttlToXhtml(n, "Definition for Value Set" + vs.present(), resource2Ttl(vs), "valueset-instance", "Value Set", null, wg("vocab"));
    }
}
Also used : RenderingContext(org.hl7.fhir.r5.renderers.utils.RenderingContext) XmlParser(org.hl7.fhir.r5.formats.XmlParser) FileOutputStream(java.io.FileOutputStream) ImplementationGuideDefn(org.hl7.fhir.definitions.model.ImplementationGuideDefn) TransformerException(javax.xml.transform.TransformerException) IOException(java.io.IOException) FHIRException(org.hl7.fhir.exceptions.FHIRException) FileNotFoundException(java.io.FileNotFoundException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IParser(org.hl7.fhir.r5.formats.IParser) JsonParser(org.hl7.fhir.r5.formats.JsonParser)

Example 25 with RenderingContext

use of org.hl7.fhir.r5.renderers.utils.RenderingContext in project kindling by HL7.

the class Publisher method generateConformanceStatement.

private void generateConformanceStatement(boolean full, String name, boolean register) throws Exception {
    pgen = new ProfileGenerator(page.getDefinitions(), page.getWorkerContext(), page, page.getGenDate(), page.getVersion(), dataElements, fpUsages, page.getFolders().rootDir, page.getUml(), page.getRc());
    CapabilityStatement cpbs = new CapabilityStatement();
    cpbs.setId(FormatUtilities.makeId(name));
    cpbs.setUrl("http://hl7.org/fhir/CapabilityStatement/" + name);
    cpbs.setVersion(page.getVersion().toCode());
    cpbs.setName("Base FHIR Capability Statement " + (full ? "(Full)" : "(Empty)"));
    cpbs.setStatus(PublicationStatus.DRAFT);
    cpbs.setExperimental(true);
    cpbs.setDate(page.getGenDate().getTime());
    cpbs.setPublisher("FHIR Project Team");
    cpbs.addContact().getTelecom().add(Factory.newContactPoint(ContactPointSystem.URL, "http://hl7.org/fhir"));
    cpbs.setKind(CapabilityStatementKind.CAPABILITY);
    cpbs.setSoftware(new CapabilityStatementSoftwareComponent());
    cpbs.getSoftware().setName("Insert your software name here...");
    cpbs.setFhirVersion(page.getVersion());
    cpbs.getFormat().add(Factory.newCode("xml"));
    cpbs.getFormat().add(Factory.newCode("json"));
    CapabilityStatementRestComponent rest = new CapabilityStatement.CapabilityStatementRestComponent();
    cpbs.getRest().add(rest);
    rest.setMode(RestfulCapabilityMode.SERVER);
    if (full) {
        rest.setDocumentation("All the functionality defined in FHIR");
        cpbs.setDescription("This is the base Capability Statement for FHIR. It represents a server that provides the full set of functionality defined by FHIR. It is provided to use as a template for system designers to build their own Capability Statements from");
    } else {
        rest.setDocumentation("An empty Capability Statement");
        cpbs.setDescription("This is the base Capability Statement for FHIR. It represents a server that provides the none of the functionality defined by FHIR. It is provided to use as a template for system designers to build their own Capability Statements from. A capability statement has to contain something, so this contains a read of a Capability Statement");
    }
    rest.setSecurity(new CapabilityStatementRestSecurityComponent());
    rest.getSecurity().setCors(true);
    rest.getSecurity().addService().setText("See http://docs.smarthealthit.org/").addCoding().setSystem("http://terminology.hl7.org/CodeSystem/restful-security-service").setCode("SMART-on-FHIR").setDisplay("SMART-on-FHIR");
    rest.getSecurity().setDescription("This is the Capability Statement to declare that the server supports SMART-on-FHIR. See the SMART-on-FHIR docs for the extension that would go with such a server");
    if (full) {
        for (String rn : page.getDefinitions().sortedResourceNames()) {
            ResourceDefn rd = page.getDefinitions().getResourceByName(rn);
            CapabilityStatementRestResourceComponent res = new CapabilityStatement.CapabilityStatementRestResourceComponent();
            rest.getResource().add(res);
            res.setType(rn);
            res.setProfile("http://hl7.org/fhir/StructureDefinition/" + rn);
            genConfInteraction(cpbs, res, TypeRestfulInteraction.READ, "Implemented per the specification (or Insert other doco here)");
            genConfInteraction(cpbs, res, TypeRestfulInteraction.VREAD, "Implemented per the specification (or Insert other doco here)");
            genConfInteraction(cpbs, res, TypeRestfulInteraction.UPDATE, "Implemented per the specification (or Insert other doco here)");
            genConfInteraction(cpbs, res, TypeRestfulInteraction.DELETE, "Implemented per the specification (or Insert other doco here)");
            genConfInteraction(cpbs, res, TypeRestfulInteraction.HISTORYINSTANCE, "Implemented per the specification (or Insert other doco here)");
            genConfInteraction(cpbs, res, TypeRestfulInteraction.HISTORYTYPE, "Implemented per the specification (or Insert other doco here)");
            genConfInteraction(cpbs, res, TypeRestfulInteraction.CREATE, "Implemented per the specification (or Insert other doco here)");
            genConfInteraction(cpbs, res, TypeRestfulInteraction.SEARCHTYPE, "Implemented per the specification (or Insert other doco here)");
            res.setConditionalCreate(true);
            res.setConditionalUpdate(true);
            res.setConditionalDelete(ConditionalDeleteStatus.MULTIPLE);
            res.addReferencePolicy(ReferenceHandlingPolicy.LITERAL);
            res.addReferencePolicy(ReferenceHandlingPolicy.LOGICAL);
            for (SearchParameterDefn i : rd.getSearchParams().values()) {
                res.getSearchParam().add(makeSearchParam(rn, i));
                if (i.getType().equals(SearchType.reference))
                    res.getSearchInclude().add(new StringType(rn + "." + i.getCode()));
            }
            for (String rni : page.getDefinitions().sortedResourceNames()) {
                ResourceDefn rdi = page.getDefinitions().getResourceByName(rni);
                for (SearchParameterDefn ii : rdi.getSearchParams().values()) {
                    if (ii.getType().equals(SearchType.reference) && ii.getTargets().contains(rn))
                        res.getSearchRevInclude().add(new StringType(rni + "." + ii.getCode()));
                }
            }
        }
        genConfInteraction(cpbs, rest, SystemRestfulInteraction.TRANSACTION, "Implemented per the specification (or Insert other doco here)");
        genConfInteraction(cpbs, rest, SystemRestfulInteraction.BATCH, "Implemented per the specification (or Insert other doco here)");
        genConfInteraction(cpbs, rest, SystemRestfulInteraction.HISTORYSYSTEM, "Implemented per the specification (or Insert other doco here)");
        genConfInteraction(cpbs, rest, SystemRestfulInteraction.SEARCHSYSTEM, "Implemented per the specification (or Insert other doco here)");
        for (ResourceDefn rd : page.getDefinitions().getBaseResources().values()) {
            for (SearchParameterDefn i : rd.getSearchParams().values()) rest.getSearchParam().add(makeSearchParam(rd.getName(), i));
            rest.getSearchParam().add(makeSearchParam("something", SearchParamType.STRING, "id", "some doco"));
            rest.getSearchParam().add(makeSearchParam("_list", SearchParamType.TOKEN, "Resource-list", "Retrieval of resources that are referenced by a List resource"));
            rest.getSearchParam().add(makeSearchParam("_has", SearchParamType.COMPOSITE, "Resource-has", "Provides support for reverse chaining"));
            rest.getSearchParam().add(makeSearchParam("_type", SearchParamType.TOKEN, "Resource-type", "Type of resource (when doing cross-resource search"));
            rest.getSearchParam().add(makeSearchParam("_sort", SearchParamType.TOKEN, "Resource-source", "How to sort the resources when returning"));
            rest.getSearchParam().add(makeSearchParam("_count", SearchParamType.NUMBER, "Resource-count", "How many resources to return"));
            rest.getSearchParam().add(makeSearchParam("_include", SearchParamType.TOKEN, "Resource-include", "Control over returning additional resources (see spec)"));
            rest.getSearchParam().add(makeSearchParam("_revinclude", SearchParamType.TOKEN, "Resource-revinclude", "Control over returning additional resources (see spec)"));
            rest.getSearchParam().add(makeSearchParam("_summary", SearchParamType.TOKEN, "Resource-summary", "What kind of information to return"));
            rest.getSearchParam().add(makeSearchParam("_elements", SearchParamType.STRING, "Resource-elements", "What kind of information to return"));
            rest.getSearchParam().add(makeSearchParam("_contained", SearchParamType.TOKEN, "Resource-contained", "Managing search into contained resources"));
            rest.getSearchParam().add(makeSearchParam("_containedType", SearchParamType.TOKEN, "Resource-containedType", "Managing search into contained resources"));
            for (Operation op : rd.getOperations()) rest.addOperation().setName(op.getName()).setDefinition("http://hl7.org/fhir/OperationDefinition/" + rd.getName().toLowerCase() + "-" + op.getName());
        }
        for (String rn : page.getDefinitions().sortedResourceNames()) {
            ResourceDefn r = page.getDefinitions().getResourceByName(rn);
            for (Operation op : r.getOperations()) rest.addOperation().setName(op.getName()).setDefinition("http://hl7.org/fhir/OperationDefinition/" + r.getName().toLowerCase() + "-" + op.getName());
        }
    } else {
    // don't add anything - the metadata operation is implicit
    // CapabilityStatementRestResourceComponent res = new CapabilityStatement.CapabilityStatementRestResourceComponent();
    // rest.getResource().add(res);
    // res.setType("CapabilityStatement");
    // genConfInteraction(cpbs, res, TypeRestfulInteraction.READ, "Read CapabilityStatement Resource");
    }
    if (register) {
        RenderingContext lrc = page.getRc().copy().setLocalPrefix("").setTooCostlyNoteEmpty(PageProcessor.TOO_MANY_CODES_TEXT_EMPTY).setTooCostlyNoteNotEmpty(PageProcessor.TOO_MANY_CODES_TEXT_NOT_EMPTY);
        RendererFactory.factory(cpbs, lrc).render(cpbs);
        FileOutputStream s = new FileOutputStream(page.getFolders().dstDir + "capabilitystatement-" + name + ".xml");
        new XmlParser().setOutputStyle(OutputStyle.PRETTY).compose(s, cpbs);
        s.close();
        s = new FileOutputStream(page.getFolders().dstDir + "capabilitystatement-" + name + ".canonical.xml");
        new XmlParser().setOutputStyle(OutputStyle.CANONICAL).compose(s, cpbs);
        s.close();
        cloneToXhtml("capabilitystatement-" + name + "", "Basic Capability Statement", true, "resource-instance:CapabilityStatement", "Capability Statement", null, wg("fhir"));
        s = new FileOutputStream(page.getFolders().dstDir + "capabilitystatement-" + name + ".json");
        new JsonParser().setOutputStyle(OutputStyle.PRETTY).compose(s, cpbs);
        s.close();
        s = new FileOutputStream(page.getFolders().dstDir + "capabilitystatement-" + name + ".canonical.json");
        new JsonParser().setOutputStyle(OutputStyle.CANONICAL).compose(s, cpbs);
        s.close();
        jsonToXhtml("capabilitystatement-" + name, "Base Capability Statement", resource2Json(cpbs), "resource-instance:CapabilityStatement", "Capability Statement", null, wg("fhir"));
        s = new FileOutputStream(page.getFolders().dstDir + "capabilitystatement-" + name + ".ttl");
        new RdfParser().setOutputStyle(OutputStyle.PRETTY).compose(s, cpbs);
        s.close();
        ttlToXhtml("capabilitystatement-" + name, "Base Capability Statement", resource2Ttl(cpbs), "resource-instance:CapabilityStatement", "Capability Statement", null, wg("fhir"));
        Utilities.copyFile(new CSFile(page.getFolders().dstDir + "capabilitystatement-" + name + ".xml"), new CSFile(page.getFolders().dstDir + "examples" + File.separator + "capabilitystatement-" + name + ".xml"));
    }
    if (buildFlags.get("all")) {
        RenderingContext lrc = page.getRc().copy().setLocalPrefix("");
        RendererFactory.factory(cpbs, lrc).render(cpbs);
        deletefromFeed(ResourceType.CapabilityStatement, name, page.getResourceBundle());
        addToResourceFeed(cpbs, page.getResourceBundle());
    }
}
Also used : RenderingContext(org.hl7.fhir.r5.renderers.utils.RenderingContext) XmlParser(org.hl7.fhir.r5.formats.XmlParser) ProfileGenerator(org.hl7.fhir.definitions.generators.specification.ProfileGenerator) StringType(org.hl7.fhir.r5.model.StringType) SearchParameterDefn(org.hl7.fhir.definitions.model.SearchParameterDefn) Operation(org.hl7.fhir.definitions.model.Operation) CSFile(org.hl7.fhir.utilities.CSFile) ResourceDefn(org.hl7.fhir.definitions.model.ResourceDefn) CapabilityStatementRestSecurityComponent(org.hl7.fhir.r5.model.CapabilityStatement.CapabilityStatementRestSecurityComponent) FileOutputStream(java.io.FileOutputStream) CapabilityStatement(org.hl7.fhir.r5.model.CapabilityStatement) CapabilityStatementSoftwareComponent(org.hl7.fhir.r5.model.CapabilityStatement.CapabilityStatementSoftwareComponent) CapabilityStatementRestComponent(org.hl7.fhir.r5.model.CapabilityStatement.CapabilityStatementRestComponent) CapabilityStatementRestResourceComponent(org.hl7.fhir.r5.model.CapabilityStatement.CapabilityStatementRestResourceComponent) JsonParser(org.hl7.fhir.r5.formats.JsonParser) RdfParser(org.hl7.fhir.r5.formats.RdfParser)

Aggregations

RenderingContext (org.hl7.fhir.r5.renderers.utils.RenderingContext)22 FHIRException (org.hl7.fhir.exceptions.FHIRException)14 FileOutputStream (java.io.FileOutputStream)13 XmlParser (org.hl7.fhir.r5.formats.XmlParser)13 XhtmlComposer (org.hl7.fhir.utilities.xhtml.XhtmlComposer)11 IOException (java.io.IOException)10 ArrayList (java.util.ArrayList)10 FileNotFoundException (java.io.FileNotFoundException)9 JsonParser (org.hl7.fhir.r5.formats.JsonParser)8 Cell (org.hl7.fhir.utilities.xhtml.HierarchicalTableGenerator.Cell)8 TransformerException (javax.xml.transform.TransformerException)6 NotImplementedException (org.apache.commons.lang3.NotImplementedException)6 DefinitionException (org.hl7.fhir.exceptions.DefinitionException)6 PathEngineException (org.hl7.fhir.exceptions.PathEngineException)6 StructureDefinition (org.hl7.fhir.r5.model.StructureDefinition)6 Piece (org.hl7.fhir.utilities.xhtml.HierarchicalTableGenerator.Piece)6 StructureDefinition (org.hl7.fhir.r4b.model.StructureDefinition)5 ValueSet (org.hl7.fhir.r5.model.ValueSet)5 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)4 IParser (org.hl7.fhir.r5.formats.IParser)4