Search in sources :

Example 11 with ProfiledType

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

the class ProfileGenerator method convertElements.

public void convertElements(ElementDefn src, StructureDefinition ed, String path) throws Exception {
    ElementDefinition dst = new ElementDefinition();
    if (!ed.hasDifferential())
        ed.setDifferential(new StructureDefinitionDifferentialComponent());
    ed.getDifferential().getElement().add(dst);
    String thisPath = path == null ? "Extension" : path;
    dst.setId(thisPath);
    dst.setPath(thisPath);
    if (!Utilities.noString(src.getProfileName()))
        dst.setSliceName(src.getProfileName());
    dst.setShort(src.getShortDefn());
    dst.setDefinition(preProcessMarkdown(src.getDefinition(), "Element Definition"));
    dst.setComment(preProcessMarkdown(src.getComments(), "Element Comments"));
    if (src.getMaxCardinality() != null) {
        if (src.getMaxCardinality() == Integer.MAX_VALUE)
            dst.setMax("*");
        else
            dst.setMax(src.getMaxCardinality().toString());
    }
    if (src.getMinCardinality() != null)
        dst.setMin(src.getMinCardinality());
    if (src.getFixed() != null)
        dst.setFixed(src.getFixed());
    if (src.hasMustSupport())
        dst.setMustSupport(src.isMustSupport());
    if (src.hasModifier())
        dst.setIsModifier(src.isModifier());
    if (dst.getIsModifier())
        dst.setIsModifierReason(src.getModifierReason());
    if (src.hasSummaryItem() && dst.getPath().contains("."))
        dst.setIsSummaryElement(Factory.newBoolean(src.isSummary()));
    for (Invariant id : src.getStatedInvariants()) dst.addCondition(id.getId());
    // dDst.
    for (TypeRef t : src.getTypes()) {
        if (t.hasParams()) {
            for (String tp : t.getParams()) {
                if (definitions.hasLogicalModel(tp)) {
                    for (String tpn : definitions.getLogicalModel(tp).getImplementations()) {
                        ElementDefinition.TypeRefComponent type = dst.getType(t.getName());
                        String pr = "http://hl7.org/fhir/StructureDefinition/" + tpn;
                        type.addTargetProfile(pr);
                    }
                } else {
                    ElementDefinition.TypeRefComponent type = dst.getType(t.getName());
                    String pr = t.hasProfile() ? t.getProfile() : // this should only happen if t.getParams().size() == 1
                    "http://hl7.org/fhir/StructureDefinition/" + (tp.equals("Any") ? "Resource" : tp);
                    if (type.getWorkingCode().equals("Reference") || type.getWorkingCode().equals("canonical") || type.getWorkingCode().equals("CodeableReference"))
                        type.addTargetProfile(pr);
                    else
                        type.addProfile(pr);
                }
            }
        } else if (t.isWildcardType()) {
            for (String n : TypesUtilities.wildcardTypes(version.toString())) dst.getType(n);
        } else {
            if (definitions != null && definitions.getConstraints().containsKey(t.getName())) {
                ProfiledType ct = definitions.getConstraints().get(t.getName());
                ElementDefinition.TypeRefComponent type = dst.getType(ct.getBaseType());
                type.addProfile("http://hl7.org/fhir/StructureDefinition/" + ct.getName());
            } else if ("Extension.url".equals(path)) {
            // juat don't populate it
            // ElementDefinition.TypeRefComponent tt = dst.addType();
            // tt.setCodeElement(new UriType());
            // tt.getFormatCommentsPre().add("Note: special primitive values do not have an assigned type. e.g. this is compiler magic. XML, JSON and RDF types provided by extension");
            // ToolingExtensions.addStringExtension(tt.getCodeElement(), ToolingExtensions.EXT_JSON_TYPE, "string");
            // ToolingExtensions.addStringExtension(tt.getCodeElement(), ToolingExtensions.EXT_XML_TYPE, "xs:anyURI");
            // ToolingExtensions.addStringExtension(tt.getCodeElement(), ToolingExtensions.EXT_RDF_TYPE, "xs:anyURI");
            } else {
                ElementDefinition.TypeRefComponent type = dst.getType(t.getName());
                if (t.hasProfile())
                    if (type.getWorkingCode().equals("Reference") || type.getWorkingCode().equals("CodeableReference"))
                        type.addTargetProfile(t.getProfile());
                    else
                        type.addProfile(t.getProfile());
            }
        }
    }
    if (definitions != null) {
        // igtodo - catch this
        for (String mu : definitions.getMapTypes().keySet()) {
            if (src.hasMapping(mu)) {
                addMapping(ed, dst, mu, src.getMapping(mu), null);
            }
        }
    }
    for (String in : src.getInvariants().keySet()) {
        ElementDefinitionConstraintComponent con = new ElementDefinitionConstraintComponent();
        Invariant inv = src.getInvariants().get(in);
        con.setKey(inv.getId());
        if (!con.hasKey()) {
            extensionCounter++;
            con.setKey("exd-" + Integer.toString(extensionCounter));
        }
        con.setRequirements(inv.getRequirements());
        if (Utilities.noString(inv.getSeverity()))
            con.setSeverity(ConstraintSeverity.ERROR);
        else
            con.setSeverity(ConstraintSeverity.fromCode(inv.getSeverity()));
        con.setHuman(inv.getEnglish());
        con.setXpath(inv.getXpath());
        if (!"n/a".equals(inv.getExpression()))
            con.setExpression(inv.getExpression());
        dst.getConstraint().add(con);
    }
    if (src.hasBinding())
        dst.setBinding(generateBinding(src.getBinding()));
    if (src.getElements().isEmpty()) {
        if (path == null)
            throw new Exception("?error parsing extension");
    } else {
        ElementDefn url = src.getElements().get(0);
        if (!url.getName().equals("url"))
            throw new Exception("first child of extension should be 'url', not " + url.getName() + " for structure definition " + ed.getUrl());
        convertElements(url, ed, thisPath + ".url");
        // this pair might leave elements out of order, but we're going to sort them later
        if (!hasValue(src)) {
            ElementDefn value = new ElementDefn();
            value.setName("value[x]");
            value.setMinCardinality(0);
            value.setMaxCardinality(0);
            convertElements(value, ed, thisPath + ".value[x]");
        } else {
            ElementDefn ext = new ElementDefn();
            // can't have an extension if you have a value
            ext.setName("extension");
            ext.setMaxCardinality(0);
            convertElements(ext, ed, thisPath + ".extension");
        }
        if (src.getElements().size() == 2 && src.getElements().get(0).getName().equals("url") && src.getElements().get(1).getName().equals("value[x]")) {
            ElementDefn value = src.getElements().get(1);
            value.setMinCardinality(1);
            convertElements(value, ed, thisPath + ".value[x]");
        } else {
            for (ElementDefn child : src.getElements()) {
                if (child != url) {
                    if (child.getName().startsWith("value") && !child.getName().startsWith("valueSet"))
                        convertElements(child, ed, thisPath + "." + child.getName());
                    else {
                        if (child.getElements().size() == 0 || !child.getElements().get(0).getName().equals("url")) {
                            ElementDefn childUrl = new ElementDefn();
                            childUrl.setName("url");
                            childUrl.setXmlAttribute(true);
                            childUrl.getTypes().add(new TypeRef("uri"));
                            childUrl.setFixed(new UriType(child.getName()));
                            child.getElements().add(0, childUrl);
                        }
                        if (!hasValue(child)) {
                            ElementDefn value = new ElementDefn();
                            value.setName("value[x]");
                            value.setMinCardinality(0);
                            value.setMaxCardinality(0);
                            child.getElements().add(value);
                        }
                        convertElements(child, ed, thisPath + ".extension");
                    }
                }
            }
        }
    }
}
Also used : Invariant(org.hl7.fhir.definitions.model.Invariant) ProfiledType(org.hl7.fhir.definitions.model.ProfiledType) TypeRefComponent(org.hl7.fhir.r5.model.ElementDefinition.TypeRefComponent) TypeRef(org.hl7.fhir.definitions.model.TypeRef) StructureDefinitionDifferentialComponent(org.hl7.fhir.r5.model.StructureDefinition.StructureDefinitionDifferentialComponent) ElementDefn(org.hl7.fhir.definitions.model.ElementDefn) ElementDefinition(org.hl7.fhir.r5.model.ElementDefinition) TypeRefComponent(org.hl7.fhir.r5.model.ElementDefinition.TypeRefComponent) ElementDefinitionConstraintComponent(org.hl7.fhir.r5.model.ElementDefinition.ElementDefinitionConstraintComponent) FHIRException(org.hl7.fhir.exceptions.FHIRException) URISyntaxException(java.net.URISyntaxException) UriType(org.hl7.fhir.r5.model.UriType)

