Search in sources :

Example 66 with ProfileUtilities

use of org.hl7.fhir.r5.conformance.ProfileUtilities in project kindling by HL7.

the class IgParser method load.

public void load(String rootDir, ImplementationGuideDefn igd, List<ValidationMessage> issues, Set<String> loadedIgs) throws Exception {
    logger.log(" ..." + igd.getName(), LogMessageType.Process);
    // first: parse the IG, then use it
    String myRoot = Utilities.path(rootDir, "guides", igd.getCode());
    CSFile file = new CSFile(Utilities.path(rootDir, igd.getSource()));
    ImplementationGuide ig = (ImplementationGuide) new XmlParser().parse(new FileInputStream(file));
    if (// for things published in the hl7.org/fhir namespace...
    !ig.getUrl().startsWith("http://hl7.org/fhir/"))
        throw new Exception("Illegal namespace");
    if (!ig.getUrl().equals("http://hl7.org/fhir/" + ig.getId()))
        throw new Exception("Illegal URL");
    if (!ig.hasName())
        throw new Exception("no name on IG");
    ig.setDateElement(new DateTimeType(genDate));
    igd.setName(ig.getName());
    igd.setIg(ig);
    Map<String, Resource> resources = new HashMap<String, Resource>();
    for (ImplementationGuideDependsOnComponent d : ig.getDependsOn()) {
        if (!loadedIgs.contains(d.getUri()))
            throw new Exception("Dependency on " + ig.getName() + " not satisfied: " + d.getUri());
    }
    loadedIgs.add(ig.getUrl());
    // for (UriType bin : ig.getBinary()) {
    // if (!new File(Utilities.path(myRoot, bin.getValue())).exists())
    // throw new Exception("Binary dependency in "+ig.getName()+" not found: "+bin.getValue());
    // igd.getImageList().add(bin.getValue());
    // }
    processPage(ig.getDefinition().getPage(), igd);
    List<Example> exr = new ArrayList<Example>();
    // first pass - verify the resources can be loaded
    for (ImplementationGuideDefinitionResourceComponent r : ig.getDefinition().getResource()) {
        if (!r.hasReference())
            throw new Exception("no source on resource in IG " + ig.getName());
        CSFile fn = new CSFile(Utilities.path(myRoot, r.getReference().getReference()));
        if (!fn.exists())
            throw new Exception("Source " + r.getReference().getReference() + " resource in IG " + ig.getName() + " could not be located @ " + fn.getAbsolutePath());
        String id = Utilities.changeFileExt(fn.getName(), "");
        // we're going to try and load the resource directly.
        // if that fails, then we'll treat it as an example.
        boolean isExample = r.hasExample();
        ResourceType rt = null;
        try {
            rt = new XmlParser().parse(new FileInputStream(fn)).getResourceType();
        } catch (Exception e) {
            rt = null;
            isExample = true;
        }
        if (isExample) {
            if (// which means that non conformance resources must be named
            !r.hasName())
                throw new Exception("no name on resource in IG " + ig.getName());
            Example example = new Example(r.getName(), id, r.getDescription(), fn, false, ExampleType.XmlFile, false);
            example.setIg(igd.getCode());
            if (r.hasExampleCanonicalType()) {
                example.setExampleFor(r.getExampleCanonicalType().asStringValue());
                example.setRegistered(true);
                exr.add(example);
            }
            igd.getExamples().add(example);
            r.setUserData(ToolResourceUtilities.NAME_RES_EXAMPLE, example);
            r.setReference(new Reference(example.getId() + ".html"));
        } else if (rt == ResourceType.ValueSet) {
            ValueSet vs = (ValueSet) new XmlParser().parse(new FileInputStream(fn));
            if (id.startsWith("valueset-"))
                id = id.substring(9);
            vs.setId(id);
            if (vs.getUrl() == null) {
                // Asserting this all the time causes issues for non-HL7 URL value sets
                vs.setUrl("http://hl7.org/fhir/ValueSet/" + id);
            }
            vs.setUserData(ToolResourceUtilities.NAME_RES_IG, igd);
            vs.setUserData("path", igd.getPath() + "valueset-" + id + ".html");
            vs.setUserData("filename", "valueset-" + id);
            if (committee != null) {
                if (!vs.hasExtension(ToolingExtensions.EXT_WORKGROUP)) {
                    vs.addExtension().setUrl(ToolingExtensions.EXT_WORKGROUP).setValue(new CodeType(committee.getCode()));
                } else {
                    String ec = ToolingExtensions.readStringExtension(vs, ToolingExtensions.EXT_WORKGROUP);
                    if (!ec.equals(committee.getCode()))
                        System.out.println("ValueSet " + vs.getUrl() + " WG mismatch 2: is " + ec + ", want to set to " + committee);
                }
            }
            new CodeSystemConvertor(codeSystems).convert(new XmlParser(), vs, fn.getAbsolutePath(), packageInfo);
            // if (id.contains(File.separator))
            igd.getValueSets().add(vs);
            if (!r.hasName())
                r.setName(vs.getName());
            if (!r.hasDescription())
                r.setDescription(vs.getDescription());
            r.setUserData(ToolResourceUtilities.RES_ACTUAL_RESOURCE, vs);
            r.setReference(new Reference(fn.getName()));
        } else if (rt == ResourceType.StructureDefinition) {
            StructureDefinition sd;
            sd = (StructureDefinition) new XmlParser().parse(new CSFileInputStream(fn));
            new ProfileUtilities(context, null, pkp).setIds(sd, false);
            if (sd.getKind() == StructureDefinitionKind.LOGICAL) {
                fn = new CSFile(Utilities.path(myRoot, r.getReference().getReference()));
                LogicalModel lm = new LogicalModel(sd);
                lm.setSource(fn.getAbsolutePath());
                lm.setId(sd.getId());
                igd.getLogicalModels().add(lm);
            } else if ("Extension".equals(sd.getType())) {
                sd.setId(tail(sd.getUrl()));
                sd.setUserData(ToolResourceUtilities.NAME_RES_IG, igd.getCode());
                ToolResourceUtilities.updateUsage(sd, igd.getCode());
                this.context.cacheResource(sd);
            } else {
                Profile pr = new Profile(igd.getCode());
                pr.setSource(fn.getAbsolutePath());
                pr.setTitle(sd.getName());
                if (!sd.hasId())
                    sd.setId(tail(sd.getUrl()));
                // Lloyd: This causes issues for profiles & extensions defined outside of HL7
                // sd.setUrl("http://hl7.org/fhir/StructureDefinition/"+sd.getId());
                pr.forceMetadata("id", sd.getId() + "-profile");
                pr.setSourceType(ConformancePackageSourceType.StructureDefinition);
                ConstraintStructure cs = new ConstraintStructure(sd, igd, wg(sd), fmm(sd), sd.getExperimental());
                pr.getProfiles().add(cs);
                igd.getProfiles().add(pr);
            }
        } else if (rt == ResourceType.Bundle) {
            Dictionary d = new Dictionary(id, r.getName(), igd.getCode(), fn.getAbsolutePath(), igd);
            igd.getDictionaries().add(d);
        } else
            logger.log("Implementation Guides do not yet support " + rt.toString(), LogMessageType.Process);
    // throw new Error("Not implemented yet - type = "+rt.toString());
    // if (r.hasExampleFor()) {
    // if (!resources.containsKey(r.getExampleFor().getReference()))
    // throw new Exception("Unable to resolve example-for reference to "+r.getExampleFor().getReference());
    // }
    }
    // second pass: load the spreadsheets
    for (ImplementationGuideDefinitionGroupingComponent p : ig.getDefinition().getGrouping()) {
        if (!p.hasName())
            throw new Exception("no name on package in IG " + ig.getName());
        for (Extension ex : p.getExtension()) {
            if (ex.getUrl().equals(ToolResourceUtilities.EXT_PROFILE_SPREADSHEET)) {
                String s = ((UriType) ex.getValue()).getValue();
                File fn = new File(Utilities.path(myRoot, s));
                if (!fn.exists())
                    throw new Exception("Spreadsheet " + s + " in package " + p.getName() + " in IG " + ig.getName() + " could not be located");
                Profile pr = new Profile(igd.getCode());
                ex.setUserData(ToolResourceUtilities.NAME_RES_PROFILE, pr);
                pr.setSource(fn.getAbsolutePath());
                pr.setSourceType(ConformancePackageSourceType.Spreadsheet);
                OldSpreadsheetParser sparser = new OldSpreadsheetParser(pr.getCategory(), new CSFileInputStream(pr.getSource()), Utilities.noString(pr.getId()) ? pr.getSource() : pr.getId(), pr.getSource(), igd, rootDir, logger, registry, FHIRVersion.fromCode(context.getVersion()), context, genDate, false, pkp, false, committee, mappings, profileIds, codeSystems, maps, workgroups, exceptionIfExcelNotNormalised);
                sparser.getBindings().putAll(commonBindings);
                sparser.setFolder(Utilities.getDirectoryForFile(pr.getSource()));
                sparser.parseConformancePackage(pr, null, Utilities.getDirectoryForFile(pr.getSource()), pr.getCategory(), issues, null);
                // System.out.println("load "+pr.getId()+" from "+s);
                igd.getProfiles().add(pr);
                // what remains to be done now is to update the package with the loaded resources, but we need to wait for all the profiles to generated, so we'll do that later
                for (BindingSpecification bs : sparser.getBindings().values()) {
                    if (!commonBindings.containsValue(bs) && bs.getValueSet() != null) {
                        ValueSet vs = bs.getValueSet();
                        String path = vs.getUserString("path");
                        path = path.substring(path.lastIndexOf("/") + 1);
                        ig.getDefinition().addResource().setName(vs.getName()).setDescription(vs.getDescription()).setReference(new Reference(path)).setUserData(ToolResourceUtilities.RES_ACTUAL_RESOURCE, vs);
                    }
                }
                // now, register resources for all the things in the spreadsheet
                for (ValueSet vs : sparser.getValuesets()) ig.getDefinition().addResource().setExample(new BooleanType(false)).setName(vs.getName()).setDescription(vs.getDescription()).setReference(new Reference("valueset-" + vs.getId() + ".html")).setUserData(ToolResourceUtilities.RES_ACTUAL_RESOURCE, vs);
                for (StructureDefinition exd : pr.getExtensions()) ig.getDefinition().addResource().setExample(new BooleanType(false)).setName(exd.getName()).setDescription(exd.getDescription()).setReference(new Reference("extension-" + exd.getId().toLowerCase() + ".html")).setUserData(ToolResourceUtilities.RES_ACTUAL_RESOURCE, exd);
                for (ConstraintStructure cs : pr.getProfiles()) {
                    cs.setResourceInfo(ig.getDefinition().addResource());
                    cs.getResourceInfo().setExample(new BooleanType(false)).setName(cs.getDefn().getName()).setDescription(cs.getDefn().getDefinition()).setReference(new Reference(cs.getId().toLowerCase() + ".html"));
                }
            }
            if (ex.getUrl().equals(ToolResourceUtilities.EXT_LOGICAL_SPREADSHEET)) {
                File fn = new CSFile(Utilities.path(myRoot, ((UriType) ex.getValue()).getValue()));
                // String source = Utilities.path(file.getParent(), e.getAttribute("source"));
                String s = fn.getName();
                if (s.endsWith("-spreadsheet.xml"))
                    s = s.substring(0, s.length() - 16);
                String id = igd.getCode() + "-" + s;
                OldSpreadsheetParser sparser = new OldSpreadsheetParser(igd.getCode(), new CSFileInputStream(fn), id, fn.getAbsolutePath(), igd, rootDir, logger, registry, FHIRVersion.fromCode(context.getVersion()), context, genDate, false, pkp, false, committee, mappings, profileIds, codeSystems, maps, workgroups, exceptionIfExcelNotNormalised);
                sparser.getBindings().putAll(commonBindings);
                sparser.setFolder(Utilities.getDirectoryForFile(fn.getAbsolutePath()));
                LogicalModel lm = sparser.parseLogicalModel();
                lm.setId(id);
                lm.setSource(fn.getAbsolutePath());
                lm.getResource().setName(lm.getId());
                igd.getLogicalModels().add(lm);
            }
        }
        ToolingExtensions.removeExtension(p, ToolResourceUtilities.EXT_PROFILE_SPREADSHEET);
        ToolingExtensions.removeExtension(p, ToolResourceUtilities.EXT_LOGICAL_SPREADSHEET);
    }
    for (Example ex : exr) {
        Profile tp = null;
        for (Profile pr : igd.getProfiles()) {
            if (("StructureDefinition/" + pr.getId()).equals(ex.getExampleFor())) {
                tp = pr;
                break;
            } else
                for (ConstraintStructure cc : pr.getProfiles()) {
                    if (("StructureDefinition/" + cc.getId()).equals(ex.getExampleFor())) {
                        tp = pr;
                        break;
                    }
                }
        }
        if (tp != null)
            tp.getExamples().add(ex);
        else
            throw new Exception("no profile found matching exampleFor = " + ex.getExampleFor());
    }
    igd.numberPages();
// // second, parse the old ig, and use that. This is being phased out
// CSFile file = new CSFile(Utilities.path(rootDir, igd.getSource()));
// DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// factory.setNamespaceAware(true);
// DocumentBuilder builder = factory.newDocumentBuilder();
// Document xdoc = builder.parse(new CSFileInputStream(file));
// Element root = xdoc.getDocumentElement();
// if (!root.getNodeName().equals("ig"))
// throw new Exception("wrong base node");
// Element e = XMLUtil.getFirstChild(root);
// while (e != null) {
// if (e.getNodeName().equals("dependsOn")) {
// // we ignore this for now
// } else if (e.getNodeName().equals("publishing")) {
// //        if (e.hasAttribute("homepage"))
// //          igd.setPage(e.getAttribute("homepage"));
// } else if (e.getNodeName().equals("page")) {
// //        igd.getPageList().add(e.getAttribute("source"));
// } else if (e.getNodeName().equals("image")) {
// //        moved above igd.getImageList().add(e.getAttribute("source"));
// } else if (e.getNodeName().equals("valueset")) {
// //        XmlParser xml = new XmlParser();
// //        ValueSet vs = (ValueSet) xml.parse(new CSFileInputStream(Utilities.path(file.getParent(), e.getAttribute("source"))));
// //        String id = Utilities.changeFileExt(new File(Utilities.path(file.getParent(), e.getAttribute("source"))).getName(), "");
// //        if (id.startsWith("valueset-"))
// //          id = id.substring(9);
// //        if (!vs.hasId() || !vs.hasUrl()) {
// //          vs.setId(id);
// //          vs.setUrl("http://hl7.org/fhir/ValueSet/"+vs.getId());
// //        }
// //        vs.setUserData(ToolResourceUtilities.NAME_RES_IG, igd);
// //        vs.setUserData("path", igd.getCode()+File.separator+"valueset-"+vs.getId()+".html");
// //        vs.setUserData("filename", "valueset-"+vs.getId());
// //        vs.setUserData("committee", committee);
// //        igd.getValueSets().add(vs);
// } else if (e.getNodeName().equals("acronym")) {
// igd.getTlas().put(e.getAttribute("target"), e.getAttribute("id"));
// } else if (e.getNodeName().equals("example")) {
// //        String filename = e.getAttribute("source");
// //        File efile = new File(Utilities.path(file.getParent(), filename));
// //        Example example = new Example(e.getAttribute("name"), Utilities.changeFileExt(efile.getName(), ""), e.getAttribute("name"), efile, false, ExampleType.XmlFile, false);
// //        example.setIg(igd.getCode());
// //        igd.getExamples().add(example);
// } else if (e.getNodeName().equals("profile")) {
// //        moved above
// //        Profile p = new Profile(igd.getCode());
// //        p.setSource(Utilities.path(file.getParent(), e.getAttribute("source")));
// //        if ("spreadsheet".equals(e.getAttribute("type"))) {
// //          p.setSourceType(ConformancePackageSourceType.Spreadsheet);
// //          SpreadsheetParser sparser = new SpreadsheetParser(p.getCategory(), new CSFileInputStream(p.getSource()), Utilities.noString(p.getId()) ? p.getSource() : p.getId(), igd,
// //              rootDir, logger, null, context.getVersion(), context, genDate, false, igd.getExtensions(), pkp, false, committee, mappings);
// //          sparser.getBindings().putAll(commonBindings);
// //          sparser.setFolder(Utilities.getDirectoryForFile(p.getSource()));
// //          sparser.parseConformancePackage(p, null, Utilities.getDirectoryForFile(p.getSource()), p.getCategory(), issues);
// //          for (BindingSpecification bs : sparser.getBindings().values()) {
// //            if (!commonBindings.containsValue(bs) && bs.getValueSet() != null) {
// //              ValueSet vs  = bs.getValueSet();
// //              String path = vs.getUserString("filename")+".xml";
// //              ig.getPackage().get(0).addResource().setName(vs.getName()).setDescription(vs.getDescription()).setSource(new UriType(path)).setUserData(ToolResourceUtilities.RES_ACTUAL_RESOURCE, vs);
// //            }
// //          }
// //        } else {
// //          throw new Exception("Unknown profile type in IG : "+e.getNodeName());
// //          // parseConformanceDocument(p, p.getId(), new File(p.getSource()), p.getCategory());
// //        }
// //
// //        String id = e.getAttribute("id");
// //        if (Utilities.noString(id))
// //          id = Utilities.changeFileExt(e.getAttribute("source"), "");
// //        igd.getProfiles().add(p);
// //        Element ex = XMLUtil.getFirstChild(e);
// //        while (ex != null) {
// //          if (ex.getNodeName().equals("example")) {
// //            String filename = ex.getAttribute("source");
// //            Example example = new Example(ex.getAttribute("name"), Utilities.changeFileExt(Utilities.getFileNameForName(filename), ""), ex.getAttribute("name"), new File(Utilities.path(file.getParent(), filename)), false, ExampleType.XmlFile, false);
// //            p.getExamples().add(example);
// //          } else
// //            throw new Exception("Unknown element name in IG: "+ex.getNodeName());
// //          ex = XMLUtil.getNextSibling(ex);
// //        }
// } else if (e.getNodeName().equals("dictionary")) {
// //        Dictionary d = new Dictionary(e.getAttribute("id"), e.getAttribute("name"), igd.getCode(), Utilities.path(Utilities.path(file.getParent(), e.getAttribute("source"))), igd);
// //        igd.getDictionaries().add(d);
// } else if (e.getNodeName().equals("logicalModel")) {
// //        String source = Utilities.path(file.getParent(), e.getAttribute("source"));
// //        String id = igd.getCode()+"-"+e.getAttribute("id");
// //        SpreadsheetParser sparser = new SpreadsheetParser(igd.getCode(), new CSFileInputStream(source), id, igd, rootDir, logger, null, context.getVersion(), context, genDate, false, igd.getExtensions(), pkp, false, committee, mappings);
// //        sparser.getBindings().putAll(commonBindings);
// //        sparser.setFolder(Utilities.getDirectoryForFile(source));
// //        LogicalModel lm = sparser.parseLogicalModel(source);
// //        lm.setId(id);
// //        lm.setSource(source);
// //        lm.getResource().setName(lm.getId());
// //        igd.getLogicalModels().add(lm);
// } else
// throw new Exception("Unknown element name in IG: "+e.getNodeName());
// e = XMLUtil.getNextSibling(e);
// }
}
Also used : Dictionary(org.hl7.fhir.definitions.model.Dictionary) ImplementationGuide(org.hl7.fhir.r5.model.ImplementationGuide) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) CSFile(org.hl7.fhir.utilities.CSFile) Profile(org.hl7.fhir.definitions.model.Profile) UriType(org.hl7.fhir.r5.model.UriType) LogicalModel(org.hl7.fhir.definitions.model.LogicalModel) StructureDefinition(org.hl7.fhir.r5.model.StructureDefinition) Example(org.hl7.fhir.definitions.model.Example) BindingSpecification(org.hl7.fhir.definitions.model.BindingSpecification) ConstraintStructure(org.hl7.fhir.definitions.model.ConstraintStructure) ValueSet(org.hl7.fhir.r5.model.ValueSet) ImplementationGuideDefinitionGroupingComponent(org.hl7.fhir.r5.model.ImplementationGuide.ImplementationGuideDefinitionGroupingComponent) XmlParser(org.hl7.fhir.r5.formats.XmlParser) Reference(org.hl7.fhir.r5.model.Reference) Resource(org.hl7.fhir.r5.model.Resource) BooleanType(org.hl7.fhir.r5.model.BooleanType) ResourceType(org.hl7.fhir.r5.model.ResourceType) CSFileInputStream(org.hl7.fhir.utilities.CSFileInputStream) FileInputStream(java.io.FileInputStream) Extension(org.hl7.fhir.r5.model.Extension) DateTimeType(org.hl7.fhir.r5.model.DateTimeType) ImplementationGuideDependsOnComponent(org.hl7.fhir.r5.model.ImplementationGuide.ImplementationGuideDependsOnComponent) ProfileUtilities(org.hl7.fhir.r5.conformance.ProfileUtilities) CodeType(org.hl7.fhir.r5.model.CodeType) OldSpreadsheetParser(org.hl7.fhir.definitions.parsers.spreadsheets.OldSpreadsheetParser) ImplementationGuideDefinitionResourceComponent(org.hl7.fhir.r5.model.ImplementationGuide.ImplementationGuideDefinitionResourceComponent) CSFile(org.hl7.fhir.utilities.CSFile) File(java.io.File) CSFileInputStream(org.hl7.fhir.utilities.CSFileInputStream)

