org.hl7.fhir.r4.model.StructureDefinition Java Examples

The following examples show how to use org.hl7.fhir.r4.model.StructureDefinition. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: StructureMapUtilities.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
private void addChildMappings(StringBuilder b, String id, String indent, StructureDefinition sd, ElementDefinition ed, boolean inner) throws DefinitionException {
  boolean first = true;
  List<ElementDefinition> children = ProfileUtilities.getChildMap(sd, ed);
  for (ElementDefinition child : children) {
    if (first && inner) {
      b.append(" then {\r\n");
      first = false;
    }
    String map = getMapping(child, id);
    if (map != null) {
      b.append(indent+"  "+child.getPath()+": "+map);
      addChildMappings(b, id, indent+"  ", sd, child, true);
      b.append("\r\n");
    }
  }
  if (!first && inner)
    b.append(indent+"}");
  
}
 
Example #2
Source File: StructureMapUtilities.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
public StructureDefinition getTargetType(StructureMap map) throws FHIRException {
  boolean found = false;
  StructureDefinition res = null;
  for (StructureMapStructureComponent uses : map.getStructure()) {
    if (uses.getMode() == StructureMapModelMode.TARGET) {
      if (found)
        throw new FHIRException("Multiple targets found in map "+map.getUrl());
      found = true;
      res = worker.fetchResource(StructureDefinition.class, uses.getUrl());
      if (res == null)
        throw new FHIRException("Unable to find "+uses.getUrl()+" referenced from map "+map.getUrl());      
    }
  }
  if (res == null)
     throw new FHIRException("No targets found in map "+map.getUrl());
  return res;
}
 
Example #3
Source File: Property.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
public boolean IsLogicalAndHasPrimitiveValue(String name) {
//		if (canBePrimitive!= null)
//			return canBePrimitive;
		
		canBePrimitive = false;
  	if (structure.getKind() != StructureDefinitionKind.LOGICAL)
  		return false;
  	if (!hasType(name))
  		return false;
  	StructureDefinition sd = context.fetchResource(StructureDefinition.class, structure.getUrl().substring(0, structure.getUrl().lastIndexOf("/")+1)+getType(name));
  	if (sd == null)
  	  sd = context.fetchResource(StructureDefinition.class, ProfileUtilities.sdNs(getType(name), context.getOverrideVersionNs()));
    if (sd != null && sd.getKind() == StructureDefinitionKind.PRIMITIVETYPE)
      return true;
  	if (sd == null || sd.getKind() != StructureDefinitionKind.LOGICAL)
  		return false;
  	for (ElementDefinition ed : sd.getSnapshot().getElement()) {
  		if (ed.getPath().equals(sd.getId()+".value") && ed.getType().size() == 1 && isPrimitive(ed.getType().get(0).getCode())) {
  			canBePrimitive = true;
  			return true;
  		}
  	}
  	return false;
	}
 
Example #4
Source File: GraphQLSchemaGenerator.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
private String generateInnerType(List<StringBuilder> list, StructureDefinition sd, String name, ElementDefinition child, String mode, String suffix) throws IOException {
  if (child.hasUserData(INNER_TYPE_NAME+"."+mode))
    return child.getUserString(INNER_TYPE_NAME+"."+mode);
  
  String typeName = name+Utilities.capitalize(tail(child.getPath(), false));
  child.setUserData(INNER_TYPE_NAME+"."+mode, typeName);
  StringBuilder b = new StringBuilder();
  list.add(b);
  b.append(mode);
  b.append(" ");
  b.append(typeName);
  b.append(suffix);
  b.append(" {\r\n");
  generateProperties(list, b, typeName, sd, child, mode, suffix);
  b.append("}");
  b.append("\r\n");
  b.append("\r\n");
  return typeName+suffix;
}
 
