org.hl7.fhir.dstu3.model.Base Java Examples

The following examples show how to use org.hl7.fhir.dstu3.model.Base. 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: FhirXmlIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testFhirJsonMarshal() throws Exception {
    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
            .marshal().fhirXml();
        }
    });

    camelctx.start();
    try {
        Patient patient = createPatient();
        ProducerTemplate template = camelctx.createProducerTemplate();
        InputStream inputStream = template.requestBody("direct:start", patient, InputStream.class);
        IBaseResource result = FhirContext.forDstu3().newXmlParser().parseResource(new InputStreamReader(inputStream));
        Assert.assertTrue("Expected marshaled patient to be equal", patient.equalsDeep((Base)result));
    } finally {
        camelctx.close();
    }
}
 
Example #2
Source File: StructureMapUtilities.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
private void processTarget(String ruleId, TransformContext context, Variables vars, StructureMap map, StructureMapGroupComponent group, StructureMapGroupRuleTargetComponent tgt, String srcVar) throws FHIRException {
  Base dest = null;
  if (tgt.hasContext()) {
 		dest = vars.get(VariableMode.OUTPUT, tgt.getContext());
	if (dest == null)
		throw new FHIRException("Rule \""+ruleId+"\": target context not known: "+tgt.getContext());
	if (!tgt.hasElement())
		throw new FHIRException("Rule \""+ruleId+"\": Not supported yet");
  }
	Base v = null;
	if (tgt.hasTransform()) {
		v = runTransform(ruleId, context, map, group, tgt, vars, dest, tgt.getElement(), srcVar);
		if (v != null && dest != null)
			v = dest.setProperty(tgt.getElement().hashCode(), tgt.getElement(), v); // reset v because some implementations may have to rewrite v when setting the value
	} else if (dest != null) 
		v = dest.makeProperty(tgt.getElement().hashCode(), tgt.getElement());
	if (tgt.hasVariable() && v != null)
		vars.add(VariableMode.OUTPUT, tgt.getVariable(), v);
}
 
Example #3
Source File: StructureMapUtilities.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
private void executeDependency(String indent, TransformContext context, StructureMap map, Variables vin, StructureMapGroupComponent group, StructureMapGroupRuleDependentComponent dependent) throws FHIRException {
  ResolvedGroup rg = resolveGroupReference(map, group, dependent.getName());

	if (rg.target.getInput().size() != dependent.getVariable().size()) {
		throw new FHIRException("Rule '"+dependent.getName()+"' has "+Integer.toString(rg.target.getInput().size())+" but the invocation has "+Integer.toString(dependent.getVariable().size())+" variables");
	}
	Variables v = new Variables();
	for (int i = 0; i < rg.target.getInput().size(); i++) {
		StructureMapGroupInputComponent input = rg.target.getInput().get(i);
		StringType rdp = dependent.getVariable().get(i);
     String var = rdp.asStringValue();
		VariableMode mode = input.getMode() == StructureMapInputMode.SOURCE ? VariableMode.INPUT :   VariableMode.OUTPUT; 
		Base vv = vin.get(mode, var);
     if (vv == null && mode == VariableMode.INPUT) //* once source, always source. but target can be treated as source at user convenient
       vv = vin.get(VariableMode.OUTPUT, var);
		if (vv == null)
			throw new FHIRException("Rule '"+dependent.getName()+"' "+mode.toString()+" variable '"+input.getName()+"' named as '"+var+"' has no value");
		v.add(mode, input.getName(), vv);    	
	}
	executeGroup(indent+"  ", context, rg.targetMap, v, rg.target);
}
 
Example #4
Source File: ProfileComparer.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
private ElementDefinitionBindingComponent unionBindings(ElementDefinition ed, ProfileComparison outcome, String path, ElementDefinitionBindingComponent left, ElementDefinitionBindingComponent right) throws FHIRFormatError {
  ElementDefinitionBindingComponent union = new ElementDefinitionBindingComponent();
  if (left.getStrength().compareTo(right.getStrength()) < 0)
    union.setStrength(left.getStrength());
  else
    union.setStrength(right.getStrength());
  union.setDescription(mergeText(ed, outcome, path, "binding.description", left.getDescription(), right.getDescription()));
  if (Base.compareDeep(left.getValueSet(), right.getValueSet(), false))
    union.setValueSet(left.getValueSet());
  else {
    ValueSet lvs = resolveVS(outcome.left, left.getValueSet());
    ValueSet rvs = resolveVS(outcome.left, right.getValueSet());
    if (lvs != null && rvs != null)
      union.setValueSet(new Reference().setReference("#"+addValueSet(unite(ed, outcome, path, lvs, rvs))));
    else if (lvs != null)
      union.setValueSet(new Reference().setReference("#"+addValueSet(lvs)));
    else if (rvs != null)
      union.setValueSet(new Reference().setReference("#"+addValueSet(rvs)));
  }
  return union;
}
 
