Search in sources :

Example 51 with ImplementationGuideDefn

use of org.hl7.fhir.definitions.model.ImplementationGuideDefn in project kindling by HL7.

the class OldSpreadsheetParser method readPackages.

private void readPackages(ResourceDefn defn, Sheet sheet) throws Exception {
    if (sheet != null) {
        for (int row = 0; row < sheet.rows.size(); row++) {
            String name = sheet.getColumn(row, "Name");
            if (name != null && !name.equals("") && !name.startsWith("!")) {
                Profile pack = new Profile(sheet.getColumn(row, "IG Name"));
                if (Utilities.noString(pack.getCategory()))
                    throw new Exception("Missing IG Name at " + getLocation(row));
                if (!definitions.getIgs().containsKey(pack.getCategory()))
                    throw new Exception("IG Name '" + pack.getCategory() + "' is not registered in [igs] in fhir.ini at " + getLocation(row));
                ImplementationGuideDefn ig = definitions.getIgs().get(pack.getCategory());
                if (!Utilities.noString(ig.getSource()))
                    throw new Exception("Implementation Guides that have their own structured definition cannot be registered directly in a source spreadsheet (" + name + ")");
                pack.setTitle(name);
                // todo-profile
                pack.setSource(checkFile(sheet, row, "Source", false, sheet.getColumn(row, "Filename")));
                String type = sheet.getColumn(row, "Type");
                if ("bundle".equalsIgnoreCase(type))
                    pack.setSourceType(ConformancePackageSourceType.Bundle);
                else if ("spreadsheet".equalsIgnoreCase(type))
                    pack.setSourceType(ConformancePackageSourceType.Spreadsheet);
                else if ("structuredefinition".equalsIgnoreCase(type))
                    pack.setSourceType(ConformancePackageSourceType.StructureDefinition);
                else
                    throw new Exception("Unknown source type: " + type + " at " + getLocation(row));
                // todo-profile
                String example = checkFile(sheet, row, "Example", true, null);
                if (example != null)
                    pack.getExamples().add(new Example(example, Utilities.fileTitle(example), "General Example for " + pack.getSource(), new File(example), true, ExampleType.XmlFile, isAbstract));
                defn.getConformancePackages().add(pack);
            }
        }
    }
}
Also used : Example(org.hl7.fhir.definitions.model.Example) OperationExample(org.hl7.fhir.definitions.model.Operation.OperationExample) ImplementationGuideDefn(org.hl7.fhir.definitions.model.ImplementationGuideDefn) IniFile(org.hl7.fhir.utilities.IniFile) File(java.io.File) CSFile(org.hl7.fhir.utilities.CSFile) TextFile(org.hl7.fhir.utilities.TextFile) Profile(org.hl7.fhir.definitions.model.Profile) FHIRException(org.hl7.fhir.exceptions.FHIRException)

Example 52 with ImplementationGuideDefn

use of org.hl7.fhir.definitions.model.ImplementationGuideDefn in project kindling by HL7.

the class SourceParser method parse.