Example #5
Source File: SimpleWorkerContext.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
@Override
public List<StructureDefinition> allStructures() {
  List<StructureDefinition> result = new ArrayList<StructureDefinition>();
  Set<StructureDefinition> set = new HashSet<StructureDefinition>();
  for (StructureDefinition sd : listStructures()) {
    if (!set.contains(sd)) {
      try {
        generateSnapshot(sd);
      } catch (Exception e) {
        System.out.println("Unable to generate snapshot for "+sd.getUrl()+" because "+e.getMessage());
      }
      result.add(sd);
      set.add(sd);
    }
  }
  return result;
}
 
Example #6
Source File: JsonParser.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
public Element parse(JsonObject object) throws FHIRException {
	JsonElement rt = object.get("resourceType");
	if (rt == null) {
		logError(line(object), col(object), "$", IssueType.INVALID, "Unable to find resourceType property", IssueSeverity.FATAL);
		return null;
	} else {
		String name = rt.getAsString();
		String path = "/"+name;

		StructureDefinition sd = getDefinition(line(object), col(object), name);
		if (sd == null)
			return null;

		Element result = new Element(name, new Property(context, sd.getSnapshot().getElement().get(0), sd));
		checkObject(object, path);
		result.markLocation(line(object), col(object));
		result.setType(name);
		parseChildren(path, object, result, true);
		result.numberChildren();
		return result;
	}
}
 
Example #7
Source File: ShExGenerator.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
/**
 * Generate a definition for a referenced element
 * @param sd Containing structure definition
 * @param ed Inner element
 * @return ShEx representation of element reference
 */
private String genInnerTypeDef(StructureDefinition sd, ElementDefinition ed) {
  String path = ed.hasBase() ? ed.getBase().getPath() : ed.getPath();;
  ST element_reference = tmplt(SHAPE_DEFINITION_TEMPLATE);
  element_reference.add("resourceDecl", "");  // Not a resource
  element_reference.add("id", path);
  String comment = ed.getShort();
  element_reference.add("comment", comment == null? " " : "# " + comment);

  List<String> elements = new ArrayList<String>();
  for (ElementDefinition child: ProfileUtilities.getChildList(sd, path, null))
    elements.add(genElementDefinition(sd, child));

  element_reference.add("elements", StringUtils.join(elements, "\n"));
  return element_reference.render();
}
 
Example #8
Source File: ParserBase.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
protected StructureDefinition getDefinition(int line, int col, String ns, String name) throws FHIRFormatError {
  if (ns == null) {
    logError(line, col, name, IssueType.STRUCTURE, "This cannot be parsed as a FHIR object (no namespace)", IssueSeverity.FATAL);
    return null;
  }
  if (name == null) {
    logError(line, col, name, IssueType.STRUCTURE, "This cannot be parsed as a FHIR object (no name)", IssueSeverity.FATAL);
    return null;
	}
 for (StructureDefinition sd : context.allStructures()) {
   if (sd.getDerivation() == TypeDerivationRule.SPECIALIZATION && !sd.getUrl().startsWith("http://hl7.org/fhir/StructureDefinition/de-")) {
     if(name.equals(sd.getType()) && (ns == null || ns.equals(FormatUtilities.FHIR_NS)) && !ToolingExtensions.hasExtension(sd, "http://hl7.org/fhir/StructureDefinition/elementdefinition-namespace"))
       return sd;
     String sns = ToolingExtensions.readStringExtension(sd, "http://hl7.org/fhir/StructureDefinition/elementdefinition-namespace");
     if (name.equals(sd.getType()) && ns != null && ns.equals(sns))
       return sd;
   }
 }
 logError(line, col, name, IssueType.STRUCTURE, "This does not appear to be a FHIR resource (unknown namespace/name '"+ns+"::"+name+"')", IssueSeverity.FATAL);
 return null;
}
 