Example 67 with ProfileUtilities

use of org.hl7.fhir.r5.conformance.ProfileUtilities in project kindling by HL7.

the class OldSpreadsheetParser method processExtension.

private int processExtension(ElementDefn extensions, Sheet sheet, int row, Definitions definitions, String uri, Profile ap, List<ValidationMessage> issues, Map<String, Invariant> invariants, WorkGroup wg) throws Exception {
    // first, we build the extension definition
    StructureDefinition ex = new StructureDefinition();
    ex.setUserData(ToolResourceUtilities.NAME_RES_IG, ig == null ? "core" : ig.getCode());
    ex.setUserData("profile", ap);
    ex.setKind(StructureDefinitionKind.COMPLEXTYPE);
    ex.setType("Extension");
    ex.setBaseDefinition("http://hl7.org/fhir/StructureDefinition/Extension");
    ex.setDerivation(TypeDerivationRule.CONSTRAINT);
    ex.setAbstract(false);
    ex.setFhirVersion(version);
    ex.setVersion(version.toCode());
    if (wg != null)
        ToolingExtensions.setCodeExtension(ex, ToolingExtensions.EXT_WORKGROUP, wg.getCode());
    String fmm = sheet.getColumn(row, "FMM");
    if (Utilities.noString(fmm))
        // default fmm value for extensions
        fmm = "1";
    ToolingExtensions.addIntegerExtension(ex, ToolingExtensions.EXT_FMM_LEVEL, Integer.parseInt(fmm));
    if (ap.hasMetadata("fmm-level"))
        ToolingExtensions.addIntegerExtension(ex, ToolingExtensions.EXT_FMM_LEVEL, Integer.parseInt(ap.getFmmLevel()));
    if (ap.hasMetadata("workgroup"))
        ToolingExtensions.setCodeExtension(ex, ToolingExtensions.EXT_WORKGROUP, ap.getWg());
    ToolResourceUtilities.updateUsage(ex, ap.getCategory());
    String name = sheet.getColumn(row, "Code");
    String context = null;
    if (Utilities.noString(name))
        throw new Exception("No code found on Extension at " + getLocation(row));
    if (name.contains("."))
        throw new Exception("Extension Definition Error: Extension names cannot contain '.': " + name + "  at " + getLocation(row));
    ex.setUrl(uri + name);
    ex.setId(tail(ex.getUrl()));
    ex.setUserData("path", "extension-" + ex.getId().toLowerCase() + ".html");
    ap.getExtensions().add(ex);
    if (context == null) {
        ExtensionContextType ct = readContextType(sheet.getColumn(row, "Context Type"), row);
        if (sheet.hasColumn("Context Invariant"))
            for (String s : sheet.getColumn(row, "Context Invariant").split("~")) ex.addContextInvariant(s);
        String cc = checkContextMacro(sheet.getColumn(row, "Context"));
        if (!Utilities.noString(cc))
            for (String c : cc.split("\\;")) {
                StructureDefinitionContextComponent ec = ex.addContext();
                ec.setExpression(c.trim());
                ec.setType(ct);
                if (definitions != null) {
                    definitions.checkContextValid(ec, this.name, this.context);
                }
            }
    }
    ex.setTitle(sheet.getColumn(row, "Display"));
    ElementDefn exe = new ElementDefn();
    exe.setName(sheet.getColumn(row, "Code"));
    ElementDefn exu = new ElementDefn();
    exu.setName("url");
    exu.setXmlAttribute(true);
    exe.getElements().add(exu);
    exu.setFixed(new UriType(ex.getUrl()));
    exu.getTypes().add(new TypeRef().setName("uri"));
    if (invariants != null) {
        for (Invariant inv : invariants.values()) {
            if (inv.getContext().equals(name))
                exe.getInvariants().put(inv.getId(), inv);
        }
    }
    parseExtensionElement(sheet, row, definitions, exe, false);
    String sl = exe.getShortDefn();
    ex.setName(sheet.getColumn(row, "Name"));
    if (!ex.hasName())
        ex.setName(exe.getName());
    if (!ex.hasName())
        ex.setName(ex.getTitle());
    if (!ex.hasName() && !Utilities.noString(sl))
        ex.setName(sl);
    if (!ex.hasName())
        throw new Exception("Extension " + ex.getUrl() + " missing name at " + getLocation(row));
    ex.setDescription(preProcessMarkdown(exe.getDefinition(), "Extension Definition"));
    ex.setPublisher(ap.metadata("author.name"));
    if (ap.hasMetadata("author.reference"))
        ex.addContact().getTelecom().add(Factory.newContactPoint(ContactPointSystem.URL, ap.metadata("author.reference")));
    // <code> opt Zero+ Coding assist with indexing and finding</code>
    if (ap.hasMetadata("date"))
        ex.setDateElement(Factory.newDateTime(ap.metadata("date").substring(0, 10)));
    else
        ex.setDate(genDate.getTime());
    if (ap.hasMetadata("status"))
        ex.setStatus(PublicationStatus.fromCode(ap.metadata("status")));
    row++;
    if (ig == null || ig.isCore()) {
        if (!ex.getUrl().startsWith("http://hl7.org/fhir/StructureDefinition/") && !ex.getUrl().startsWith("http://fhir-registry.smarthealthit.org/StructureDefinition/"))
            throw new Exception("extension " + ex.getUrl() + " is not valid in the publication tooling");
    } else {
        if (!ex.getUrl().startsWith("http://hl7.org/fhir/StructureDefinition/" + ig.getCode() + "-"))
            throw new Exception("extension " + ex.getUrl() + " is not valid for the IG " + ig.getCode() + " in the publication tooling");
    }
    while (row < sheet.getRows().size() && sheet.getColumn(row, "Code").startsWith(name + ".")) {
        String n = sheet.getColumn(row, "Code");
        ElementDefn p = findContext(exe, n.substring(0, n.lastIndexOf(".")), "Extension Definition " + name);
        ElementDefn child = new ElementDefn();
        p.getElements().add(child);
        child.setName(n.substring(n.lastIndexOf(".") + 1));
        child.setProfileName(child.getName());
        parseExtensionElement(sheet, row, definitions, child, true);
        if (invariants != null) {
            for (Invariant inv : invariants.values()) {
                if (inv.getContext().equals(n))
                    child.getInvariants().put(inv.getId(), inv);
            }
        }
        row++;
    }
    ProfileGenerator gen = new ProfileGenerator(definitions, null, pkp, null, version, null, fpUsages, null, null, rc);
    ProfileUtilities utils = new ProfileUtilities(this.context, issues, pkp);
    gen.convertElements(exe, ex, null);
    ex.getDifferential().getElementFirstRep().getType().clear();
    utils.setIds(ex, false);
    StructureDefinition base = definitions != null ? definitions.getSnapShotForType("Extension") : this.context.fetchResource(StructureDefinition.class, "http://hl7.org/fhir/StructureDefinition/Extension");
    List<String> errors = new ArrayList<String>();
    utils.sortDifferential(base, ex, "extension " + ex.getUrl(), errors, false);
    assert (errors.size() == 0);
    utils.generateSnapshot(base, ex, ex.getUrl(), "http://hl7.org/fhir", ex.getName());
    utils.setIds(ex, true);
    new ExtensionDefinitionValidator(context).validate(ex);
    this.context.cacheResource(ex);
    return row;
}
Also used : Invariant(org.hl7.fhir.definitions.model.Invariant) ProfileGenerator(org.hl7.fhir.definitions.generators.specification.ProfileGenerator) StructureDefinitionContextComponent(org.hl7.fhir.r5.model.StructureDefinition.StructureDefinitionContextComponent) TypeRef(org.hl7.fhir.definitions.model.TypeRef) ElementDefn(org.hl7.fhir.definitions.model.ElementDefn) ArrayList(java.util.ArrayList) FHIRException(org.hl7.fhir.exceptions.FHIRException) UriType(org.hl7.fhir.r5.model.UriType) StructureDefinition(org.hl7.fhir.r5.model.StructureDefinition) ExtensionContextType(org.hl7.fhir.r5.model.StructureDefinition.ExtensionContextType) ProfileUtilities(org.hl7.fhir.r5.conformance.ProfileUtilities) ExtensionDefinitionValidator(org.hl7.fhir.definitions.validation.ExtensionDefinitionValidator)