Example 12 with ProfiledType

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

the class ProfileGenerator method generate.

public StructureDefinition generate(ProfiledType pt, List<ValidationMessage> issues) throws Exception {
    StructureDefinition p = new StructureDefinition();
    p.setId(pt.getName());
    p.setUrl("http://hl7.org/fhir/StructureDefinition/" + pt.getName());
    p.setBaseDefinition("http://hl7.org/fhir/StructureDefinition/" + pt.getBaseType());
    p.setKind(StructureDefinitionKind.COMPLEXTYPE);
    p.setType(pt.getBaseType());
    p.setDerivation(TypeDerivationRule.CONSTRAINT);
    p.setAbstract(false);
    p.setUserData("filename", pt.getName().toLowerCase());
    p.setUserData("path", "datatypes.html#" + pt.getName());
    p.setFhirVersion(version);
    p.setVersion(version.toCode());
    ToolingExtensions.setStandardsStatus(p, StandardsStatus.NORMATIVE, "4.0.0");
    p.setStatus(PublicationStatus.fromCode("active"));
    ToolResourceUtilities.updateUsage(p, "core");
    p.setName(pt.getName());
    p.setPublisher("HL7 FHIR Standard");
    p.addContact().getTelecom().add(Factory.newContactPoint(ContactPointSystem.URL, "http://hl7.org/fhir"));
    p.setDescription("Base StructureDefinition for Type " + pt.getName() + ": " + pt.getDefinition());
    p.setDescription(pt.getDefinition());
    p.setDate(genDate.getTime());
    // first, the differential
    p.setName(pt.getName());
    ElementDefinition e = new ElementDefinition();
    String idroot = e.getId();
    e.setPath(pt.getBaseType());
    // e.setSliceName(pt.getName());
    e.setShort(pt.getDefinition());
    e.setDefinition(preProcessMarkdown(pt.getDescription(), "??"));
    e.setMin(0);
    e.setMax("*");
    e.setIsModifier(false);
    String s = definitions.getTLAs().get(pt.getName().toLowerCase());
    if (s == null)
        throw new Exception("There is no TLA for '" + pt.getName() + "' in fhir.ini");
    ElementDefinitionConstraintComponent inv = new ElementDefinitionConstraintComponent();
    inv.setKey(s + "-1");
    inv.setRequirements(pt.getInvariant().getRequirements());
    inv.setSeverity(ConstraintSeverity.ERROR);
    inv.setHuman(pt.getInvariant().getEnglish());
    if (!"n/a".equals(pt.getInvariant().getExpression())) {
        fpUsages.add(new FHIRPathUsage(pt.getName(), pt.getName(), pt.getName(), null, pt.getInvariant().getExpression()));
        inv.setExpression(pt.getInvariant().getExpression());
    }
    inv.setXpath(pt.getInvariant().getXpath());
    e.getConstraint().add(inv);
    p.setDifferential(new StructureDefinitionDifferentialComponent());
    p.getDifferential().getElement().add(e);
    StructureDefinition base = getTypeSnapshot(pt.getBaseType());
    if (!pt.getRules().isEmpty()) {
        // throw new Exception("todo");
        for (String rule : pt.getRules().keySet()) {
            String[] parts = rule.split("\\.");
            String value = pt.getRules().get(rule);
            ElementDefinition er = findElement(p.getDifferential(), pt.getBaseType() + '.' + parts[0]);
            if (er == null) {
                er = new ElementDefinition();
                er.setId(pt.getBaseType() + ':' + p.getId() + '.' + parts[0]);
                er.setPath(pt.getBaseType() + '.' + parts[0]);
                p.getDifferential().getElement().add(er);
            }
            if (parts[1].equals("min"))
                er.setMin(Integer.parseInt(value));
            else if (parts[1].equals("max"))
                er.setMax(value);
            else if (parts[1].equals("defn"))
                er.setDefinition(preProcessMarkdown(value, "er"));
        }
        List<String> errors = new ArrayList<String>();
        new ProfileUtilities(context, null, pkp).sortDifferential(base, p, p.getName(), errors, true);
        for (String se : errors) issues.add(new ValidationMessage(Source.ProfileValidator, IssueType.STRUCTURE, -1, -1, p.getUrl(), se, IssueSeverity.WARNING));
    }
    reset();
    // now, the snapshot
    new ProfileUtilities(context, issues, pkp).generateSnapshot(base, p, "http://hl7.org/fhir/StructureDefinition/" + pt.getBaseType(), "http://hl7.org/fhir", p.getName());
    // for (ElementDefinition ed : p.getSnapshot().getElement())
    // generateElementDefinition(ed, getParent(ed, p.getSnapshot().getElement()));
    p.getDifferential().getElement().get(0).getType().clear();
    p.getSnapshot().getElement().get(0).getType().clear();
    XhtmlNode div = new XhtmlNode(NodeType.Element, "div");
    div.addTag("h2").addText("Data type " + pt.getName());
    div.addTag("p").addText(pt.getDefinition());
    div.addTag("h3").addText("Rule");
    div.addTag("p").addText(pt.getInvariant().getEnglish());
    div.addTag("p").addText("XPath:");
    div.addTag("blockquote").addTag("pre").addText(pt.getInvariant().getXpath());
    p.setText(new Narrative());
    p.getText().setStatus(NarrativeStatus.GENERATED);
    p.getText().setDiv(div);
    addElementConstraintToSnapshot(p);
    new ProfileUtilities(context, issues, pkp).setIds(p, false);
    checkHasTypes(p);
    return p;
}
Also used : ValidationMessage(org.hl7.fhir.utilities.validation.ValidationMessage) ArrayList(java.util.ArrayList) ElementDefinitionConstraintComponent(org.hl7.fhir.r5.model.ElementDefinition.ElementDefinitionConstraintComponent) FHIRException(org.hl7.fhir.exceptions.FHIRException) URISyntaxException(java.net.URISyntaxException) XhtmlNode(org.hl7.fhir.utilities.xhtml.XhtmlNode) StructureDefinition(org.hl7.fhir.r5.model.StructureDefinition) ProfileUtilities(org.hl7.fhir.r5.conformance.ProfileUtilities) Narrative(org.hl7.fhir.r5.model.Narrative) StructureDefinitionDifferentialComponent(org.hl7.fhir.r5.model.StructureDefinition.StructureDefinitionDifferentialComponent) ElementDefinition(org.hl7.fhir.r5.model.ElementDefinition) FHIRPathUsage(org.hl7.fhir.definitions.validation.FHIRPathUsage)