Example #9
Source File: ExtensionDefinitionGenerator.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
private List<StructureDefinition> loadSource() throws IOException, FHIRException {
  List<StructureDefinition> list = new ArrayList<>();
  FilesystemPackageCacheManager pcm = new FilesystemPackageCacheManager(true, ToolsVersion.TOOLS_VERSION);
  NpmPackage npm = pcm.loadPackage("hl7.fhir.core", sourceVersion.toCode());
  if (sourceVersion == FHIRVersion._4_0_0)
    context = SimpleWorkerContext.fromPackage(npm);
  else if (sourceVersion == FHIRVersion._3_0_1)
    context = SimpleWorkerContext.fromPackage(npm, new R3ToR4Loader());
  else if (sourceVersion == FHIRVersion._1_4_0)
    context = SimpleWorkerContext.fromPackage(npm, new R2016MayToR4Loader());
  else if (sourceVersion == FHIRVersion._1_0_2)
    context = SimpleWorkerContext.fromPackage(npm, new R2ToR4Loader());
  pu = new ProfileUtilities(context,  null,  null);
  for (String fn : npm.listResources("StructureDefinition")) {
    list.add((StructureDefinition) loadResource(npm.load("package", fn), sourceVersion));
  }
  for (StructureDefinition sd : list)
    if (sd.getName().equals("Extension")) {
      extbase = sd;
      extv = extbase.getSnapshot().getElement().get(extbase.getSnapshot().getElement().size() -1);
    }        
  return list;
}
 
Example #10
Source File: ShExGenerator.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
/**
 * Generate a shape definition for the current set of datatypes
 * @return stringified data type definitions
 */
private String emitDataTypes() {
  StringBuilder dtDefs = new StringBuilder();
  while (emittedDatatypes.size() < datatypes.size()) {
    for (String dt : new HashSet<String>(datatypes)) {
      if (!emittedDatatypes.contains(dt)) {
        StructureDefinition sd = context.fetchResource(StructureDefinition.class,
            ProfileUtilities.sdNs(dt, null));
        // TODO: Figure out why the line below doesn't work
        // if (sd != null && !uniq_structures.contains(sd))
        if(sd != null && !uniq_structure_urls.contains(sd.getUrl()))
          dtDefs.append("\n").append(genShapeDefinition(sd, false));
        emittedDatatypes.add(dt);
      }
    }
  }
  return dtDefs.toString();
}
 
Example #11
Source File: XmlParser.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
public Element parse(org.w3c.dom.Element element) throws FHIRFormatError, DefinitionException, FHIRException, IOException {
  String ns = element.getNamespaceURI();
  String name = element.getLocalName();
  String path = "/"+pathPrefix(ns)+name;
  
  StructureDefinition sd = getDefinition(line(element), col(element), ns, name);
  if (sd == null)
    return null;

  Element result = new Element(element.getLocalName(), new Property(context, sd.getSnapshot().getElement().get(0), sd));
  checkElement(element, path, result.getProperty());
  result.markLocation(line(element), col(element));
  result.setType(element.getLocalName());
  parseChildren(path, element, result);
  result.numberChildren();
  return result;
}
 
Example #12
Source File: SnapShotGenerationTests.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
private StructureDefinition getSD(String url, SnapShotGenerationTestsContext context) throws DefinitionException, FHIRException, IOException {
  StructureDefinition sd = context.getByUrl(url);
  if (sd == null)
    sd = TestingUtilities.context().fetchResource(StructureDefinition.class, url);
  if (!sd.hasSnapshot()) {
    StructureDefinition base = getSD(sd.getBaseDefinition(), context);
    ProfileUtilities pu = new ProfileUtilities(TestingUtilities.context(), messages, new TestPKP());
    pu.setNewSlicingProcessing(true);
    List<String> errors = new ArrayList<String>();
    pu.sortDifferential(base, sd, url, errors);
    if (!errors.isEmpty())
      throw new FHIRException(errors.get(0));
    pu.setIds(sd, false);
    pu.generateSnapshot(base, sd, sd.getUrl(), "http://test.org/profile", sd.getName());
  }
  return sd;
}
 