Example #5
Source File: ProfileComparer.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
private boolean ruleCompares(ElementDefinition ed, Type vLeft, Type vRight, String path, int nullStatus) throws IOException {
  if (vLeft == null && vRight == null && nullStatus == BOTH_NULL)
    return true;
  if (vLeft == null && vRight == null) {
    messages.add(new ValidationMessage(Source.ProfileComparer, ValidationMessage.IssueType.STRUCTURE, path, "Must be the same and not null (null/null)", ValidationMessage.IssueSeverity.ERROR));
    status(ed, ProfileUtilities.STATUS_ERROR);
  }
  if (vLeft == null && nullStatus == EITHER_NULL)
    return true;
  if (vRight == null && nullStatus == EITHER_NULL)
    return true;
  if (vLeft == null || vRight == null || !Base.compareDeep(vLeft, vRight, false)) {
    messages.add(new ValidationMessage(Source.ProfileComparer, ValidationMessage.IssueType.STRUCTURE, path, "Must be the same ("+toString(vLeft)+"/"+toString(vRight)+")", ValidationMessage.IssueSeverity.ERROR));
    status(ed, ProfileUtilities.STATUS_ERROR);
  }
  return true;
}
 
Example #6
Source File: ObjectConverter.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
private Element convertElement(Property property, Base base) throws FHIRException {
  if (base == null)
    return null;
  String tn = base.fhirType();
  StructureDefinition sd = context.fetchTypeDefinition(tn);
  if (sd == null)
    throw new FHIRException("Unable to find definition for type "+tn);
  Element res = new Element(property.getName(), property);
  if (sd.getKind() == StructureDefinitionKind.PRIMITIVETYPE) 
    res.setValue(((PrimitiveType) base).asStringValue());

  List<ElementDefinition> children = ProfileUtilities.getChildMap(sd, sd.getSnapshot().getElementFirstRep()); 
  for (ElementDefinition child : children) {
    String n = tail(child.getPath());
    if (sd.getKind() != StructureDefinitionKind.PRIMITIVETYPE || !"value".equals(n)) {
      Base[] values = base.getProperty(n.hashCode(), n, false);
      if (values != null)
        for (Base value : values) {
          res.getChildren().add(convertElement(new Property(context, child, sd), value));
        }
    }
  }
  return res;
}
 
Example #7
Source File: Element.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
@Override
	public Base[] getProperty(int hash, String name, boolean checkValid) throws FHIRException {
  	if (isPrimitive() && (hash == "value".hashCode()) && !Utilities.noString(value)) {
//  		String tn = getType();
//  		throw new Error(tn+" not done yet");
  	  Base[] b = new Base[1];
  	  b[0] = new StringType(value);
  	  return b;
  	}
  		
  	List<Base> result = new ArrayList<Base>();
  	if (children != null) {
  	for (Element child : children) {
  		if (child.getName().equals(name))
  			result.add(child);
  		if (child.getName().startsWith(name) && child.getProperty().isChoice() && child.getProperty().getName().equals(name+"[x]"))
  			result.add(child);
  	}
  	}
  	if (result.isEmpty() && checkValid) {
//  		throw new FHIRException("not determined yet");
  	}
  	return result.toArray(new Base[result.size()]);
	}
 
Example #8
Source File: Stu3FhirConversionSupport.java    From bunsen with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, List> compositeValues(IBase composite) {

  List<Property> children = ((Base) composite).children();

  if (children == null) {

    return null;
  } else {

    // Some FHIR resources produce duplicate properties in the children,
    // so just use the first when converting to a map.
    return children.stream()
        .filter(property -> property.hasValues())
        .collect(
            Collectors.toMap(Property::getName,
                property -> property.getValues(),
                (first, second) -> first));
  }
}
 