Example 13 with ProfiledType

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

the class ProfileGenerator method produceOpParam.

private void produceOpParam(String path, List<OperationDefinitionParameterComponent> opd, OperationParameter p, OperationParameterUse defUse) throws Exception {
    OperationDefinitionParameterComponent pp = new OperationDefinitionParameterComponent();
    pp.setName(p.getName());
    if (path.contains("."))
        pp.setUse(defUse);
    else if (p.getUse().equals("in"))
        pp.setUse(OperationParameterUse.IN);
    else if (p.getUse().equals("out"))
        pp.setUse(OperationParameterUse.OUT);
    else
        // but this is validated elsewhere
        throw new Exception("Unable to determine parameter use: " + p.getUse() + " at " + path + "." + p.getName());
    pp.setDocumentation(preProcessMarkdown(p.getDoc(), "Operation Parameter Doco"));
    pp.setMin(p.getMin());
    pp.setMax(p.getMax());
    if (p.getBs() != null) {
        if (p.getBs().hasMax())
            throw new Error("Max binding not handled yet");
        pp.setBinding(new OperationDefinitionParameterBindingComponent().setStrength(p.getBs().getStrength()).setValueSet(buildValueSetReference(p.getBs())));
        if (!Utilities.noString(p.getBinding().getName())) {
            pp.getBinding().addExtension("http://hl7.org/fhir/StructureDefinition/elementdefinition-bindingName", new StringType(p.getBinding().getName()));
        }
    }
    if (!Utilities.noString(p.getProfile())) {
        pp.addTargetProfile(p.getProfile());
    }
    opd.add(pp);
    if (p.getFhirType().equals("Tuple")) {
        for (OperationParameter part : p.getParts()) {
            produceOpParam(path + "." + p.getName(), pp.getPart(), part, pp.getUse());
        }
    } else {
        List<TypeRef> trs = new TypeParser(version.toCode()).parse(p.getFhirType(), false, null, null, false);
        if (trs.size() > 1) {
            if (p.getSearchType() != null)
                pp.setSearchType(SearchParamType.fromCode(p.getSearchType()));
            pp.setType(Enumerations.FHIRAllTypes.fromCode("Element"));
            for (TypeRef tr : trs) {
                pp.addExtension(ToolingExtensions.EXT_ALLOWED_TYPE, new UriType(tr.getName()));
                if (tr.getParams().size() > 0)
                    throw new Error("Multiple types for an operation parameter, where one is a reference, is not supported by the build tools");
            }
        } else {
            TypeRef tr = trs.get(0);
            if (definitions.getConstraints().containsKey(tr.getName())) {
                ProfiledType pt = definitions.getConstraints().get(tr.getName());
                pp.setType(Enumerations.FHIRAllTypes.fromCode(pt.getBaseType().equals("*") ? "Type" : pt.getBaseType()));
                pp.addTargetProfile("http://hl7.org/fhir/StructureDefinition/" + pt.getName());
            } else {
                if (p.getSearchType() != null)
                    pp.setSearchType(SearchParamType.fromCode(p.getSearchType()));
                pp.setType(Enumerations.FHIRAllTypes.fromCode(tr.getName().equals("*") ? "Type" : tr.getName()));
                if (tr.getParams().size() == 1 && !tr.getParams().get(0).equals("Any"))
                    pp.addTargetProfile("http://hl7.org/fhir/StructureDefinition/" + tr.getParams().get(0));
            }
        }
    }
}
Also used : TypeParser(org.hl7.fhir.definitions.parsers.TypeParser) ProfiledType(org.hl7.fhir.definitions.model.ProfiledType) StringType(org.hl7.fhir.r5.model.StringType) TypeRef(org.hl7.fhir.definitions.model.TypeRef) OperationDefinitionParameterBindingComponent(org.hl7.fhir.r5.model.OperationDefinition.OperationDefinitionParameterBindingComponent) OperationParameter(org.hl7.fhir.definitions.model.OperationParameter) FHIRFormatError(org.hl7.fhir.exceptions.FHIRFormatError) FHIRException(org.hl7.fhir.exceptions.FHIRException) URISyntaxException(java.net.URISyntaxException) OperationDefinitionParameterComponent(org.hl7.fhir.r5.model.OperationDefinition.OperationDefinitionParameterComponent) UriType(org.hl7.fhir.r5.model.UriType)

