Search in sources :

Example 21 with PackageInfo

use of org.hl7.fhir.utilities.npm.PackageInfo 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 22 with PackageInfo

use of org.hl7.fhir.utilities.npm.PackageInfo in project kindling by HL7.

the class OldSpreadsheetParser method loadValueSet.

private ValueSet loadValueSet(String ref) throws Exception {
    if (!ref.startsWith("valueset-"))
        throw new Exception("Value set file names must start with 'valueset-'");
    IParser p;
    String filename;
    if (new File(Utilities.path(folder, ref + ".xml")).exists()) {
        p = new XmlParser();
        filename = Utilities.path(folder, ref + ".xml");
    } else if (new File(Utilities.path(folder, ref + ".json")).exists()) {
        p = new JsonParser();
        filename = Utilities.path(folder, ref + ".json");
    } else if (new File(Utilities.path(dataTypesFolder, ref + ".xml")).exists()) {
        p = new XmlParser();
        filename = Utilities.path(dataTypesFolder, ref + ".xml");
    } else if (new File(Utilities.path(dataTypesFolder, ref + ".json")).exists()) {
        p = new JsonParser();
        filename = Utilities.path(dataTypesFolder, ref + ".json");
    } else
        throw new Exception("Unable to find source for " + ref + " in " + folder + " (" + Utilities.path(folder, ref + ".xml/json)"));
    ValueSet result;
    try {
        CSFileInputStream input = null;
        try {
            input = new CSFileInputStream(filename);
            result = ValueSetUtilities.makeShareable((ValueSet) p.parse(input));
        } finally {
            IOUtils.closeQuietly(input);
        }
    } catch (Exception e) {
        throw new Exception("Error loading value set '" + filename + "': " + e.getMessage(), e);
    }
    result.setId(igSuffix(ig) + ref.substring(9));
    result.setUrl("http://hl7.org/fhir/ValueSet/" + igSuffix(ig) + ref.substring(9));
    if (!result.hasTitle())
        result.setTitle(Utilities.capitalize(Utilities.unCamelCase(result.getName())));
    if (!result.hasExperimental())
        result.setExperimental(false);
    if (!result.hasVersion() || result.getUrl().startsWith("http://hl7.org/fhir"))
        result.setVersion(version.toCode());
    result.setUserData("filename", ref);
    result.setUserData("path", ((ig == null || ig.isCore()) ? "" : ig.getCode() + "/") + ref + ".html");
    if (!result.hasExtension(ToolingExtensions.EXT_WORKGROUP)) {
        result.addExtension().setUrl(ToolingExtensions.EXT_WORKGROUP).setValue(new CodeType(committee.getCode()));
    } else {
        String ec = ToolingExtensions.readStringExtension(result, ToolingExtensions.EXT_WORKGROUP);
        if (!ec.equals(committee.getCode()))
            System.out.println("ValueSet " + result.getUrl() + " WG mismatch 5: is " + ec + ", want to set to " + committee.getCode());
    }
    new CodeSystemConvertor(codeSystems).convert(p, result, filename, packageInfo);
    valuesets.add(result);
    return result;
}
Also used : XmlParser(org.hl7.fhir.r5.formats.XmlParser) XLSXmlParser(org.hl7.fhir.utilities.xls.XLSXmlParser) CodeSystemConvertor(org.hl7.fhir.definitions.parsers.CodeSystemConvertor) CodeType(org.hl7.fhir.r5.model.CodeType) IniFile(org.hl7.fhir.utilities.IniFile) File(java.io.File) CSFile(org.hl7.fhir.utilities.CSFile) TextFile(org.hl7.fhir.utilities.TextFile) ValueSet(org.hl7.fhir.r5.model.ValueSet) FHIRException(org.hl7.fhir.exceptions.FHIRException) CSFileInputStream(org.hl7.fhir.utilities.CSFileInputStream) IParser(org.hl7.fhir.r5.formats.IParser) JsonParser(org.hl7.fhir.r5.formats.JsonParser)