public void parse(Calendar genDate, List<ValidationMessage> issues) throws Exception {
    logger.log("Loading", LogMessageType.Process);
    loadNormativePackages();
    loadWorkGroups();
    loadW5s();
    loadMappingSpaces();
    loadGlobalBindings();
    loadExternals();
    loadTLAs();
    loadIgs();
    loadTypePages();
    loadDictionaries();
    loadStyleExemptions();
    logger.log("Load Code Systems", LogMessageType.Process);
    String[] pn = ini.getPropertyNames("codesystems");
    if (pn != null) {
        for (String n : pn) {
            loadCodeSystem(n);
        }
    }
    logger.log("Load Value Sets", LogMessageType.Process);
    pn = ini.getPropertyNames("valuesets");
    if (pn != null) {
        for (String n : pn) {
            loadValueSet(n);
        }
    }
    loadCommonSearchParameters();
    loadPrimitives();
    for (String id : ini.getPropertyNames("search-rules")) {
        definitions.seachRule(id, ini.getStringProperty("search-rules", id));
    }
    for (String id : ini.getPropertyNames("valueset-fixup")) {
        definitions.getVsFixups().add(id);
    }
    for (String n : ini.getPropertyNames("infrastructure")) {
        loadCompositeType(n, definitions.getInfrastructure(), "5", "abstract".equals(ini.getStringProperty("infrastructure", n)));
    }
    for (String n : ini.getPropertyNames("types")) {
        loadCompositeType(n, definitions.getTypes(), "5", "abstract".equals(ini.getStringProperty("types", n)));
    }
    String[] shared = ini.getPropertyNames("shared");
    if (shared != null) {
        for (String n : shared) {
            definitions.getShared().add(loadCompositeType(n, definitions.getTypes(), "2", "abstract".equals(ini.getStringProperty("shared", n))));
        }
    }
    String[] logical = ini.getPropertyNames("logical");
    if (logical != null) {
        for (String n : logical) {
            definitions.getIgs().get("core").getLogicalModels().add(loadLogicalModel(n));
        }
    }
    // basic infrastructure
    for (String n : ini.getPropertyNames("resource-infrastructure")) {
        String[] parts = ini.getStringProperty("resource-infrastructure", n).split("\\,");
        boolean isAbstract = false;
        boolean isInterface = false;
        if (parts[0].equals("abstract")) {
            isAbstract = true;
        } else if (parts[0].equals("interface")) {
            isAbstract = true;
            isInterface = true;
        }
        ResourceDefn r = loadResource(n, null, isAbstract, false, parts[1], isInterface);
        r.setAbstract(isAbstract);
        r.setInterface(isInterface);
        definitions.getBaseResources().put(parts[1], r);
    }
    if (ini.getPropertyNames("resource-templates") != null) {
        logger.log("Load Resource Templates", LogMessageType.Process);
        for (String n : ini.getPropertyNames("resource-templates")) {
            loadResource(n, definitions.getResourceTemplates(), false, true, ini.getStringProperty("resource-templates", n), false);
        }
    }
    logger.log("Load Resources", LogMessageType.Process);
    for (String n : ini.getPropertyNames("resources")) {
        loadResource(n, definitions.getResources(), false, false, ini.getStringProperty("resources", n), false);
    }
    processSearchExpressions();
    processContainerExamples();
    logger.log("Load Extras", LogMessageType.Process);
    loadCompartments();
    loadStatusCodes();
    buildSpecialValues();
    for (String n : ini.getPropertyNames("svg")) {
        definitions.getDiagrams().put(n, ini.getStringProperty("svg", n));
    }
    for (String n : ini.getPropertyNames("special-resources")) {
        definitions.getAggregationEndpoints().add(n);
    }
    logger.log("Load Profiles", LogMessageType.Process);
    for (String n : ini.getPropertyNames("profiles")) {
        // todo-profile: rename this
        loadConformancePackages(n, issues);
    }
    for (ResourceDefn r : definitions.getBaseResources().values()) {
        findValueSets(r.getRoot());
    }
    for (ResourceDefn r : definitions.getResources().values()) {
        findValueSets(r.getRoot());
    }
    for (ResourceDefn r : definitions.getBaseResources().values()) {
        for (Profile p : r.getConformancePackages()) {
            loadConformancePackage(p, issues, r.getWg());
        }
    }
    for (ResourceDefn r : definitions.getResources().values()) {
        for (Profile p : r.getConformancePackages()) {
            loadConformancePackage(p, issues, r.getWg());
        }
    }
    definitions.setLoaded(true);
    for (ImplementationGuideDefn ig : definitions.getSortedIgs()) {
        if (!Utilities.noString(ig.getSource())) {
            try {
                new IgParser(page, page.getWorkerContext(), page.getGenDate(), page, definitions.getCommonBindings(), wg(ig.getCommittee()), definitions.getMapTypes(), definitions.getProfileIds(), definitions.getCodeSystems(), registry, page.getConceptMaps(), definitions.getWorkgroups(), exceptionIfExcelNotNormalised, page.packageInfo()).load(rootDir, ig, issues, igNames);
                // register what needs registering
                for (ValueSet vs : ig.getValueSets()) {
                    definitions.getExtraValuesets().put(vs.getId(), vs);
                    context.cacheResource(vs);
                }
                for (Example ex : ig.getExamples()) {
                    definitions.getResourceByName(ex.getResourceName()).getExamples().add(ex);
                }
                for (Profile p : ig.getProfiles()) {
                    if (definitions.getPackMap().containsKey(p.getId())) {
                        throw new Exception("Duplicate Pack id " + p.getId());
                    }
                    definitions.getPackList().add(p);
                    definitions.getPackMap().put(p.getId(), p);
                }
                for (Dictionary d : ig.getDictionaries()) {
                    definitions.getDictionaries().put(d.getId(), d);
                }
            } catch (Exception e) {
                throw new Exception("Error reading IG " + ig.getSource() + ": " + e.getMessage(), e);
            }
        }
    }
    closeTemplates();
}
Also used : Dictionary(org.hl7.fhir.definitions.model.Dictionary) Example(org.hl7.fhir.definitions.model.Example) ImplementationGuideDefn(org.hl7.fhir.definitions.model.ImplementationGuideDefn) ResourceDefn(org.hl7.fhir.definitions.model.ResourceDefn) ValueSet(org.hl7.fhir.r5.model.ValueSet) Profile(org.hl7.fhir.definitions.model.Profile) IOException(java.io.IOException) FHIRException(org.hl7.fhir.exceptions.FHIRException) FileNotFoundException(java.io.FileNotFoundException) SAXException(org.xml.sax.SAXException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 53 with ImplementationGuideDefn

use of org.hl7.fhir.definitions.model.ImplementationGuideDefn in project kindling by HL7.

the class Publisher method producePage.

// private void validateProfile(ProfileDefn profile) throws FileNotFoundException, Exception {
// for (ResourceDefn c : profile.getResources()) {
// StructureDefinition resource = loadResourceProfile(c.getName());
// ProfileValidator v = new ProfileValidator();
// v.setCandidate(c);
// v.setProfile(resource);
// v.setTypes(typeFeed);
// List<String> errors = v.evaluate();
// if (errors.size() > 0)
// throw new Exception("Error validating " + profile.metadata("name") + ": " + errors.toString());
// }
// }
// private void produceFutureReference(String n) throws Exception {
// ElementDefn e = new ElementDefn();
// e.setName(page.getIni().getStringProperty("future-resources", n));
// }
/*
  private StructureDefinition loadResourceProfile(String name) throws FileNotFoundException, Exception {
    XmlParser xml = new XmlParser();
    try {
      return (StructureDefinition) xml.parse(new CSFileInputStream(page.getFolders().dstDir + name.toLowerCase() + ".profile.xml"));
    } catch (Exception e) {
      throw new Exception("error parsing " + name, e);
    }
  }
  */
// private void produceIgPage(String source, String file, String logicalName, ImplementationGuideDefn ig) throws Exception {
// String src = TextFile.fileToString(source);
// src = page.processPageIncludes(file, src, "page", null, null, null, logicalName, null);
// // before we save this page out, we're going to figure out what it's index
// // is, and number the headers if we can
// 
// if (Utilities.noString(logicalName))
// logicalName = Utilities.fileTitle(file);
// 
// TextFile.stringToFile(src, page.getFolders().dstDir + file);
// src = addSectionNumbers(file, logicalName, src, null, 0, null, ig);
// 
// TextFile.stringToFile(src, page.getFolders().dstDir + file);
// 
// src = TextFile.fileToString(source).replace("<body>", "<body style=\"margin: 10px\">");
// src = page.processPageIncludesForBook(file, src, "page", null, null);
// cachePage(file, src, logicalName);
// }
// 
private void producePage(String file, String logicalName) throws Exception {
    String src = TextFile.fileToString(page.getFolders().srcDir + file);
    src = page.processPageIncludes(file, src, "page", null, null, null, logicalName, null, null, null);
    if (Utilities.noString(logicalName))
        logicalName = Utilities.fileTitle(file);
    TextFile.stringToFile(src, page.getFolders().dstDir + file);
    DocumentHolder doch = new DocumentHolder();
    src = addSectionNumbers(file, logicalName, src, null, 0, doch, null);
    if (!page.getDefinitions().getStructuralPages().contains(file)) {
        XhtmlNode fmm = findId(doch.doc, "fmm");
        XhtmlNode wg = findId(doch.doc, "wg");
        if (fmm == null)
            page.getValidationErrors().add(new ValidationMessage(Source.Publisher, IssueType.BUSINESSRULE, -1, -1, file, "Page has no fmm level", IssueSeverity.ERROR));
        else
            page.getDefinitions().page(file).setFmm(get2ndPart(fmm.allText()));
        if (wg == null)
            page.getValidationErrors().add(new ValidationMessage(Source.Publisher, IssueType.BUSINESSRULE, -1, -1, file, "Page has no workgroup", IssueSeverity.ERROR));
        else
            page.getDefinitions().page(file).setWg(wg.getChildNodes().get(0).allText());
    }
    TextFile.stringToFile(src, page.getFolders().dstDir + file);
    src = TextFile.fileToString(page.getFolders().srcDir + file).replace("<body>", "<body style=\"margin: 10px\">");
    src = page.processPageIncludesForBook(file, src, "page", null, null, null);
    cachePage(file, src, logicalName, true);
}
Also used : ValidationMessage(org.hl7.fhir.utilities.validation.ValidationMessage) XhtmlNode(org.hl7.fhir.utilities.xhtml.XhtmlNode)

Example 54 with ImplementationGuideDefn

use of org.hl7.fhir.definitions.model.ImplementationGuideDefn in project kindling by HL7.

the class Publisher method validationProcess.

private void validationProcess() throws Exception {
    if (!isPostPR) {
        if (buildFlags.get("all"))
            runJUnitTestsInProcess();
        page.log("Validating Examples", LogMessageType.Process);
        ExampleInspector ei = new ExampleInspector(page.getWorkerContext(), page, page.getFolders().dstDir, Utilities.path(page.getFolders().rootDir, "tools", "schematron"), page.getValidationErrors(), page.getDefinitions(), page.getVersion());
        page.log(".. Loading", LogMessageType.Process);
        ei.prepare();
        for (String rname : page.getDefinitions().sortedResourceNames()) {
            ResourceDefn r = page.getDefinitions().getResources().get(rname);
            if (wantBuild(rname)) {
                for (Example e : r.getExamples()) {
                    String n = e.getTitle();
                    ImplementationGuideDefn ig = e.getIg() == null ? null : page.getDefinitions().getIgs().get(e.getIg());
                    if (ig != null)
                        n = ig.getCode() + File.separator + n;
                    if (validateId == null || validateId.equals(n))
                        ei.validate(n, rname);
                }
                for (Profile e : r.getConformancePackages()) {
                    for (Example en : e.getExamples()) {
                        ImplementationGuideDefn ig = en.getIg() == null ? null : page.getDefinitions().getIgs().get(en.getIg());
                        String prefix = (ig == null || ig.isCore()) ? "" : ig.getCode() + File.separator;
                        String n = prefix + Utilities.changeFileExt(en.getTitle(), "");
                        if (validateId == null || validateId.equals(n))
                            ei.validate(n, rname, e.getProfiles().get(0).getResource());
                    }
                }
            }
        }
        for (ImplementationGuideDefn ig : page.getDefinitions().getSortedIgs()) {
            String prefix = (ig == null || ig.isCore()) ? "" : ig.getCode() + File.separator;
            for (Example ex : ig.getExamples()) {
                String n = ex.getTitle();
                ei.validate(prefix + n, ex.getResourceName());
            }
            for (Profile pck : ig.getProfiles()) {
                for (Example en : pck.getExamples()) {
                    ei.validate(prefix + Utilities.changeFileExt(en.getTitle(), ""), en.getResourceName(), pck.getProfiles().get(0).getResource());
                }
            }
        }
        if (buildFlags.get("all") && validateBundles) {
            if (validateId == null || validateId.equals("valuesets"))
                ei.validate("valuesets", "Bundle");
            if (validateId == null || validateId.equals("conceptmaps"))
                ei.validate("conceptmaps", "Bundle");
            if (validateId == null || validateId.equals("profiles-types"))
                ei.validate("profiles-types", "Bundle");
            if (validateId == null || validateId.equals("profiles-resources"))
                ei.validate("profiles-resources", "Bundle");
            if (validateId == null || validateId.equals("profiles-others"))
                ei.validate("profiles-others", "Bundle");
            if (validateId == null || validateId.equals("search-parameters"))
                ei.validate("search-parameters", "Bundle");
            if (validateId == null || validateId.equals("extension-definitions"))
                ei.validate("extension-definitions", "Bundle");
        }
        ei.summarise();
        if (buildFlags.get("all"))
            runJUnitTestsEnd();
        if (buildFlags.get("all") && isGenerate)
            produceCoverageWarnings();
        if (buildFlags.get("all"))
            miscValidation();
    }
}
Also used : Example(org.hl7.fhir.definitions.model.Example) ImplementationGuideDefn(org.hl7.fhir.definitions.model.ImplementationGuideDefn) ResourceDefn(org.hl7.fhir.definitions.model.ResourceDefn) Profile(org.hl7.fhir.definitions.model.Profile)

Example 55 with ImplementationGuideDefn

use of org.hl7.fhir.definitions.model.ImplementationGuideDefn 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)