Example 14 with ProfiledType

use of org.hl7.fhir.definitions.model.ProfiledType in project org.hl7.fhir.core by hapifhir.

the class JavaResourceGenerator method generate.

// public void generate(ElementDefinition root, String name, JavaGenClass clss, ProfiledType cd, Date genDate, String version, boolean isAbstract, Map<String, SearchParameterDefn> nameToSearchParamDef, ElementDefinition template) throws Exception {
public void generate(Analysis analysis) throws Exception {
    if (analysis.getStructure().getKind() == StructureDefinitionKind.RESOURCE) {
        clss = JavaGenClass.Resource;
    } else {
        clss = JavaGenClass.Type;
    }
    write("package org.hl7.fhir." + jid + ".model;\r\n");
    startMark(version, genDate);
    // hasList(root);
    boolean hl = true;
    boolean hh = hasXhtml(analysis.getStructure().getSnapshot().getElement());
    boolean hd = hasDecimal(analysis.getStructure().getSnapshot().getElement());
    boolean hs = hasString(analysis.getStructure().getSnapshot().getElement());
    boolean he = hasSharedEnums(analysis.getStructure().getSnapshot().getElement());
    boolean hn = hasNestedTypes(analysis.getStructure().getSnapshot().getElement());
    if (hl || hh || hd || he) {
        if (hl) {
            write("import java.util.ArrayList;\r\n");
            write("import java.util.Date;\r\n");
            write("import java.util.List;\r\n");
        } else {
            write("import java.util.Date;\r\n");
        }
        if (hh) {
            write("import org.hl7.fhir.utilities.xhtml.NodeType;\r\n");
            write("import org.hl7.fhir.utilities.xhtml.XhtmlNode;\r\n");
        }
        if (hd)
            write("import java.math.*;\r\n");
        if (hs)
            write("import org.hl7.fhir.utilities.Utilities;\r\n");
        if (he)
            write("import org.hl7.fhir." + jid + ".model.Enumerations.*;\r\n");
    }
    if (hn) {
        if (clss == JavaGenClass.Resource) {
            write("import org.hl7.fhir.instance.model.api.IBaseBackboneElement;\r\n");
        } else {
            write("import org.hl7.fhir.instance.model.api.IBaseDatatypeElement;\r\n");
        }
    }
    write("import org.hl7.fhir.exceptions.FHIRException;\r\n");
    write("import org.hl7.fhir.instance.model.api.ICompositeType;\r\n");
    if (clss == JavaGenClass.Resource) {
        write("import ca.uhn.fhir.model.api.annotation.ResourceDef;\r\n");
        write("import ca.uhn.fhir.model.api.annotation.SearchParamDefinition;\r\n");
    }
    if (clss == JavaGenClass.Resource || "BackboneElement".equals(analysis.getName()) || "BackboneType".equals(analysis.getName())) {
        write("import org.hl7.fhir.instance.model.api.IBaseBackboneElement;\r\n");
    }
    write("import ca.uhn.fhir.model.api.annotation.Child;\r\n");
    write("import ca.uhn.fhir.model.api.annotation.ChildOrder;\r\n");
    if (clss != JavaGenClass.Resource) {
        write("import ca.uhn.fhir.model.api.annotation.DatatypeDef;\r\n");
    }
    write("import ca.uhn.fhir.model.api.annotation.Description;\r\n");
    write("import ca.uhn.fhir.model.api.annotation.Block;\r\n");
    write("\r\n");
    if (config.getIni().hasProperty("imports", analysis.getName())) {
        for (String imp : config.getIni().getStringProperty("imports", analysis.getName()).split("\\,")) {
            write("import " + imp.replace("{{jid}}", jid) + ";\r\n");
        }
    }
    jdoc("", replaceTitle(analysis.getName(), analysis.getStructure().getDescription()));
    TypeInfo ti = analysis.getRootType();
    boolean hasChildren = ti.getChildren().size() > 0;
    String superName = analysis.getAncestor() == null ? null : analysis.getAncestor().getName();
    if (VersionUtilities.isR4BVer(version) && !Utilities.noString(config.getIni().getStringProperty("R4B.CanonicalResources", analysis.getName()))) {
        superName = "CanonicalResource";
    }
    String hierarchy = analysis.getAncestor() != null ? "extends " + superName : "";
    if (clss == JavaGenClass.Resource) {
        if (!analysis.isAbstract()) {
            write("@ResourceDef(name=\"" + upFirst(analysis.getName()).replace("ListResource", "List") + "\", profile=\"http://hl7.org/fhir/StructureDefinition/" + upFirst(analysis.getName()) + "\")\r\n");
        }
    } else {
        write("@DatatypeDef(name=\"" + upFirst(analysis.getName()) + "\")\r\n");
        hierarchy = hierarchy + " implements ICompositeType";
    }
    if (config.getIni().hasProperty("hierarchy", analysis.getName())) {
        String h = config.getIni().getStringProperty("hierarchy", analysis.getName());
        if (analysis.getAncestor() != null) {
            h = h.replace("{{super}}", superName);
        }
        hierarchy = h;
    }
    write("public " + (analysis.isAbstract() ? "abstract " : "") + "class " + analysis.getClassName() + " " + hierarchy.trim() + " {\r\n");
    write("\r\n");
    for (String s : sorted(analysis.getEnums().keySet())) {
        EnumInfo e = analysis.getEnums().get(s);
        generateEnum(e);
    }
    for (TypeInfo t : analysis.getTypeList()) {
        generateType(analysis, t);
    }
    allfields = "";
    int i = 0;
    for (ElementDefinition e : ti.getChildren()) {
        if (!analysis.isInterface()) {
            generateField(analysis, ti, e, "    ", i++);
        }
    }
    write("    private static final long serialVersionUID = " + Long.toString(allfields.hashCode()) + "L;\r\n\r\n");
    hashSum = hashSum + allfields.hashCode();
    List<ElementDefinition> mandatory = new ArrayList<ElementDefinition>();
    generateConstructor(analysis.getClassName(), mandatory, "  ");
    if (hasChildren) {
        for (ElementDefinition e : ti.getChildren()) {
            if (e.getMin() > 0)
                mandatory.add(e);
        }
        if (mandatory.size() > 0)
            generateConstructor(analysis.getClassName(), mandatory, "  ");
        generateTypeSpecificConstructors(analysis.getClassName());
        for (ElementDefinition e : ti.getChildren()) {
            if (analysis.isInterface()) {
                generateAbstractAccessors(analysis, ti, e, "    ");
            } else {
                generateAccessors(analysis, ti, e, "    ", matchingInheritedElement(ti.getInheritedChildren(), e, analysis.getName()));
            }
        }
        if (!analysis.isInterface() && ti.getInheritedChildren() != null) {
            for (ElementDefinition e : filterInherited(ti.getInheritedChildren(), ti.getChildren())) {
                generateUnimplementedAccessors(analysis, ti, e, "    ");
            }
        }
        generateChildrenRegister(analysis, ti, "    ");
        generatePropertyGetterId(analysis, ti, "    ");
        generatePropertySetterId(analysis, ti, "    ");
        generatePropertySetterName(analysis, ti, "    ");
        generatePropertyMaker(analysis, ti, "    ");
        generatePropertyTypeGetter(analysis, ti, "    ");
        generateChildAdder(analysis, ti, "    ");
    }
    generateFhirType(analysis.getName());
    // // check for mappings
    // for (String map : root.getMappings().keySet()) {
    // if ("http://hl7.org/fhir/workflow".equals(map)) {
    // String namenn = root.getMapping(map);
    // if (patterns.containsKey(namenn)) {
    // generateImpl(namenn, patterns.get(namenn), upFirst(name), root, version, genDate);
    // }
    // }
    // }
    generateCopy(analysis, ti, false);
    if (hasChildren) {
        generateEquals(analysis, ti, false);
        generateIsEmpty(analysis, ti, false);
    }
    if (clss == JavaGenClass.Resource && !analysis.isAbstract()) {
        write("  @Override\r\n");
        write("  public ResourceType getResourceType() {\r\n");
        write("    return ResourceType." + analysis.getName() + ";\r\n");
        write("   }\r\n");
        write("\r\n");
    } else if (analysis.isAbstract() && analysis.getAncestor() != null && Utilities.noString(superName)) {
        write("\r\n");
        write("  @Override\r\n");
        write("  public String getIdBase() {\r\n");
        write("    return getId();\r\n");
        write("  }\r\n");
        write("  \r\n");
        write("  @Override\r\n");
        write("  public void setIdBase(String value) {\r\n");
        write("    setId(value);\r\n");
        write("  }\r\n");
        write("  public abstract ResourceType getResourceType();\r\n");
    } else if (analysis.isAbstract() && analysis.getAncestor() != null && Utilities.noString(superName)) {
        write("  @Override\r\n");
        write("  public String getIdBase() {\r\n");
        write("    return getId();\r\n");
        write("  }\r\n");
        write("  \r\n");
        write("  @Override\r\n");
        write("  public void setIdBase(String value) {\r\n");
        write("    setId(value);\r\n");
        write("  }\r\n");
    }
    // Write resource fields which can be used as constants in client code
    // to refer to standard search params
    Set<String> spcodes = new HashSet<>();
    for (SearchParameter sp : analysis.getSearchParams()) {
        String code = sp.getCode();
        if (!spcodes.contains(code)) {
            spcodes.add(code);
            /* 
		     * For composite codes we want to find the two param this is a composite
		     * of. We generate search parameter constants which reference the 
		     * component parts of the composite.  
		     */
            if (sp.getType() == SearchParamType.COMPOSITE) {
                if (code.endsWith("-[x]")) {
                    // partialCode will have "value" in this example
                    String partialCode = code.substring(0, code.length() - 4);
                    partialCode = partialCode.substring(partialCode.lastIndexOf('-') + 1);
                    // rootCode will have "component-code"
                    String rootCode = code.substring(0, code.indexOf("-" + partialCode));
                    /*
		         * If the composite has the form "foo-bar[x]" we expand this to create 
		         * a constant for each of the possible [x] values, so that client have
		         * static binding to the individual possibilities. AFAIK this is only
		         * used right now in Observation (e.g. for code-value-[x]) 
		         */
                    for (SearchParameter nextCandidate : analysis.getSearchParams()) {
                        if (nextCandidate.getCode().startsWith(partialCode)) {
                            String nextCompositeCode = rootCode + "-" + nextCandidate.getCode();
                            String[] compositeOf = new String[] { rootCode, nextCandidate.getCode() };
                            writeSearchParameterField(analysis.getName(), clss, analysis.isAbstract(), sp, nextCompositeCode, compositeOf, analysis.getSearchParams(), analysis.getName());
                        }
                    }
                } else {
                    SearchParameter comp0 = definitions.getSearchParams().get(sp.getComponent().get(0).getDefinition());
                    SearchParameter comp1 = definitions.getSearchParams().get(sp.getComponent().get(1).getDefinition());
                    if (comp0 != null && comp1 != null) {
                        String[] compositeOf = new String[] { comp0.getCode(), comp1.getCode() };
                        writeSearchParameterField(analysis.getName(), clss, analysis.isAbstract(), sp, sp.getCode(), compositeOf, analysis.getSearchParams(), analysis.getName());
                    }
                }
            } else if (code.contains("[x]")) {
                /*
		       * We only know how to handle search parameters with [x] in the name
		       * where it's a composite, and the [x] comes last. Are there other possibilities?
		       */
                throw new Exception("Unable to generate constant for search parameter: " + code);
            } else {
                writeSearchParameterField(analysis.getName(), clss, analysis.isAbstract(), sp, code, null, analysis.getSearchParams(), analysis.getName());
            }
        }
    }
    if (VersionUtilities.isR4BVer(version)) {
        String extras = config.getIni().getStringProperty("R4B.NullImplementation", analysis.getName());
        if (!Utilities.noString(extras)) {
            for (String n : extras.split("\\,")) {
                String t = n.substring(n.indexOf(":") + 1);
                n = n.substring(0, n.indexOf(":"));
                if (n.endsWith("[]")) {
                    n = Utilities.capitalize(n.substring(0, n.length() - 2));
                    write("      @Override\r\n");
                    write("      public List<" + t + "> get" + n + "() {\r\n");
                    write("        return new ArrayList<>();\r\n");
                    write("      }\r\n");
                    write("      \r\n");
                    write("      @Override\r\n");
                    write("      public CanonicalResource set" + n + "(List<" + t + "> the" + n + ") {\r\n");
                    write("        return this;\r\n");
                    write("      }\r\n");
                    write("      \r\n");
                    write("      @Override\r\n");
                    write("      public boolean has" + n + "() {\r\n");
                    write("        return false;\r\n");
                    write("      }\r\n");
                    write("      \r\n");
                    write("      @Override\r\n");
                    write("      public " + t + " add" + n + "() {\r\n");
                    write("	        return null;\r\n");
                    write("	      }\r\n");
                    write("	      \r\n");
                    write("      @Override\r\n");
                    write("      public CanonicalResource add" + n + "(" + t + " t) {\r\n");
                    write("        return null;\r\n");
                    write("	      }\r\n");
                    write("      \r\n");
                    write("      @Override\r\n");
                    write("      public " + t + " get" + n + "FirstRep() {\r\n");
                    write("        return new " + t + "();\r\n");
                    write("      }\r\n");
                    write("      \r\n");
                } else if (t.contains("|")) {
                    n = Utilities.capitalize(n);
                    String t1 = t.substring(0, t.indexOf("|"));
                    String t2 = t.substring(t.indexOf("|") + 1);
                    write("      @Override\r\n");
                    write("      public " + t1 + " get" + n + "() {\r\n");
                    if ("boolean".equals(t1)) {
                        write("        return false;\r\n");
                    } else {
                        write("        return new " + t1 + "();\r\n");
                    }
                    write("      }\r\n");
                    write("      \r\n");
                    write("      @Override\r\n");
                    write("      public " + t2 + " get" + n + "Element() {\r\n");
                    write("        return new " + t2 + "();\r\n");
                    write("      }\r\n");
                    write("      \r\n");
                    write("      @Override\r\n");
                    write("      public CanonicalResource set" + n + "(" + t1 + " the" + n + ") {\r\n");
                    write("        return this;\r\n");
                    write("      }\r\n");
                    write("      \r\n");
                    write("      @Override\r\n");
                    write("      public CanonicalResource set" + n + "Element(" + t2 + " the" + n + ") {\r\n");
                    write("        return this;\r\n");
                    write("      }\r\n");
                    write("      \r\n");
                    write("      @Override\r\n");
                    write("      public boolean has" + n + "() {\r\n");
                    write("        return false;\r\n");
                    write("      }\r\n");
                    write("      \r\n");
                    write("      @Override\r\n");
                    write("      public boolean has" + n + "Element() {\r\n");
                    write("        return false;\r\n");
                    write("      }\r\n");
                    write("      \r\n");
                    write("      \r\n");
                } else {
                    n = Utilities.capitalize(n);
                    write("      @Override\r\n");
                    write("      public " + t + " get" + n + "() {\r\n");
                    write("        return new " + t + "();\r\n");
                    write("      }\r\n");
                    write("      \r\n");
                    write("      @Override\r\n");
                    write("      public CanonicalResource set" + n + "(" + t + " the" + n + ") {\r\n");
                    write("        return this;\r\n");
                    write("      }\r\n");
                    write("      \r\n");
                    write("      @Override\r\n");
                    write("      public boolean has" + n + "() {\r\n");
                    write("        return false;\r\n");
                    write("      }\r\n");
                    write("      \r\n");
                    write("      @Override\r\n");
                    write("      public boolean has" + n + "Element() {\r\n");
                    write("        return false;\r\n");
                    write("      }\r\n");
                    write("      \r\n");
                    write("      \r\n");
                }
            }
        }
    }
    if (config.getAdornments().containsKey(analysis.getClassName())) {
        write("// Manual code (from Configuration.txt):\r\n");
        write(config.getAdornments().get(analysis.getClassName()) + "\r\n");
        write("// end addition\r\n");
    }
    write("\r\n");
    write("}\r\n");
    write("\r\n");
    flush();
}
Also used : EnumInfo(org.hl7.fhir.core.generator.analysis.EnumInfo) ArrayList(java.util.ArrayList) TypeInfo(org.hl7.fhir.core.generator.analysis.TypeInfo) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ElementDefinition(org.hl7.fhir.r5.model.ElementDefinition) SearchParameter(org.hl7.fhir.r5.model.SearchParameter) HashSet(java.util.HashSet)