Example 23 with PackageInfo

use of org.hl7.fhir.utilities.npm.PackageInfo in project kindling by HL7.

the class BindingsParser method processLine.

private void processLine(List<BindingSpecification> results, Sheet sheet, int row) throws Exception {
    BindingSpecification cd = new BindingSpecification("core", sheet.getColumn(row, "Binding Name"), true);
    if (!cd.getName().startsWith("!")) {
        if (Character.isLowerCase(cd.getName().charAt(0)))
            throw new Exception("binding name " + cd.getName() + " is illegal - must start with a capital letter");
        cd.setDefinition(Utilities.appendPeriod(sheet.getColumn(row, "Definition")));
        cd.setBindingMethod(readBinding(sheet.getColumn(row, "Binding"), cd.getName() + " in " + filename));
        boolean utg = "y".equals(sheet.getColumn(row, "UTG"));
        String ref = sheet.getColumn(row, "Reference");
        if (!cd.getBinding().equals(BindingMethod.Unbound) && Utilities.noString(ref))
            throw new Exception("binding " + cd.getName() + " is missing a reference");
        if (cd.getBinding() == BindingMethod.CodeList) {
            cd.setValueSet(new ValueSet());
            cd.getValueSet().setId(ref.substring(1));
            cd.getValueSet().setUrl("http://hl7.org/fhir/ValueSet/" + ref.substring(1));
            cd.getValueSet().setVersion(version);
            if (!Utilities.noString(sheet.getColumn(row, "Committee"))) {
                cd.getValueSet().addExtension().setUrl(ToolingExtensions.EXT_WORKGROUP).setValue(new CodeType(sheet.getColumn(row, "Committee").toLowerCase()));
            }
            cd.getValueSet().setUserData("filename", "valueset-" + cd.getValueSet().getId());
            cd.getValueSet().setUserData("path", "valueset-" + cd.getValueSet().getId() + ".html");
            cd.getValueSet().setName(cd.getName());
            cd.getValueSet().setTitle(cd.getName());
            cd.getValueSet().setDateElement(new DateTimeType(genDate));
            cd.getValueSet().setStatus(PublicationStatus.DRAFT);
            cd.getValueSet().setDescription(sheet.getColumn(row, "Description"));
            if (!cd.getValueSet().hasDescription())
                cd.getValueSet().setDescription(cd.getDefinition());
            if (!ref.startsWith("#"))
                throw new Exception("Error parsing binding " + cd.getName() + ": code list reference '" + ref + "' must started with '#'");
            Sheet cs = xls.getSheets().get(ref.substring(1));
            if (cs == null)
                throw new Exception("Error parsing binding " + cd.getName() + ": code list reference '" + ref + "' not resolved");
            new CodeListToValueSetParser(cs, ref.substring(1), cd.getValueSet(), version, codeSystems, maps, packageInfo).execute(sheet.getColumn(row, "v2"), sheet.getColumn(row, "v3"), utg);
        } else if (cd.getBinding() == BindingMethod.ValueSet) {
            if (ref.startsWith("http:")) {
                // will sort this out later
                cd.setReference(sheet.getColumn(row, "Reference"));
            } else
                cd.setValueSet(loadValueSet(ref, sheet.getColumn(row, "Committee").toLowerCase()));
            String max = sheet.getColumn(row, "Max");
            if (!Utilities.noString(max))
                if (max.startsWith("http:")) {
                    // will sort this out later
                    cd.setMaxReference(max);
                } else
                    cd.setMaxValueSet(loadValueSet(max, sheet.getColumn(row, "Committee").toLowerCase()));
        } else if (cd.getBinding() == BindingMethod.Special) {
            cd.setValueSet(new ValueSet());
            cd.getValueSet().setId(ref.substring(1));
            cd.getValueSet().setUrl("http://hl7.org/fhir/ValueSet/" + ref.substring(1));
            cd.getValueSet().setVersion(version);
            cd.getValueSet().setName(cd.getName());
        // do nothing more: this will get filled out once all the resources are loaded
        }
        // do this anyway in the short term
        cd.setReference(sheet.getColumn(row, "Reference"));
        if (cd.getValueSet() != null) {
            touchVS(cd.getValueSet());
            ValueSetUtilities.markStatus(cd.getValueSet(), Utilities.noString(sheet.getColumn(row, "Committee")) ? "vocab" : sheet.getColumn(row, "Committee").toLowerCase(), null, null, Utilities.noString(sheet.getColumn(row, "FMM")) ? null : sheet.getColumn(row, "FMM"), null, Utilities.noString(sheet.getColumn(row, "Normative-Version")) ? null : sheet.getColumn(row, "Normative-Version"));
        }
        if (cd.getMaxValueSet() != null) {
            touchVS(cd.getMaxValueSet());
            ValueSetUtilities.markStatus(cd.getMaxValueSet(), Utilities.noString(sheet.getColumn(row, "Committee")) ? "vocab" : sheet.getColumn(row, "Committee").toLowerCase(), null, null, Utilities.noString(sheet.getColumn(row, "FMM")) ? null : sheet.getColumn(row, "FMM"), null, Utilities.noString(sheet.getColumn(row, "Max-Normative-Version")) ? null : sheet.getColumn(row, "Max-Normative-Version"));
        }
        cd.setDescription(sheet.getColumn(row, "Description"));
        cd.setSource(filename);
        cd.setUri(sheet.getColumn(row, "Uri"));
        cd.setStrength(readBindingStrength(sheet.getColumn(row, "Conformance")));
        String oid = sheet.getColumn(row, "Oid");
        if (!Utilities.noString(oid))
            // no cs oid in this case
            cd.setVsOid(oid);
        cd.setWebSite(sheet.getColumn(row, "Website"));
        cd.setStatus(PublicationStatus.fromCode(sheet.getColumn(row, "Status")));
        cd.setEmail(sheet.getColumn(row, "Email"));
        cd.setV2Map(sheet.getColumn(row, "v2"));
        cd.setV3Map(sheet.getColumn(row, "v3"));
        if (cd.getBinding() == BindingMethod.Unbound) {
            cd.setStrength(BindingStrength.EXAMPLE);
        }
        results.add(cd);
    }
}
Also used : DateTimeType(org.hl7.fhir.r5.model.DateTimeType) CodeListToValueSetParser(org.hl7.fhir.definitions.parsers.CodeListToValueSetParser) BindingSpecification(org.hl7.fhir.definitions.model.BindingSpecification) CodeType(org.hl7.fhir.r5.model.CodeType) ValueSet(org.hl7.fhir.r5.model.ValueSet) Sheet(org.hl7.fhir.utilities.xls.XLSXmlParser.Sheet) URISyntaxException(java.net.URISyntaxException)