Example 68 with ProfileUtilities

use of org.hl7.fhir.r5.conformance.ProfileUtilities in project kindling by HL7.

the class Publisher method produceResource2.

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

Example 69 with ProfileUtilities

use of org.hl7.fhir.r5.conformance.ProfileUtilities in project kindling by HL7.

the class Publisher method sortProfile.

private void sortProfile(StructureDefinition diff) throws Exception {
    StructureDefinition base = page.getWorkerContext().fetchResource(StructureDefinition.class, diff.getBaseDefinition());
    if (base == null) {
        throw new Exception("unable to find base profile " + diff.getBaseDefinition() + " for " + diff.getUrl());
    }
    List<String> errors = new ArrayList<String>();
    new ProfileUtilities(page.getWorkerContext(), null, page).sortDifferential(base, diff, diff.getName(), errors, false);
// if (errors.size() > 0)
// throw new Exception("Error sorting profile "+diff.getName()+": "+errors.toString());
}
Also used : StructureDefinition(org.hl7.fhir.r5.model.StructureDefinition) ProfileUtilities(org.hl7.fhir.r5.conformance.ProfileUtilities) ArrayList(java.util.ArrayList) TransformerException(javax.xml.transform.TransformerException) IOException(java.io.IOException) FHIRException(org.hl7.fhir.exceptions.FHIRException) FileNotFoundException(java.io.FileNotFoundException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 70 with ProfileUtilities

use of org.hl7.fhir.r5.conformance.ProfileUtilities in project kindling by HL7.

the class Publisher method processExtension.

private void processExtension(StructureDefinition ex) throws Exception {
    StructureDefinition bd = page.getDefinitions().getSnapShotForBase(ex.getBaseDefinition());
    new ProfileUtilities(page.getWorkerContext(), page.getValidationErrors(), page).generateSnapshot(bd, ex, ex.getUrl(), null, ex.getName());
}
Also used : StructureDefinition(org.hl7.fhir.r5.model.StructureDefinition) ProfileUtilities(org.hl7.fhir.r5.conformance.ProfileUtilities)

Aggregations

ArrayList (java.util.ArrayList)74 FHIRException (org.hl7.fhir.exceptions.FHIRException)59 ValidationMessage (org.hl7.fhir.utilities.validation.ValidationMessage)52 ProfileUtilities (org.hl7.fhir.r5.conformance.ProfileUtilities)48 StructureDefinition (org.hl7.fhir.r5.model.StructureDefinition)38 ProfileUtilities (org.hl7.fhir.dstu3.conformance.ProfileUtilities)21 StructureDefinition (org.hl7.fhir.dstu3.model.StructureDefinition)20 StructureDefinition (org.hl7.fhir.dstu2.model.StructureDefinition)16 ElementDefinition (org.hl7.fhir.r5.model.ElementDefinition)16 FileOutputStream (java.io.FileOutputStream)15 ProfileUtilities (org.hl7.fhir.r4b.conformance.ProfileUtilities)14 IOException (java.io.IOException)13 ElementDefinition (org.hl7.fhir.dstu2.model.ElementDefinition)13 ProfileUtilities (org.hl7.fhir.dstu2.utils.ProfileUtilities)13 ElementDefinition (org.hl7.fhir.dstu3.model.ElementDefinition)13 DefinitionException (org.hl7.fhir.exceptions.DefinitionException)13 ProfileUtilities (org.hl7.fhir.r4.conformance.ProfileUtilities)12 StructureDefinition (org.hl7.fhir.r4b.model.StructureDefinition)12 Test (org.junit.jupiter.api.Test)12 FileNotFoundException (java.io.FileNotFoundException)11