Example #13
Source File: ProfileUtilitiesTests.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
private void compareXml(StructureDefinition base, StructureDefinition focus) throws FileNotFoundException, IOException {
    base.setText(null);
    focus.setText(null);
    base.setDifferential(null);
//    focus.setDifferential(null);
    String f1 = Utilities.path("c:", "temp", "base.xml");
    String f2 = Utilities.path("c:", "temp", "derived.xml");
    new XmlParser().setOutputStyle(OutputStyle.PRETTY).compose(new FileOutputStream(f1), base);
    ;
    new XmlParser().setOutputStyle(OutputStyle.PRETTY).compose(new FileOutputStream(f2), focus);
    ;
    String diff = Utilities.path(System.getenv("ProgramFiles(X86)"), "WinMerge", "WinMergeU.exe");
    List<String> command = new ArrayList<String>();
    command.add("\"" + diff + "\" \"" + f1 + "\" \"" + f2 + "\"");

    ProcessBuilder builder = new ProcessBuilder(command);
    builder.directory(new CSFile("c:\\temp"));
    builder.start();
  }
 
Example #14
Source File: XmlSchemaGenerator.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
private StructureDefinition getCommonAncestor(StructureDefinition sd1, StructureDefinition sd2) throws FHIRException {
  // this will always return something because everything comes from Element
  List<StructureDefinition> chain1 = new ArrayList<>();
  List<StructureDefinition> chain2 = new ArrayList<>();
  chain1.add(sd1);
  chain2.add(sd2);
  StructureDefinition root = library.get("Element");
  StructureDefinition common = findIntersection(chain1, chain2);
  boolean chain1Done = false;
  boolean chain2Done = false;
  while (common == null) {
     chain1Done = checkChain(chain1, root, chain1Done);
     chain2Done = checkChain(chain2, root, chain2Done);
     if (chain1Done && chain2Done)
       return null;
     common = findIntersection(chain1, chain2);
  }
  return common;
}
 
Example #15
Source File: XmlSchemaGenerator.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
private void produceAttribute(StructureDefinition sd, ElementDefinition ed, ElementDefinition edc, String lang) throws IOException, FHIRException {
    TypeRefComponent t = edc.getTypeFirstRep();
    String name = tailDot(edc.getPath());
    String min = String.valueOf(edc.getMin());
    String max = edc.getMax();
    // todo: check it's a code...
//    if (!max.equals("1"))
//      throw new FHIRException("Illegal cardinality \""+max+"\" for attribute "+edc.getPath());
    
    String tc = t.getWorkingCode();
    if (Utilities.isAbsoluteUrl(tc)) 
      throw new FHIRException("Only FHIR primitive types are supported for attributes ("+tc+")");
    String typeNs = namespaces.get("http://hl7.org/fhir");
    String type = tc; 
    
    w("        <xs:attribute name=\""+name+"\" use=\""+(min.equals("0") || edc.hasFixed() || edc.hasDefaultValue() ? "optional" : "required")+"\" type=\""+typeNs+":"+type+(typeNs.equals("fhir") ? "-primitive" : "")+"\""+
    (edc.hasFixed() ? " fixed=\""+edc.getFixed().primitiveValue()+"\"" : "")+(edc.hasDefaultValue() && !edc.hasFixed() ? " default=\""+edc.getDefaultValue().primitiveValue()+"\"" : "")+"");
    if (annotations && edc.hasDefinition()) {
      ln(">");
      ln("          <xs:annotation>");
      ln("            <xs:documentation xml:lang=\""+lang+"\">"+Utilities.escapeXml(edc.getDefinition())+"</xs:documentation>");
      ln("          </xs:annotation>");
      ln("        </xs:attribute>");
    } else
      ln("/>");
  }
 