Example 24 with PackageInfo

use of org.hl7.fhir.utilities.npm.PackageInfo in project org.hl7.fhir.core by hapifhir.

the class BaseWorkerContext method cacheResourceFromPackage.

public void cacheResourceFromPackage(Resource r, PackageVersion packageInfo) throws FHIRException {
    synchronized (lock) {
        Map<String, ResourceProxy> map = allResourcesById.get(r.fhirType());
        if (map == null) {
            map = new HashMap<String, ResourceProxy>();
            allResourcesById.put(r.fhirType(), map);
        }
        if ((packageInfo == null || !packageInfo.isExamplesPackage()) || !map.containsKey(r.getId())) {
            map.put(r.getId(), new ResourceProxy(r));
        } else {
            System.out.println("Ignore " + r.fhirType() + "/" + r.getId() + " from package " + packageInfo.toString());
        }
        if (r instanceof CodeSystem || r instanceof NamingSystem) {
            oidCache.clear();
        }
        if (r instanceof CanonicalResource) {
            CanonicalResource m = (CanonicalResource) r;
            String url = m.getUrl();
            if (!allowLoadingDuplicates && hasResource(r.getClass(), url)) {
                // spcial workaround for known problems with existing packages
                if (Utilities.existsInList(url, "http://hl7.org/fhir/SearchParameter/example")) {
                    return;
                }
                throw new DefinitionException(formatMessage(I18nConstants.DUPLICATE_RESOURCE_, url));
            }
            if (r instanceof StructureDefinition) {
                StructureDefinition sd = (StructureDefinition) m;
                if ("1.4.0".equals(version)) {
                    fixOldSD(sd);
                }
                structures.see(sd, packageInfo);
            } else if (r instanceof ValueSet) {
                valueSets.see((ValueSet) m, packageInfo);
            } else if (r instanceof CodeSystem) {
                CodeSystemUtilities.crossLinkCodeSystem((CodeSystem) r);
                codeSystems.see((CodeSystem) m, packageInfo);
            } else if (r instanceof ImplementationGuide) {
                guides.see((ImplementationGuide) m, packageInfo);
            } else if (r instanceof CapabilityStatement) {
                capstmts.see((CapabilityStatement) m, packageInfo);
            } else if (r instanceof Measure) {
                measures.see((Measure) m, packageInfo);
            } else if (r instanceof Library) {
                libraries.see((Library) m, packageInfo);
            } else if (r instanceof SearchParameter) {
                searchParameters.see((SearchParameter) m, packageInfo);
            } else if (r instanceof PlanDefinition) {
                plans.see((PlanDefinition) m, packageInfo);
            } else if (r instanceof OperationDefinition) {
                operations.see((OperationDefinition) m, packageInfo);
            } else if (r instanceof Questionnaire) {
                questionnaires.see((Questionnaire) m, packageInfo);
            } else if (r instanceof ConceptMap) {
                maps.see((ConceptMap) m, packageInfo);
            } else if (r instanceof StructureMap) {
                transforms.see((StructureMap) m, packageInfo);
            } else if (r instanceof NamingSystem) {
                systems.see((NamingSystem) m, packageInfo);
            }
        }
    }
}
Also used : Questionnaire(org.hl7.fhir.r4b.model.Questionnaire) ImplementationGuide(org.hl7.fhir.r4b.model.ImplementationGuide) CodeSystem(org.hl7.fhir.r4b.model.CodeSystem) CanonicalResourceProxy(org.hl7.fhir.r4b.context.CanonicalResourceManager.CanonicalResourceProxy) ResourceProxy(org.hl7.fhir.r4b.context.BaseWorkerContext.ResourceProxy) StructureMap(org.hl7.fhir.r4b.model.StructureMap) StructureDefinition(org.hl7.fhir.r4b.model.StructureDefinition) NamingSystem(org.hl7.fhir.r4b.model.NamingSystem) CapabilityStatement(org.hl7.fhir.r4b.model.CapabilityStatement) Measure(org.hl7.fhir.r4b.model.Measure) PlanDefinition(org.hl7.fhir.r4b.model.PlanDefinition) DefinitionException(org.hl7.fhir.exceptions.DefinitionException) Library(org.hl7.fhir.r4b.model.Library) SearchParameter(org.hl7.fhir.r4b.model.SearchParameter) ConceptMap(org.hl7.fhir.r4b.model.ConceptMap) CanonicalResource(org.hl7.fhir.r4b.model.CanonicalResource) ValueSet(org.hl7.fhir.r4b.model.ValueSet) OperationDefinition(org.hl7.fhir.r4b.model.OperationDefinition)

