Search in sources :

Example 56 with XhtmlComposer

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

the class Publisher method produceOperation.

private void produceOperation(ImplementationGuideDefn ig, String name, String id, ResourceDefn resource, Operation op, SectionTracker st) throws Exception {
    OperationDefinition opd = new ProfileGenerator(page.getDefinitions(), page.getWorkerContext(), page, page.getGenDate(), page.getVersion(), dataElements, fpUsages, page.getFolders().rootDir, page.getUml(), page.getRc()).generate(name, id, resource.getName(), op, resource);
    String dir = ig == null ? "" : ig.getCode() + File.separator;
    FileOutputStream s = new FileOutputStream(page.getFolders().dstDir + dir + "operation-" + name + ".xml");
    new XmlParser().setOutputStyle(OutputStyle.PRETTY).compose(s, opd);
    s.close();
    s = new FileOutputStream(page.getFolders().dstDir + dir + "operation-" + name + ".canonical.xml");
    new XmlParser().setOutputStyle(OutputStyle.CANONICAL).compose(s, opd);
    s.close();
    cloneToXhtml(dir + "operation-" + name + "", "Operation Definition", true, "resource-instance:OperationDefinition", "Operation definition", resource, resource.getWg());
    s = new FileOutputStream(page.getFolders().dstDir + dir + "operation-" + name + ".json");
    new JsonParser().setOutputStyle(OutputStyle.PRETTY).compose(s, opd);
    s.close();
    s = new FileOutputStream(page.getFolders().dstDir + dir + "operation-" + name + ".canonical.json");
    new JsonParser().setOutputStyle(OutputStyle.CANONICAL).compose(s, opd);
    s.close();
    jsonToXhtml(dir + "operation-" + name, "Operation Definition", resource2Json(opd), "resource-instance:OperationDefinition", "Operation definition", resource, resource.getWg());
    s = new FileOutputStream(page.getFolders().dstDir + dir + "operation-" + name + ".ttl");
    new RdfParser().setOutputStyle(OutputStyle.PRETTY).compose(s, opd);
    s.close();
    ttlToXhtml(dir + "operation-" + name, "Operation Definition", resource2Ttl(opd), "resource-instance:OperationDefinition", "Operation definition", resource, resource.getWg());
    Utilities.copyFile(new CSFile(page.getFolders().dstDir + dir + "operation-" + name + ".xml"), new CSFile(page.getFolders().dstDir + "examples" + File.separator + "operation-" + name + ".xml"));
    if (buildFlags.get("all")) {
        addToResourceFeed(opd, page.getResourceBundle(), name);
        page.getWorkerContext().cacheResource(opd);
    }
    // now we create a page for the operation
    String fnp = resource.getName().toLowerCase() + "-operation-" + op.getName().toLowerCase() + ".html";
    String src = TextFile.fileToString(page.getFolders().templateDir + "template-operation.html");
    src = page.processPageIncludes(fnp, src, "res-Operations", null, "operation-" + name + ".html", op.getResource(), null, "Operation Definition", op, ig, resource, resource.getWg());
    TextFile.stringToFile(insertSectionNumbers(src, st, fnp, 0, null), page.getFolders().dstDir + fnp);
    page.getHTMLChecker().registerFile(fnp, "Operation " + op.getName() + " for " + resource.getName(), HTMLLinkChecker.XHTML_TYPE, true);
    // now, we create an html page from the narrative
    String html = TextFile.fileToString(page.getFolders().templateDir + "template-example.html").replace("<%example%>", new XhtmlComposer(XhtmlComposer.HTML).compose(opd.getText().getDiv()));
    html = page.processPageIncludes(dir + "operation-" + name + ".html", html, "resource-instance:OperationDefinition", null, null, null, "Operation Definition", ig, resource, resource.getWg());
    TextFile.stringToFile(html, page.getFolders().dstDir + dir + "operation-" + name + ".html");
    page.getHTMLChecker().registerFile(dir + "operation-" + name + ".html", "Operation " + op.getName(), HTMLLinkChecker.XHTML_TYPE, true);
// 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");
}
Also used : XmlParser(org.hl7.fhir.r5.formats.XmlParser) ProfileGenerator(org.hl7.fhir.definitions.generators.specification.ProfileGenerator) FileOutputStream(java.io.FileOutputStream) XhtmlComposer(org.hl7.fhir.utilities.xhtml.XhtmlComposer) CSFile(org.hl7.fhir.utilities.CSFile) OperationDefinition(org.hl7.fhir.r5.model.OperationDefinition) JsonParser(org.hl7.fhir.r5.formats.JsonParser) RdfParser(org.hl7.fhir.r5.formats.RdfParser)