Example #16
Source File: SimpleWorkerContext.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
public void generateSnapshot(StructureDefinition p) throws DefinitionException, FHIRException {
  if (!p.hasSnapshot() && p.getKind() != StructureDefinitionKind.LOGICAL) {
    if (!p.hasBaseDefinition())
      throw new DefinitionException("Profile "+p.getName()+" ("+p.getUrl()+") has no base and no snapshot");
    StructureDefinition sd = fetchResource(StructureDefinition.class, p.getBaseDefinition());
    if (sd == null)
      throw new DefinitionException("Profile "+p.getName()+" ("+p.getUrl()+") base "+p.getBaseDefinition()+" could not be resolved");
    List<ValidationMessage> msgs = new ArrayList<ValidationMessage>();
    List<String> errors = new ArrayList<String>();
    ProfileUtilities pu = new ProfileUtilities(this, msgs, this);
    pu.setThrowException(false);
    pu.sortDifferential(sd, p, p.getUrl(), errors);
    for (String err : errors)
      msgs.add(new ValidationMessage(Source.ProfileValidator, IssueType.EXCEPTION, p.getUserString("path"), "Error sorting Differential: "+err, ValidationMessage.IssueSeverity.ERROR));
    pu.generateSnapshot(sd, p, p.getUrl(), Utilities.extractBaseUrl(sd.getUserString("path")), p.getName());
    for (ValidationMessage msg : msgs) {
      if ((!ignoreProfileErrors && msg.getLevel() == ValidationMessage.IssueSeverity.ERROR) || msg.getLevel() == ValidationMessage.IssueSeverity.FATAL)
        throw new DefinitionException("Profile "+p.getName()+" ("+p.getUrl()+"). Error generating snapshot: "+msg.getMessage());
    }
    if (!p.hasSnapshot())
      throw new FHIRException("Profile "+p.getName()+" ("+p.getUrl()+"). Error generating snapshot");
    pu = null;
  }
}
 
Example #17
Source File: ShExGenerator.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
/**
 * Generate a flattened definition for the inner types
 * @return stringified inner type definitions
 */
private String emitInnerTypes() {
  StringBuilder itDefs = new StringBuilder();
  while(emittedInnerTypes.size() < innerTypes.size()) {
    for (Pair<StructureDefinition, ElementDefinition> it : new HashSet<Pair<StructureDefinition, ElementDefinition>>(innerTypes)) {
      if (!emittedInnerTypes.contains(it)) {
        itDefs.append("\n").append(genInnerTypeDef(it.getLeft(), it.getRight()));
        emittedInnerTypes.add(it);
      }
    }
  }
  return itDefs.toString();
}
 
Example #18
Source File: ShExGenerator.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
/**
 * Generate a list of type choices for a "name[x]" style id
 * @param sd Structure containing ed
 * @param ed element definition
 * @param id choice identifier
 * @return ShEx fragment for the set of choices
 */
private String genChoiceTypes(StructureDefinition sd, ElementDefinition ed, String id) {
  List<String> choiceEntries = new ArrayList<String>();
  String base = id.replace("[x]", "");

  for(ElementDefinition.TypeRefComponent typ : ed.getType())
    choiceEntries.add(genChoiceEntry(sd, ed, id, base, typ));

  return StringUtils.join(choiceEntries, " |\n");
}
 
Example #19
Source File: DefinitionNavigator.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private DefinitionNavigator(IWorkerContext context, StructureDefinition structure, int index, String path, List<String> names, String type) {
  this.path = path;
  this.context = context;
  this.structure = structure;
  this.index = index;
  if (type == null)
    for (String name : names)
      this.names.add(name+"."+nameTail());
  else {
    this.names.addAll(names);
    this.names.add(type);
  }
}
 
Example #20
Source File: ShExGenerator.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
/**
 * Generate an entry in a choice list
 * @param base base identifier
 * @param typ type/discriminant
 * @return ShEx fragment for choice entry
 */