Aggregations

ImplementationGuideDefn (org.hl7.fhir.definitions.model.ImplementationGuideDefn)34 FHIRException (org.hl7.fhir.exceptions.FHIRException)25 FileNotFoundException (java.io.FileNotFoundException)22 IOException (java.io.IOException)22 TransformerException (javax.xml.transform.TransformerException)21 CSFile (org.hl7.fhir.utilities.CSFile)21 StructureDefinition (org.hl7.fhir.r5.model.StructureDefinition)19 CommaSeparatedStringBuilder (org.hl7.fhir.utilities.CommaSeparatedStringBuilder)18 ContactPoint (org.hl7.fhir.r5.model.ContactPoint)17 File (java.io.File)16 ArrayList (java.util.ArrayList)16 Profile (org.hl7.fhir.definitions.model.Profile)16 ValueSet (org.hl7.fhir.r5.model.ValueSet)15 IniFile (org.hl7.fhir.utilities.IniFile)15 TextFile (org.hl7.fhir.utilities.TextFile)15 Example (org.hl7.fhir.definitions.model.Example)14 UnsupportedEncodingException (java.io.UnsupportedEncodingException)11 URISyntaxException (java.net.URISyntaxException)11 HashMap (java.util.HashMap)10 TransformerConfigurationException (javax.xml.transform.TransformerConfigurationException)10