Example #9
Source File: FhirJsonIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testFhirJsonMarshal() throws Exception {
    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
            .marshal().fhirJson("DSTU3");
        }
    });

    camelctx.start();
    try {
        Patient patient = createPatient();
        ProducerTemplate template = camelctx.createProducerTemplate();
        InputStream inputStream = template.requestBody("direct:start", patient, InputStream.class);
        IBaseResource result = FhirContext.forDstu3().newJsonParser().parseResource(new InputStreamReader(inputStream));
        Assert.assertTrue("Expected marshaled patient to be equal", patient.equalsDeep((Base)result));
    } finally {
        camelctx.close();
    }
}
 
Example #10
Source File: Element.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
@Override
public boolean equalsShallow(Base other) {
  if (!super.equalsShallow(other))
    return false;
  if (isPrimitive() && other.isPrimitive())
    return primitiveValue().equals(other.primitiveValue());
  if (isPrimitive() || other.isPrimitive())
    return false;
  return true; //?
}
 
Example #11
Source File: ProfileComparer.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private boolean mergeIntoExisting(List<ConceptSetComponent> include, ConceptSetComponent inc) {
  for (ConceptSetComponent dst : include) {
    if (Base.compareDeep(dst,  inc, false))
      return true; // they're actually the same
    if (dst.getSystem().equals(inc.getSystem())) {
      if (inc.hasFilter() || dst.hasFilter()) {
        return false; // just add the new one as a a parallel
      } else if (inc.hasConcept() && dst.hasConcept()) {
        for (ConceptReferenceComponent cc : inc.getConcept()) {
          boolean found = false;
          for (ConceptReferenceComponent dd : dst.getConcept()) {
            if (dd.getCode().equals(cc.getCode()))
              found = true;
            if (found) {
              if (cc.hasDisplay() && !dd.hasDisplay())
                dd.setDisplay(cc.getDisplay());
              break;
            }
          }
          if (!found)
            dst.getConcept().add(cc.copy());
        }
      } else
        dst.getConcept().clear(); // one of them includes the entire code system 
    }
  }
  return false;
}
 
Example #12
Source File: Element.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private boolean equalsDeep(org.hl7.fhir.dstu3.model.Property p, org.hl7.fhir.dstu3.model.Property o) {
  if (o == null || p == null)
    return false;
  if (p.getValues().size() != o.getValues().size())
    return false;
  for (int i = 0; i < p.getValues().size(); i++)
    if (!Base.compareDeep(p.getValues().get(i), o.getValues().get(i), true))
      return false;
  return true;
}
 
Example #13
Source File: R2R3ConversionManager.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
@Override
public List<Base> performSearch(Object appContext, String url) {
  List<Base> results = new ArrayList<Base>();
  String[] parts = url.split("\\?");
  if (parts.length == 2 && parts[0].substring(1).equals("PractitionerRole")) {
    String[] vals = parts[1].split("\\=");
    if (vals.length == 2 && vals[0].equals("practitioner"))
    for (Resource r : extras) {
      if (r instanceof PractitionerRole && ((PractitionerRole) r).getPractitioner().getReference().equals("Practitioner/"+vals[1])) {
        results.add(r);
      }
    }
  }
  return results;
}
 
Example #14
Source File: StructureMapUtilities.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
public Base resolveConstant(Object appContext, String name) throws PathEngineException {
  Variables vars = (Variables) appContext;
  Base res = vars.get(VariableMode.INPUT, name);
  if (res == null)
    res = vars.get(VariableMode.OUTPUT, name);
  return res;
}
 
Example #15
Source File: StructureMapUtilities.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
public void add(VariableMode mode, String name, Base object) {
	Variable vv = null;
	for (Variable v : list) 
		if ((v.mode == mode) && v.getName().equals(name))
			vv = v;
	if (vv != null)
		list.remove(vv);
	list.add(new Variable(mode, name, object));
}
 
Example #16
Source File: StructureMapUtilities.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private String getParamStringNoNull(Variables vars, StructureMapGroupRuleTargetParameterComponent parameter, String message) throws FHIRException {
  Base b = getParam(vars, parameter);
  if (b == null)
    throw new FHIRException("Unable to find a value for "+parameter.toString()+". Context: "+message);
  if (!b.hasPrimitiveValue())
    throw new FHIRException("Found a value for "+parameter.toString()+", but it has a type of "+b.fhirType()+" and cannot be treated as a string. Context: "+message);
  return b.primitiveValue();
}
 