Example 57 with XhtmlComposer

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

the class JsonParserBase method composeXhtml.

protected void composeXhtml(String name, XhtmlNode html) throws IOException {
    if (!Utilities.noString(xhtmlMessage)) {
        prop(name, "<div>!-- " + xhtmlMessage + " --></div>");
    } else {
        XhtmlComposer comp = new XhtmlComposer(XhtmlComposer.XML, htmlPretty);
        prop(name, comp.compose(html));
    }
}
Also used : XhtmlComposer(org.hl7.fhir.utilities.xhtml.XhtmlComposer)

Example 58 with XhtmlComposer

use of org.hl7.fhir.utilities.xhtml.XhtmlComposer 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 59 with XhtmlComposer

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

the class NarrativeGenerationTests method test.

@ParameterizedTest(name = "{index}: file {0}")
@MethodSource("data")
public void test(String id, TestDetails test) throws Exception {
    RenderingContext rc = new RenderingContext(context, null, null, "http://hl7.org/fhir", "", null, ResourceRendererMode.END_USER);
    rc.setDestDir("");
    rc.setHeader(test.isHeader());
    rc.setDefinitionsTarget("test.html");
    rc.setTerminologyServiceOptions(TerminologyServiceOptions.defaults());
    rc.setParser(new TestTypeParser());
    // getting timezones correct (well, at least consistent, so tests pass on any computer)
    rc.setLocale(new java.util.Locale("en", "AU"));
    rc.setTimeZoneId(ZoneId.of("Australia/Sydney"));
    rc.setDateTimeFormatString("yyyy-MM-dd'T'HH:mm:ssZZZZZ");
    rc.setDateFormatString("yyyy-MM-dd");
    rc.setMode(test.technical ? ResourceRendererMode.TECHNICAL : ResourceRendererMode.END_USER);
    Resource source;
    if (TestingUtilities.findTestResource("r4b", "narrative", test.getId() + ".json")) {
        source = (Resource) new JsonParser().parse(TestingUtilities.loadTestResourceStream("r4b", "narrative", test.getId() + ".json"));
    } else {
        source = (Resource) new XmlParser().parse(TestingUtilities.loadTestResourceStream("r4b", "narrative", test.getId() + ".xml"));
    }
    XhtmlNode x = RendererFactory.factory(source, rc).build(source);
    String target = TextFile.streamToString(TestingUtilities.loadTestResourceStream("r5", "narrative", test.getId() + ".html"));
    String output = HEADER + new XhtmlComposer(true, true).compose(x) + FOOTER;
    String tfn = TestingUtilities.tempFile("narrative", test.getId() + ".target.html");
    String ofn = TestingUtilities.tempFile("narrative", test.getId() + ".output.html");
    TextFile.stringToFile(target, tfn);
    TextFile.stringToFile(output, ofn);
    String msg = TestingUtilities.checkXMLIsSame(ofn, tfn);
    Assertions.assertTrue(msg == null, "Output does not match expected: " + msg);
    if (test.isMeta()) {
        org.hl7.fhir.r4b.elementmodel.Element e = Manager.parseSingle(context, TestingUtilities.loadTestResourceStream("r5", "narrative", test.getId() + ".xml"), FhirFormat.XML);
        x = RendererFactory.factory(source, rc).render(new ElementWrappers.ResourceWrapperMetaElement(rc, e));
        target = TextFile.streamToString(TestingUtilities.loadTestResourceStream("r4b", "narrative", test.getId() + "-meta.html"));
        output = HEADER + new XhtmlComposer(true, true).compose(x) + FOOTER;
        ofn = TestingUtilities.tempFile("narrative", test.getId() + "-meta.output.html");
        TextFile.stringToFile(output, ofn);
        msg = TestingUtilities.checkXMLIsSame(ofn, tfn);
        Assertions.assertTrue(msg == null, "Meta output does not match expected: " + msg);
    }
}
Also used : RenderingContext(org.hl7.fhir.r4b.renderers.utils.RenderingContext) XmlParser(org.hl7.fhir.r4b.formats.XmlParser) Resource(org.hl7.fhir.r4b.model.Resource) XhtmlNode(org.hl7.fhir.utilities.xhtml.XhtmlNode) XhtmlComposer(org.hl7.fhir.utilities.xhtml.XhtmlComposer) JsonParser(org.hl7.fhir.r4b.formats.JsonParser) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 60 with XhtmlComposer

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