Example 25 with PackageInfo

use of org.hl7.fhir.utilities.npm.PackageInfo in project org.hl7.fhir.core by hapifhir.

the class BaseWorkerContext method registerResourceFromPackage.

public void registerResourceFromPackage(CanonicalResourceProxy r, PackageVersion packageInfo) throws FHIRException {
    synchronized (lock) {
        Map<String, ResourceProxy> map = allResourcesById.get(r.getType());
        if (map == null) {
            map = new HashMap<String, ResourceProxy>();
            allResourcesById.put(r.getType(), map);
        }
        if ((packageInfo == null || !packageInfo.isExamplesPackage()) || !map.containsKey(r.getId())) {
            map.put(r.getId(), new ResourceProxy(r));
        }
        String url = r.getUrl();
        if (!allowLoadingDuplicates && hasResource(r.getType(), url)) {
            // spcial workaround for known problems with existing packages
            if (Utilities.existsInList(url, "http://hl7.org/fhir/SearchParameter/example")) {
                return;
            }
            throw new DefinitionException(formatMessage(I18nConstants.DUPLICATE_RESOURCE_, url));
        }
        switch(r.getType()) {
            case "StructureDefinition":
                if ("1.4.0".equals(version)) {
                    StructureDefinition sd = (StructureDefinition) r.getResource();
                    fixOldSD(sd);
                }
                structures.register(r, packageInfo);
                break;
            case "ValueSet":
                valueSets.register(r, packageInfo);
                break;
            case "CodeSystem":
                codeSystems.register(r, packageInfo);
                break;
            case "ImplementationGuide":
                guides.register(r, packageInfo);
                break;
            case "CapabilityStatement":
                capstmts.register(r, packageInfo);
                break;
            case "Measure":
                measures.register(r, packageInfo);
                break;
            case "Library":
                libraries.register(r, packageInfo);
                break;
            case "SearchParameter":
                searchParameters.register(r, packageInfo);
                break;
            case "PlanDefinition":
                plans.register(r, packageInfo);
                break;
            case "OperationDefinition":
                operations.register(r, packageInfo);
                break;
            case "Questionnaire":
                questionnaires.register(r, packageInfo);
                break;
            case "ConceptMap":
                maps.register(r, packageInfo);
                break;
            case "StructureMap":
                transforms.register(r, packageInfo);
                break;
            case "NamingSystem":
                systems.register(r, packageInfo);
                break;
        }
    }
}
Also used : StructureDefinition(org.hl7.fhir.r4b.model.StructureDefinition) DefinitionException(org.hl7.fhir.exceptions.DefinitionException) CanonicalResourceProxy(org.hl7.fhir.r4b.context.CanonicalResourceManager.CanonicalResourceProxy) ResourceProxy(org.hl7.fhir.r4b.context.BaseWorkerContext.ResourceProxy)