Example 15 with ProfiledType

use of org.hl7.fhir.definitions.model.ProfiledType in project org.hl7.fhir.core by hapifhir.

the class StructureMapUtilities method analyseTransform.

private TypeDetails analyseTransform(TransformContext context, StructureMap map, StructureMapGroupRuleTargetComponent tgt, VariableForProfiling var, VariablesForProfiling vars) throws FHIRException {
    switch(tgt.getTransform()) {
        case CREATE:
            String p = getParamString(vars, tgt.getParameter().get(0));
            return new TypeDetails(CollectionStatus.SINGLETON, p);
        case COPY:
            return getParam(vars, tgt.getParameter().get(0));
        case EVALUATE:
            ExpressionNode expr = (ExpressionNode) tgt.getUserData(MAP_EXPRESSION);
            if (expr == null) {
                expr = fpe.parse(getParamString(vars, tgt.getParameter().get(tgt.getParameter().size() - 1)));
                tgt.setUserData(MAP_WHERE_EXPRESSION, expr);
            }
            return fpe.check(vars, null, expr);
        // //  throw new Error("Transform "+tgt.getTransform().toCode()+" not supported yet");
        case TRANSLATE:
            return new TypeDetails(CollectionStatus.SINGLETON, "CodeableConcept");
        case CC:
            ProfiledType res = new ProfiledType("CodeableConcept");
            if (tgt.getParameter().size() >= 2 && isParamId(vars, tgt.getParameter().get(1))) {
                TypeDetails td = vars.get(null, getParamId(vars, tgt.getParameter().get(1))).property.types;
                if (td != null && td.hasBinding())
                    // todo: do we need to check that there's no implicit translation her? I don't think we do...
                    res.addBinding(td.getBinding());
            }
            return new TypeDetails(CollectionStatus.SINGLETON, res);
        case C:
            return new TypeDetails(CollectionStatus.SINGLETON, "Coding");
        case QTY:
            return new TypeDetails(CollectionStatus.SINGLETON, "Quantity");
        case REFERENCE:
            VariableForProfiling vrs = vars.get(VariableMode.OUTPUT, getParamId(vars, tgt.getParameterFirstRep()));
            if (vrs == null)
                throw new FHIRException("Unable to resolve variable \"" + getParamId(vars, tgt.getParameterFirstRep()) + "\"");
            String profile = vrs.property.getProfileProperty().getStructure().getUrl();
            TypeDetails td = new TypeDetails(CollectionStatus.SINGLETON);
            td.addType("Reference", profile);
            return td;
        // //    throw new FHIRException("Transform engine cannot point at an element of type "+b.fhirType());
        default:
            throw new Error("Transform Unknown or not handled yet: " + tgt.getTransform().toCode());
    }
}
Also used : TypeDetails(org.hl7.fhir.dstu3.model.TypeDetails) ProfiledType(org.hl7.fhir.dstu3.model.TypeDetails.ProfiledType) ExpressionNode(org.hl7.fhir.dstu3.model.ExpressionNode) FHIRFormatError(org.hl7.fhir.exceptions.FHIRFormatError) FHIRException(org.hl7.fhir.exceptions.FHIRException)