the class NarrativeGeneratorTests method checkDateTimeRendering.

private void checkDateTimeRendering(String src, String lang, String country, ZoneId tz, String fmt, ResourceRendererMode mode, String... expected) throws FHIRFormatError, DefinitionException, IOException {
    rc.setLocale(new java.util.Locale(lang, country));
    rc.setTimeZoneId(tz);
    if (fmt == null) {
        rc.setDateTimeFormat(null);
        rc.setDateFormat(null);
    } else {
        // really, it would be better to test patterns based on FormatStyle here, since
        // that's what will be used in the real world, but
        rc.setDateTimeFormat(DateTimeFormatter.ofPattern(fmt));
        rc.setDateFormat(DateTimeFormatter.ofPattern(fmt));
    }
    rc.setMode(mode);
    DateTimeType dt = new DateTimeType(src);
    String actual = new DataRenderer(rc).display(dt);
    Assert.assertTrue("Actual = " + actual + ", expected one of " + Utilities.toString(expected), Utilities.existsInList(actual, expected));
    XhtmlNode node = new XhtmlNode(NodeType.Element, "p");
    new DataRenderer(rc).render(node, dt);
    actual = new XhtmlComposer(true, false).compose(node);
    Assert.assertTrue(actual.startsWith("<p>"));
    Assert.assertTrue(actual.endsWith("</p>"));
    Assert.assertTrue("Actual = " + actual + ", expected one of " + Utilities.toString(expected), Utilities.existsInList(actual.substring(0, actual.length() - 4).substring(3), expected));
}
Also used : DateTimeType(org.hl7.fhir.r4b.model.DateTimeType) DataRenderer(org.hl7.fhir.r4b.renderers.DataRenderer) Locale(java.util.Locale) XhtmlComposer(org.hl7.fhir.utilities.xhtml.XhtmlComposer) XhtmlNode(org.hl7.fhir.utilities.xhtml.XhtmlNode)

Aggregations

XhtmlComposer (org.hl7.fhir.utilities.xhtml.XhtmlComposer)78 XhtmlNode (org.hl7.fhir.utilities.xhtml.XhtmlNode)31 FHIRException (org.hl7.fhir.exceptions.FHIRException)15 IOException (java.io.IOException)14 FileOutputStream (java.io.FileOutputStream)13 NotImplementedException (org.apache.commons.lang3.NotImplementedException)11 XhtmlParser (org.hl7.fhir.utilities.xhtml.XhtmlParser)11 File (java.io.File)10 FileNotFoundException (java.io.FileNotFoundException)10 DefinitionException (org.hl7.fhir.exceptions.DefinitionException)10 RenderingContext (org.hl7.fhir.r5.renderers.utils.RenderingContext)10 FileInputStream (java.io.FileInputStream)8 UnsupportedEncodingException (java.io.UnsupportedEncodingException)8 HashMap (java.util.HashMap)7 TransformerException (javax.xml.transform.TransformerException)7 XmlParser (org.hl7.fhir.r5.formats.XmlParser)7 ValueSet (org.hl7.fhir.r5.model.ValueSet)7 CanonicalResource (org.hl7.fhir.r5.model.CanonicalResource)6 URISyntaxException (java.net.URISyntaxException)5 TransformerConfigurationException (javax.xml.transform.TransformerConfigurationException)5