Aggregations

PackageInfo (org.hl7.fhir.utilities.npm.PackageInfo)12 CachingPackageClient (org.hl7.fhir.utilities.npm.CachingPackageClient)11 CodeType (org.hl7.fhir.r5.model.CodeType)10 Test (org.junit.jupiter.api.Test)10 CodeSystem (org.hl7.fhir.r5.model.CodeSystem)8 ValueSet (org.hl7.fhir.r5.model.ValueSet)8 ArrayList (java.util.ArrayList)6 ValueSetComposeComponent (org.hl7.fhir.r5.model.ValueSet.ValueSetComposeComponent)5 File (java.io.File)4 DefinitionException (org.hl7.fhir.exceptions.DefinitionException)4 ConceptDefinitionComponent (org.hl7.fhir.r5.model.CodeSystem.ConceptDefinitionComponent)4 FileInputStream (java.io.FileInputStream)3 BindingSpecification (org.hl7.fhir.definitions.model.BindingSpecification)3 FHIRException (org.hl7.fhir.exceptions.FHIRException)3 XmlParser (org.hl7.fhir.r5.formats.XmlParser)3 ContactPoint (org.hl7.fhir.r5.model.ContactPoint)3 JsonObject (com.google.gson.JsonObject)2 IOException (java.io.IOException)2 URISyntaxException (java.net.URISyntaxException)2 HashMap (java.util.HashMap)2