private String genChoiceEntry(StructureDefinition sd, ElementDefinition ed, String id, String base, ElementDefinition.TypeRefComponent typ) {
  ST shex_choice_entry = tmplt(ELEMENT_TEMPLATE);

  String ext = typ.getWorkingCode();
  shex_choice_entry.add("id", "fhir:" + base+Character.toUpperCase(ext.charAt(0)) + ext.substring(1) + " ");
  shex_choice_entry.add("card", "");
  shex_choice_entry.add("defn", genTypeRef(sd, ed, id, typ));
  shex_choice_entry.add("comment", " ");
  return shex_choice_entry.render();
}
 
Example #21
Source File: DefinitionNavigator.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
public DefinitionNavigator(IWorkerContext context, StructureDefinition structure) throws DefinitionException {
  if (!structure.hasSnapshot())
    throw new DefinitionException("Snapshot required");
  this.context = context;
  this.structure = structure;
  this.index = 0;
  this.path = current().getPath();
  names.add(nameTail());
}
 
Example #22
Source File: ExtensionDefinitionGenerator.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private void savePackage(List<StructureDefinition> extensions) throws FHIRException, IOException {
  JsonObject npm = new JsonObject();
  npm.addProperty("name", "hl7.fhir.extensions.r"+sourceVersion.toCode(1));
  npm.addProperty("version", targetVersion.toCode(3));
  npm.addProperty("tools-version", ToolsVersion.TOOLS_VERSION);
  npm.addProperty("type", PackageType.IG.getCode());
  npm.addProperty("license", SPDXLicense.CC01_0.toCode());
  npm.addProperty("canonical", "http://hl7.org/fhir/"+sourceVersion.toCode(3)+"/extensions/"+targetVersion.toCode(3));
  npm.addProperty("url", "http://hl7.org/fhir/"+sourceVersion.toCode(3)+"/extensions/"+targetVersion.toCode(3));
  npm.addProperty("title", "Extension Definitions for representing elements from "+sourceVersion.toCode()+" in "+targetVersion.toCode());
  npm.addProperty("description", "Extension Definitions for representing elements from "+sourceVersion.toCode()+" in "+targetVersion.toCode()+" built "+new SimpleDateFormat("EEE, MMM d, yyyy HH:mmZ", new Locale("en", "US")).format(Calendar.getInstance().getTime())+timezone()+")");
  JsonObject dep = new JsonObject();
  npm.add("dependencies", dep);
  dep.addProperty("hl7.fhir.core", targetVersion.toCode());
  npm.addProperty("author", "FHIR Project");
  JsonArray m = new JsonArray();
  JsonObject md = new JsonObject();
  m.add(md);
  md.addProperty("name", "FHIR Project");
  md.addProperty("url", "http://hl7.org/fhir");
  NPMPackageGenerator pi = new NPMPackageGenerator(filename, npm);
  for (StructureDefinition sd : extensions) {
    byte[] cnt = saveResource(sd, targetVersion); 
    pi.addFile(Category.RESOURCE, "StructureDefinition-"+sd.getId()+".json", cnt);
  }
  pi.finish();

}
 
Example #23
Source File: CareConnectProfileDbValidationSupportR4.java    From careconnect-reference-implementation with Apache License 2.0 5 votes vote down vote up
/**
 * Method to fetch a remote StructureDefinition resource.
 *
 * Caches results.
 *
 * @param theCtx FHIR Context
 * @param theUrl The URL to fetch from
 * @return The StructureDefinition resource or null
 */
@Override
public final StructureDefinition fetchStructureDefinition(
        final FhirContext theCtx,
        final String theUrl) {
    logD(
            "CareConnectValidator asked to fetch StructureDefinition: %s%n",
            theUrl);

    if (!isSupported(theUrl)) {
        log.trace("  Returning null as it's an HL7 one");
        return null;
    }

    if (cachedResource.get(theUrl) == null) {
        IBaseResource response = fetchURL(theUrl);
        log.trace("  About to parse response into a StructureDefinition");

        cachedResource.put(theUrl, (StructureDefinition) response);
        logD("  StructureDefinition now added to the cache: %s%n", theUrl);
    } else {
        logD("  This URL was already loaded: %s%n", theUrl);
    }
    StructureDefinition sd
            = (StructureDefinition)
            cachedResource.get(theUrl);
    return sd;
}
 