Example #17
Source File: StructureMapUtilities.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
public void transform(Object appInfo, Base source, StructureMap map, Base target) throws FHIRException {
	TransformContext context = new TransformContext(appInfo);
   log("Start Transform "+map.getUrl());
   StructureMapGroupComponent g = map.getGroup().get(0);

	Variables vars = new Variables();
	vars.add(VariableMode.INPUT, getInputName(g, StructureMapInputMode.SOURCE, "source"), source);
	vars.add(VariableMode.OUTPUT, getInputName(g, StructureMapInputMode.TARGET, "target"), target);

   executeGroup("", context, map, vars, g);
   if (target instanceof Element)
     ((Element) target).sort();
}
 
Example #18
Source File: StructureMapUtilities.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private void executeRule(String indent, TransformContext context, StructureMap map, Variables vars, StructureMapGroupComponent group, StructureMapGroupRuleComponent rule) throws FHIRException {
	log(indent+"rule : "+rule.getName());
	if (rule.getName().contains("CarePlan.participant-unlink"))
	  System.out.println("debug");
	Variables srcVars = vars.copy();
	if (rule.getSource().size() != 1)
		throw new FHIRException("Rule \""+rule.getName()+"\": not handled yet");
	List<Variables> source = processSource(rule.getName(), context, srcVars, rule.getSource().get(0));
	if (source != null) {
		for (Variables v : source) {
			for (StructureMapGroupRuleTargetComponent t : rule.getTarget()) {
				processTarget(rule.getName(), context, v, map, group, t, rule.getSource().size() == 1 ? rule.getSourceFirstRep().getVariable() : null);
			}
			if (rule.hasRule()) {
				for (StructureMapGroupRuleComponent childrule : rule.getRule()) {
					executeRule(indent +"  ", context, map, v, group, childrule);
				}
			} else if (rule.hasDependent()) {
				for (StructureMapGroupRuleDependentComponent dependent : rule.getDependent()) {
					executeDependency(indent+"  ", context, map, v, group, dependent);
				}
			} else if (rule.getSource().size() == 1 && rule.getSourceFirstRep().hasVariable() && rule.getTarget().size() == 1 && rule.getTargetFirstRep().hasVariable() && rule.getTargetFirstRep().getTransform() == StructureMapTransform.CREATE && !rule.getTargetFirstRep().hasParameter()) {
			  // simple inferred, map by type
			  Base src = v.get(VariableMode.INPUT, rule.getSourceFirstRep().getVariable());
			  Base tgt = v.get(VariableMode.OUTPUT, rule.getTargetFirstRep().getVariable());
			  String srcType = src.fhirType();
			  String tgtType = tgt.fhirType();
			  ResolvedGroup defGroup = resolveGroupByTypes(map, rule.getName(), group, srcType, tgtType);
		    Variables vdef = new Variables();
         vdef.add(VariableMode.INPUT, defGroup.target.getInput().get(0).getName(), src);
         vdef.add(VariableMode.OUTPUT, defGroup.target.getInput().get(1).getName(), tgt);
			  executeGroup(indent+"  ", context, defGroup.targetMap, vdef, defGroup.target);
			}
		}
	}
}
 
Example #19
Source File: R2R3ConversionManager.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
@Override
public Base createResource(Object appInfo, Base res) {
  if (res instanceof Resource && (res.fhirType().equals("CodeSystem") || res.fhirType().equals("CareTeam")) || res.fhirType().equals("PractitionerRole")) {
    Resource r = (Resource) res;
    extras.add(r);
    r.setId(((TransformContext) appInfo).getId()+"-"+extras.size()); //todo: get this into appinfo
  }
  return res;
}
 