Aggregations

FHIRException (org.hl7.fhir.exceptions.FHIRException)19 ProfiledType (org.hl7.fhir.definitions.model.ProfiledType)14 ArrayList (java.util.ArrayList)11 FHIRFormatError (org.hl7.fhir.exceptions.FHIRFormatError)9 ElementDefn (org.hl7.fhir.definitions.model.ElementDefn)7 TypeRef (org.hl7.fhir.definitions.model.TypeRef)7 DefinitionException (org.hl7.fhir.exceptions.DefinitionException)7 StructureDefinition (org.hl7.fhir.r5.model.StructureDefinition)6 IOException (java.io.IOException)5 ElementDefinition (org.hl7.fhir.r5.model.ElementDefinition)5 URISyntaxException (java.net.URISyntaxException)4 ProfiledType (org.hl7.fhir.dstu3.model.TypeDetails.ProfiledType)4 ProfiledType (org.hl7.fhir.r4.model.TypeDetails.ProfiledType)4 ProfiledType (org.hl7.fhir.r4b.model.TypeDetails.ProfiledType)4 TypeRefComponent (org.hl7.fhir.r5.model.ElementDefinition.TypeRefComponent)4 ProfiledType (org.hl7.fhir.r5.model.TypeDetails.ProfiledType)4 FileNotFoundException (java.io.FileNotFoundException)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)3 List (java.util.List)3 DefinedCode (org.hl7.fhir.definitions.model.DefinedCode)3