Example #24
Source File: StructureMapUtilities.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private String getActualType(StructureMap map, String statedType) throws FHIRException {
  // check the aliases
  for (StructureMapStructureComponent imp : map.getStructure()) {
    if (imp.hasAlias() && statedType.equals(imp.getAlias())) {
      StructureDefinition sd = worker.fetchResource(StructureDefinition.class, imp.getUrl());
      if (sd == null)
        throw new FHIRException("Unable to resolve structure "+imp.getUrl());
      return sd.getId(); // should be sd.getType(), but R2...
    }
  }
  return statedType;
}
 
Example #25
Source File: ValidationSupportR4.java    From synthea with Apache License 2.0 5 votes vote down vote up
/**
 * Defines the custom validation support for various implementation guides.
 */
public ValidationSupportR4() {
  resources = new ArrayList<IBaseResource>();
  resourcesMap = new HashMap<String, IBaseResource>();
  definitions = new ArrayList<StructureDefinition>();
  definitionsMap = new HashMap<String, StructureDefinition>();
  codeSystemMap = new HashMap<String, CodeSystem>();

  try {
    loadFromDirectory(profileDir);
  } catch (Throwable t) {
    throw new RuntimeException(t);
  }
}
 
Example #26
Source File: StructureMapUtilities.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private PropertyWithType resolveType(StructureMap map, String type, StructureMapInputMode mode) throws FHIRException {
  for (StructureMapStructureComponent imp : map.getStructure()) {
    if ((imp.getMode() == StructureMapModelMode.SOURCE && mode == StructureMapInputMode.SOURCE) || 
        (imp.getMode() == StructureMapModelMode.TARGET && mode == StructureMapInputMode.TARGET)) {
      StructureDefinition sd = worker.fetchResource(StructureDefinition.class, imp.getUrl());
      if (sd == null)
        throw new FHIRException("Import "+imp.getUrl()+" cannot be resolved");
      if (sd.getId().equals(type)) {
        return new PropertyWithType(sd.getType(), new Property(worker, sd.getSnapshot().getElement().get(0), sd), null, new TypeDetails(CollectionStatus.SINGLETON, sd.getUrl()));
      }
    }
  }
  throw new FHIRException("Unable to find structure definition for "+type+" in imports");
}
 
Example #27
Source File: StructureMapUtilities.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
public StructureMap generateMapFromMappings(StructureDefinition sd) throws IOException, FHIRException {
  String id = getLogicalMappingId(sd);
  if (id == null) 
      return null;
  String prefix = ToolingExtensions.readStringExtension(sd,  ToolingExtensions.EXT_MAPPING_PREFIX);
  String suffix = ToolingExtensions.readStringExtension(sd,  ToolingExtensions.EXT_MAPPING_SUFFIX);
  if (prefix == null || suffix == null)
    return null;
  // we build this by text. Any element that has a mapping, we put it's mappings inside it....
  StringBuilder b = new StringBuilder();
  b.append(prefix);

  ElementDefinition root = sd.getSnapshot().getElementFirstRep();
  String m = getMapping(root, id);
  if (m != null)
    b.append(m+"\r\n");
  addChildMappings(b, id, "", sd, root, false);
  b.append("\r\n");
  b.append(suffix);
  b.append("\r\n");
  StructureMap map = parse(b.toString(), sd.getUrl());
  map.setId(tail(map.getUrl()));
  if (!map.hasStatus())
    map.setStatus(PublicationStatus.DRAFT);
  map.getText().setStatus(NarrativeStatus.GENERATED);
  map.getText().setDiv(new XhtmlNode(NodeType.Element, "div"));
  map.getText().getDiv().addTag("pre").addText(render(map));
  return map;
}
 