Example #20
Source File: FhirDstu3Processor.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@BuildStep(onlyIf = FhirFlags.Dstu3Enabled.class)
void enableReflection(BuildProducer<ReflectiveClassBuildItem> reflectiveClass,
        Dstu3PropertiesBuildItem propertiesBuildItem) {
    Set<String> classes = new HashSet<>();
    classes.add(DomainResource.class.getCanonicalName());
    classes.add(Resource.class.getCanonicalName());
    classes.add(org.hl7.fhir.dstu3.model.BaseResource.class.getCanonicalName());
    classes.add(Base.class.getCanonicalName());
    classes.addAll(getModelClasses(propertiesBuildItem.getProperties()));
    classes.addAll(getInnerClasses(Enumerations.class.getCanonicalName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(true, true, true, Meta.class.getCanonicalName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(true, true, true, MetadataResource.class.getCanonicalName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, classes.toArray(new String[0])));
}
 
Example #21
Source File: StructureMapUtilities.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private Base getParam(Variables vars, StructureMapGroupRuleTargetParameterComponent parameter) throws DefinitionException {
	Type p = parameter.getValue();
	if (!(p instanceof IdType))
		return p;
	else { 
		String n = ((IdType) p).asStringValue();
     Base b = vars.get(VariableMode.INPUT, n);
		if (b == null)
			b = vars.get(VariableMode.OUTPUT, n);
		if (b == null)
       throw new DefinitionException("Variable "+n+" not found ("+vars.summary()+")");
		return b;
	}
}
 
Example #22
Source File: QuestionnaireBuilder.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private void processExisting(String path, List<QuestionnaireResponse.QuestionnaireResponseItemComponent> answerGroups, List<QuestionnaireResponse.QuestionnaireResponseItemComponent> nResponse) throws FHIRException {
  // processing existing data
  for (QuestionnaireResponse.QuestionnaireResponseItemComponent ag : answerGroups) {
    List<Base> children = ((Element) ag.getUserData("object")).listChildrenByName(tail(path));
    for (Base child : children) {
      if (child != null) {
        QuestionnaireResponse.QuestionnaireResponseItemComponent ans = ag.addItem();
        ans.setUserData("object", child);
        nResponse.add(ans);
      }
    }
  }
}
 
Example #23
Source File: NarrativeGenerator.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
@Override
  public Base getBase() throws UnsupportedEncodingException, IOException, FHIRException {
    if (type == null || type.equals("Resource") || type.equals("BackboneElement") || type.equals("Element"))
      return null;

    String xml;
try {
	xml = new XmlGenerator().generate(element);
} catch (org.hl7.fhir.exceptions.FHIRException e) {
	throw new FHIRException(e.getMessage(), e);
}
    return context.newXmlParser().setOutputStyle(OutputStyle.PRETTY).parseType(xml, type);
  }
 
Example #24
Source File: NarrativeGenerator.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
@Override
public Base getBase() throws UnsupportedEncodingException, IOException, FHIRException {
  if (type == null || type.equals("Resource") || type.equals("BackboneElement") || type.equals("Element"))
    return null;

  if (element.hasElementProperty())
    return null;
  ByteArrayOutputStream xml = new ByteArrayOutputStream();
  try {
    new org.hl7.fhir.dstu3.elementmodel.XmlParser(context).compose(element, xml, OutputStyle.PRETTY, null);
  } catch (Exception e) {
    throw new FHIRException(e.getMessage(), e);
  }
  return context.newXmlParser().setOutputStyle(OutputStyle.PRETTY).parseType(xml.toString(), type);
}
 
Example #25
Source File: NarrativeGenerator.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
@Override
public List<BaseWrapper> getValues() {
  if (list == null) {
    list = new ArrayList<NarrativeGenerator.BaseWrapper>();
    for (Base b : wrapped.getValues())
      list.add(b == null ? null : new BaseWrapperDirect(b));
  }
  return list;
}
 
Example #26
Source File: NarrativeGenerator.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
public XhtmlNode renderBundle(org.hl7.fhir.dstu3.elementmodel.Element element) throws FHIRException {
  XhtmlNode root = new XhtmlNode(NodeType.Element, "div");
  for (Base b : element.listChildrenByName("entry")) {
    XhtmlNode c = getHtmlForResource(((org.hl7.fhir.dstu3.elementmodel.Element) b).getNamedChild("resource"));
    if (c != null)
      root.getChildNodes().addAll(c.getChildNodes());
    root.hr();
  }
  return root;
}
 
Example #27
Source File: SnapShotGenerationTests.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
@Override
public List<Base> executeFunction(Object appContext, String functionName, List<List<Base>> parameters) {
  if ("fixture".equals(functionName)) {
    String id = fp.convertToString(parameters.get(0));
    Resource res = fetchFixture(id);
    if (res != null) {
      List<Base> list = new ArrayList<Base>();
      list.add(res);
      return list;
    }
  }
  return null;
}
 
Example #28
Source File: ProfileUtilitiesTests.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
/**
 * This is simple: we just create an empty differential, generate the snapshot, and then insist it must match the base 
 * 
 * @param context2
 * @
 * @throws EOperationOutcome 
 */
private void testSimple() throws EOperationOutcome, Exception {
  StructureDefinition focus = new StructureDefinition();
  StructureDefinition base = 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(context, messages, null).generateSnapshot(base, focus, focus.getUrl(), "Simple Test");

  boolean ok = base.getSnapshot().getElement().size() == focus.getSnapshot().getElement().size();
  for (int i = 0; i < base.getSnapshot().getElement().size(); i++) {
    if (ok) {
      ElementDefinition b = base.getSnapshot().getElement().get(i);
      ElementDefinition f = focus.getSnapshot().getElement().get(i);
      if (!f.hasBase() || !b.getPath().equals(f.getBase().getPath())) 
        ok = false;
      else {
        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 #29
Source File: ProfileUtilitiesTests.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
/**
 * This is simple: we just create an empty differential, generate the snapshot, and then insist it must match the base. for a different resource with recursion 
 * 
 * @param context2
 * @
 * @throws EOperationOutcome 
 */
private void testSimple2() throws EOperationOutcome, Exception {
  StructureDefinition focus = new StructureDefinition();
  StructureDefinition base = context.fetchResource(StructureDefinition.class, "http://hl7.org/fhir/StructureDefinition/ValueSet").copy();
  focus.setUrl(Utilities.makeUuidUrn());
  focus.setBaseDefinition(base.getUrl());
  focus.setType(base.getType());
  focus.setDerivation(TypeDerivationRule.CONSTRAINT);
  List<ValidationMessage> messages = new ArrayList<ValidationMessage>();
  new ProfileUtilities(context, messages, null).generateSnapshot(base, focus, focus.getUrl(), "Simple Test" );

  boolean ok = base.getSnapshot().getElement().size() == focus.getSnapshot().getElement().size();
  for (int i = 0; i < base.getSnapshot().getElement().size(); i++) {
    if (ok) {
      ElementDefinition b = base.getSnapshot().getElement().get(i);
      ElementDefinition f = focus.getSnapshot().getElement().get(i);
      if (!f.hasBase() || !b.getPath().equals(f.getBase().getPath())) 
        ok = false;
      else {
        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: ProfileUtilitiesTests.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
/**
 * Change one cardinality.
 * 
 * @param context2
 * @
 * @throws EOperationOutcome 
 */
private void testCardinalityChange() throws EOperationOutcome, Exception {
  StructureDefinition focus = new StructureDefinition();
  StructureDefinition base = context.fetchResource(StructureDefinition.class, "http://hl7.org/fhir/StructureDefinition/Patient").copy();
  focus.setUrl(Utilities.makeUuidUrn());
  focus.setBaseDefinition(base.getUrl());
  focus.setType(base.getType());
  focus.setDerivation(TypeDerivationRule.CONSTRAINT);
  ElementDefinition id = focus.getDifferential().addElement();
  id.setPath("Patient.identifier");
  id.setMin(1);
  List<ValidationMessage> messages = new ArrayList<ValidationMessage>();
  new ProfileUtilities(context, messages, null).generateSnapshot(base, focus, focus.getUrl(), "Simple Test" );

  boolean ok = base.getSnapshot().getElement().size() == focus.getSnapshot().getElement().size();
  for (int i = 0; i < base.getSnapshot().getElement().size(); i++) {
    if (ok) {
      ElementDefinition b = base.getSnapshot().getElement().get(i);
      ElementDefinition f = focus.getSnapshot().getElement().get(i);
      if (!f.hasBase() || !b.getPath().equals(f.getBase().getPath())) 
        ok = false;
      else {
        f.setBase(null);
        if (f.getPath().equals("Patient.identifier")) {
          ok = f.getMin() == 1;
          if (ok)
            f.setMin(0);
        }
        ok = ok && Base.compareDeep(b, f, true);
      }
    }
  }
  
  if (!ok) {
    compareXml(base, focus);
    throw new FHIRException("Snap shot generation chenge cardinality test failed");
  } else 
    System.out.println("Snap shot generation chenge cardinality test passed");
}