Example #28
Source File: ProfileComparer.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private StructureDefinition resolveProfile(ElementDefinition ed, ProfileComparison outcome, String path, String url, String name) {
  StructureDefinition res = context.fetchResource(StructureDefinition.class, url);
  if (res == null) {
    outcome.messages.add(new ValidationMessage(Source.ProfileComparer, ValidationMessage.IssueType.INFORMATIONAL, path, "Unable to resolve profile "+url+" in profile "+name, ValidationMessage.IssueSeverity.WARNING));
    status(ed, ProfileUtilities.STATUS_HINT);
  }
  return res;
}
 
Example #29
Source File: ProfileUtilitiesTests.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
@Test
public void testSimple() throws FHIRException, FileNotFoundException, IOException, UcumException {

  StructureDefinition focus = new StructureDefinition();
  StructureDefinition base = TestingUtilities.context().fetchResource(StructureDefinition.class, "http://hl7.org/fhir/StructureDefinition/Patient").copy();
  focus.setUrl(Utilities.makeUuidUrn());
  focus.setBaseDefinition(base.getUrl());
  focus.setType("Patient");
  focus.setDerivation(TypeDerivationRule.CONSTRAINT);
  List<ValidationMessage> messages = new ArrayList<ValidationMessage>();
  new ProfileUtilities(TestingUtilities.context(), messages, null).generateSnapshot(base, focus, focus.getUrl(), "http://hl7.org/fhir/R4", "Simple Test");

  boolean ok = base.getSnapshot().getElement().size() == focus.getSnapshot().getElement().size();
  for (int i = 0; i < base.getSnapshot().getElement().size(); i++) {
    ElementDefinition b = base.getSnapshot().getElement().get(i);
    ElementDefinition f = focus.getSnapshot().getElement().get(i);
    if (ok) {
      if (!f.hasBase())
        ok = false;
      else if (!b.getPath().equals(f.getPath()))
        ok = false;
      else {
        b.setBase(null);
        f.setBase(null);
        ok = Base.compareDeep(b, f, true);
      }
    }
  }

  if (!ok) {
    compareXml(base, focus);
    throw new FHIRException("Snap shot generation simple test failed");
  } else
    System.out.println("Snap shot generation simple test passed");
}
 
Example #30
Source File: StructureMapUtilities.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
/**
* Given a structure map, return a set of analyses on it. 
* 
* Returned:
*   - a list or profiles for what it will create. First profile is the target
*   - a table with a summary (in xhtml) for easy human undertanding of the mapping
*   
* 
* @param appInfo
* @param map
* @return
* @throws Exception
*/
public StructureMapAnalysis analyse(Object appInfo, StructureMap map) throws FHIRException {
  ids.clear();
  StructureMapAnalysis result = new StructureMapAnalysis(); 
  TransformContext context = new TransformContext(appInfo);
  VariablesForProfiling vars = new VariablesForProfiling(false, false);
  StructureMapGroupComponent start = map.getGroup().get(0);
  for (StructureMapGroupInputComponent t : start.getInput()) {
    PropertyWithType ti = resolveType(map, t.getType(), t.getMode());
    if (t.getMode() == StructureMapInputMode.SOURCE)
     vars.add(VariableMode.INPUT, t.getName(), ti);
    else 
      vars.add(VariableMode.OUTPUT, t.getName(), createProfile(map, result.profiles, ti, start.getName(), start));
  }

  result.summary = new XhtmlNode(NodeType.Element, "table").setAttribute("class", "grid");
  XhtmlNode tr = result.summary.addTag("tr");
  tr.addTag("td").addTag("b").addText("Source");
  tr.addTag("td").addTag("b").addText("Target");
  
  log("Start Profiling Transform "+map.getUrl());
  analyseGroup("", context, map, vars, start, result);
  ProfileUtilities pu = new ProfileUtilities(worker, null, pkp);
  for (StructureDefinition sd : result.getProfiles())
    pu.cleanUpDifferential(sd);
  return result;
}