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

The following examples show how to use org.hl7.fhir.dstu3.model.Resource. 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: SimpleWorkerContext.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
public void seeResource(String url, Resource r) throws FHIRException {
   if (r instanceof StructureDefinition)
     seeProfile(url, (StructureDefinition) r);
   else if (r instanceof ValueSet)
     seeValueSet(url, (ValueSet) r);
   else if (r instanceof CodeSystem)
     seeCodeSystem(url, (CodeSystem) r);
   else if (r instanceof OperationDefinition)
     seeOperationDefinition(url, (OperationDefinition) r);
   else if (r instanceof ConceptMap)
     maps.put(((ConceptMap) r).getUrl(), (ConceptMap) r);
   else if (r instanceof StructureMap)
     transforms.put(((StructureMap) r).getUrl(), (StructureMap) r);
   else if (r instanceof NamingSystem)
   	systems.add((NamingSystem) r);
}
 
Example #2
Source File: ProfileUtilities.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
public StructureDefinition getProfile(StructureDefinition source, String url) {
	StructureDefinition profile = null;
	String code = null;
	if (url.startsWith("#")) {
		profile = source;
		code = url.substring(1);
	} else if (context != null) {
		String[] parts = url.split("\\#");
		profile = context.fetchResource(StructureDefinition.class, parts[0]);
    code = parts.length == 1 ? null : parts[1];
	}  	  
	if (profile == null)
		return null;
	if (code == null)
		return profile;
	for (Resource r : profile.getContained()) {
		if (r instanceof StructureDefinition && r.getId().equals(code))
			return (StructureDefinition) r;
	}
	return null;
}
 
Example #3
Source File: ValueSetExpansionCache.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
private void loadCache() throws FHIRFormatError, IOException {
 File[] files = new File(cacheFolder).listFiles();
  for (File f : files) {
    if (f.getName().endsWith(".xml")) {
      final FileInputStream is = new FileInputStream(f);
      try {	   
      Resource r = context.newXmlParser().setOutputStyle(OutputStyle.PRETTY).parse(is);
      if (r instanceof OperationOutcome) {
        OperationOutcome oo = (OperationOutcome) r;
        expansions.put(ToolingExtensions.getExtension(oo,VS_ID_EXT).getValue().toString(),
          new ValueSetExpansionOutcome(new XhtmlComposer(XhtmlComposer.XML).composePlainText(oo.getText().getDiv()), TerminologyServiceErrorClass.UNKNOWN));
      } else {
        ValueSet vs = (ValueSet) r; 
        expansions.put(vs.getUrl(), new ValueSetExpansionOutcome(vs));
      }
      } finally {
        IOUtils.closeQuietly(is);
      }
    }
  }
}
 
Example #4
Source File: FhirStu3.java    From synthea with Apache License 2.0 6 votes vote down vote up
/**
 * Helper function to create an Entry for the given Resource within the given Bundle.
 * Sets the entry's fullURL to resourceID, and adds the entry to the bundle.
 *
 * @param bundle The Bundle to add the Entry to
 * @param resource Resource the new Entry should contain
 * @param resourceID The Resource ID to assign
 * @return the created Entry
 */
private static BundleEntryComponent newEntry(Bundle bundle, Resource resource,
    String resourceID) {
  BundleEntryComponent entry = bundle.addEntry();

  resource.setId(resourceID);
  if (Boolean.parseBoolean(Config.get("exporter.fhir.bulk_data"))) {
    entry.setFullUrl(resource.fhirType() + "/" + resourceID);
  } else {
    entry.setFullUrl("urn:uuid:" + resourceID);
  }
  entry.setResource(resource);

  if (TRANSACTION_BUNDLE) {
    BundleEntryRequestComponent request = entry.getRequest();
    request.setMethod(HTTPVerb.POST);
    request.setUrl(resource.getResourceType().name());
    entry.setRequest(request);
  }

  return entry;
}
 
Example #5
Source File: NarrativeGenerator.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
public XhtmlNode generateDocumentNarrative(Bundle feed) {
  /*
   When the document is presented for human consumption, applications must present the collated narrative portions of the following resources in order:
   * The Composition resource
   * The Subject resource
   * Resources referenced in the section.content
   */
  XhtmlNode root = new XhtmlNode(NodeType.Element, "div");
  Composition comp = (Composition) feed.getEntry().get(0).getResource();
  root.getChildNodes().add(comp.getText().getDiv());
  Resource subject = ResourceUtilities.getById(feed, null, comp.getSubject().getReference());
  if (subject != null && subject instanceof DomainResource) {
    root.hr();
    root.getChildNodes().add(((DomainResource)subject).getText().getDiv());
  }
  List<SectionComponent> sections = comp.getSection();
  renderSections(feed, root, sections, 1);
  return root;
}
 
Example #6
Source File: ToolsHelper.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
public void executeRoundTrip(String[] args) throws IOException, FHIRException {
	FileInputStream in;
	File source = new CSFile(args[1]);
	File dest = new CSFile(args[2]);
	if (args.length >= 4) {
		Utilities.copyFile(args[1], args[3]);
	}

	if (!source.exists())        
		throw new FHIRException("Source File \""+source.getAbsolutePath()+"\" not found");
	in = new CSFileInputStream(source);
	XmlParser p = new XmlParser();
	JsonParser parser = new JsonParser();
	JsonParser pj = parser;
	Resource rf = p.parse(in);
	ByteArrayOutputStream json = new ByteArrayOutputStream();
	parser.setOutputStyle(OutputStyle.PRETTY);
	parser.compose(json, rf);
	json.close();
	TextFile.stringToFile(new String(json.toByteArray()), Utilities.changeFileExt(dest.getAbsolutePath(), ".json"));
	rf = pj.parse(new ByteArrayInputStream(json.toByteArray()));
	FileOutputStream s = new FileOutputStream(dest);
	new XmlParser().compose(s, rf, true);
	s.close();
}
 
Example #7
Source File: FHIRToolingClient.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
public <T extends Resource> T vread(Class<T> resourceClass, String id, String version) {
	ResourceRequest<T> result = null;
	try {
		result = utils.issueGetResourceRequest(resourceAddress.resolveGetUriFromResourceClassAndIdAndVersion(resourceClass, id, version), getPreferredResourceFormat());
		result.addErrorStatus(410);//gone
		result.addErrorStatus(404);//unknown
		result.addErrorStatus(405);//unknown
		result.addSuccessStatus(200);//Only one for now
		if(result.isUnsuccessfulRequest()) {
			throw new EFhirClientException("Server returned error code " + result.getHttpStatus(), (OperationOutcome)result.getPayload());
		}
	} catch (Exception e) {
		handleException("An error has occurred while trying to read this version of the resource", e);
	}
	return result.getPayload();
}
 
Example #8
Source File: FHIRToolingClient.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
public ValueSet expandValueset(ValueSet source, ExpansionProfile profile) {
  List<Header> headers = null;
  Parameters p = new Parameters();
  p.addParameter().setName("valueSet").setResource(source);
  if (profile != null)
    p.addParameter().setName("profile").setResource(profile);
  ResourceRequest<Resource> result = utils.issuePostRequest(resourceAddress.resolveOperationUri(ValueSet.class, "expand"), 
      utils.getResourceAsByteArray(p, false, isJson(getPreferredResourceFormat())), getPreferredResourceFormat(), headers);
  result.addErrorStatus(410);//gone
  result.addErrorStatus(404);//unknown
  result.addErrorStatus(405);
  result.addErrorStatus(422);//Unprocessable Entity
  result.addSuccessStatus(200);
  result.addSuccessStatus(201);
  if(result.isUnsuccessfulRequest()) {
    throw new EFhirClientException("Server returned error code " + result.getHttpStatus(), (OperationOutcome)result.getPayload());
  }
  return (ValueSet) result.getPayload();
}
 
Example #9
Source File: FHIRToolingClient.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
public ConceptMap updateClosure(String name, Coding coding) {
  Parameters params = new Parameters();
  params.addParameter().setName("name").setValue(new StringType(name));
  params.addParameter().setName("concept").setValue(coding);
  List<Header> headers = null;
  ResourceRequest<Resource> result = utils.issuePostRequest(resourceAddress.resolveOperationUri(null, "closure", new HashMap<String, String>()),
      utils.getResourceAsByteArray(params, false, isJson(getPreferredResourceFormat())), getPreferredResourceFormat(), headers);
  result.addErrorStatus(410);//gone
  result.addErrorStatus(404);//unknown
  result.addErrorStatus(405);
  result.addErrorStatus(422);//Unprocessable Entity
  result.addSuccessStatus(200);
  result.addSuccessStatus(201);
  if(result.isUnsuccessfulRequest()) {
    throw new EFhirClientException("Server returned error code " + result.getHttpStatus(), (OperationOutcome)result.getPayload());
  }
  return (ConceptMap) result.getPayload();
}
 
Example #10
Source File: XmlParserBase.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
protected Resource parseResourceContained(XmlPullParser xpp) throws IOException, FHIRFormatError, XmlPullParserException  {
	next(xpp);
	int eventType = nextNoWhitespace(xpp);
	if (eventType == XmlPullParser.START_TAG) { 
		Resource r = (Resource) parseResource(xpp);
		nextNoWhitespace(xpp);
		next(xpp);
		return r;
	} else {
		unknownContent(xpp);
		return null;
	}
}
 
Example #11
Source File: XmlParserBase.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
/**
 * Compose a resource to a stream, possibly using pretty presentation for a human reader, and maybe a different choice in the xhtml narrative (used in the spec in one place, but should not be used in production)
 * @ 
 */
public void compose(OutputStream stream, Resource resource, boolean htmlPretty)  throws IOException {
	XMLWriter writer = new XMLWriter(stream, "UTF-8");
	writer.setPretty(style == OutputStyle.PRETTY);
	writer.start();
	compose(writer, resource, htmlPretty);
	writer.end();
}
 
Example #12
Source File: QuestionnaireResponseRepository.java    From careconnect-reference-implementation with Apache License 2.0 5 votes vote down vote up
public List<Resource> searchQuestionnaireResponse(FhirContext ctx,

                                                      @OptionalParam(name = QuestionnaireResponse.SP_IDENTIFIER) TokenParam identifier,
                                                      @OptionalParam(name= QuestionnaireResponse.SP_RES_ID) StringParam id,
                                                      @OptionalParam(name= QuestionnaireResponse.SP_QUESTIONNAIRE) ReferenceParam questionnaire,
                                                      @OptionalParam(name = QuestionnaireResponse.SP_PATIENT) ReferenceParam patient,
                                                      @IncludeParam(allow= {"*"}) Set<Include> includes

    );
 
Example #13
Source File: PersonProvider.java    From careconnect-reference-implementation with Apache License 2.0 5 votes vote down vote up
@Search
public List<Resource> searchPerson(HttpServletRequest theRequest,
                                   @OptionalParam(name= Person.SP_NAME) StringParam name,
                                   @OptionalParam(name = Person.SP_IDENTIFIER) TokenParam identifier,
                                   @OptionalParam(name = Person.SP_EMAIL) TokenParam email,
                                   @OptionalParam(name = Person.SP_PHONE) TokenParam phone
 ) {
    return personDao.search(ctx,name, identifier, email, phone);
}
 
Example #14
Source File: TaskProvider.java    From careconnect-reference-implementation with Apache License 2.0 5 votes vote down vote up
@Search
public List<Resource> search(HttpServletRequest theRequest,
                             @OptionalParam(name = Task.SP_PATIENT) ReferenceParam patient
        , @OptionalParam(name = Task.SP_IDENTIFIER) TokenParam identifier
        , @OptionalParam(name = Task.SP_RES_ID) StringParam id
        , @OptionalParam(name = Task.SP_OWNER) ReferenceParam owner
        , @OptionalParam(name = Task.SP_REQUESTER) ReferenceParam requester
        , @OptionalParam(name = Task.SP_STATUS) TokenParam status
        , @OptionalParam(name = Task.SP_CODE) TokenParam code
) {
    return taskDao.search(ctx,patient, identifier,id, owner, requester,status, code);
}
 
Example #15
Source File: XmlParserBase.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
/**
 * Compose a resource to a stream, possibly using pretty presentation for a human reader (used in the spec, for example, but not normally in production)
 * @ 
 */
@Override
public void compose(OutputStream stream, Resource resource)  throws IOException {
	XMLWriter writer = new XMLWriter(stream, "UTF-8");
	writer.setPretty(style == OutputStyle.PRETTY);
	writer.start();
	compose(writer, resource, writer.isPretty());
	writer.end();
}
 
Example #16
Source File: QuestionnaireResponseProvider.java    From careconnect-reference-implementation with Apache License 2.0 5 votes vote down vote up
@Search
public List<Resource> searchQuestionnaire(HttpServletRequest theRequest,
                                          @OptionalParam(name = QuestionnaireResponse.SP_IDENTIFIER) TokenParam identifier,
                                          @OptionalParam(name = QuestionnaireResponse.SP_RES_ID) StringParam id,
                                          @OptionalParam(name = QuestionnaireResponse.SP_QUESTIONNAIRE) ReferenceParam questionnaire,
                                          @OptionalParam(name = QuestionnaireResponse.SP_PATIENT) ReferenceParam patient,
                                          @IncludeParam(allow = {"*"}) Set<Include> includes
) {
    return formDao.searchQuestionnaireResponse(ctx, identifier, id, questionnaire, patient, includes);
}
 
Example #17
Source File: SnapShotGenerationTests.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private StructureDefinition findContainedProfile(String url, SnapShotGenerationTestsContext context) throws DefinitionException, FHIRException {
  for (Resource r : context.tests.getContained()) {
    if (r instanceof StructureDefinition) {
      StructureDefinition sd = (StructureDefinition) r;
      if (sd.getUrl().equals(url)) {
        StructureDefinition p = sd.copy();
        ProfileUtilities pu = new ProfileUtilities(TestingUtilities.context, null, null);
        pu.setIds(p, false);
        pu.generateSnapshot(getSD(p.getBaseDefinition(), context), p, p.getUrl(), p.getName());
        return p;
      }
    }
  }
  return null;
}
 
Example #18
Source File: SnapShotGenerationTests.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
public Resource fetchFixture(String id) {
  if (fixtures.containsKey(id))
    return fixtures.get(id);

  for (TestScriptFixtureComponent ds : tests.getFixture()) {
    if (id.equals(ds.getId()))
      throw new Error("not done yet");
  }
  for (Resource r : tests.getContained()) {
    if (id.equals(r.getId()))
      return r;
  }
  return null;
}
 
Example #19
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 #20
Source File: ToolsHelper.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
public void executeCanonicalXml(String[] args) throws FHIRException, IOException {
	FileInputStream in;
	File source = new CSFile(args[1]);
	File dest = new CSFile(args[2]);

	if (!source.exists())        
		throw new FHIRException("Source File \""+source.getAbsolutePath()+"\" not found");
	in = new CSFileInputStream(source);
	XmlParser p = new XmlParser();
	Resource rf = p.parse(in);
	XmlParser cxml = new XmlParser();
	cxml.setOutputStyle(OutputStyle.NORMAL);
	cxml.compose(new FileOutputStream(dest), rf);
}
 
Example #21
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 #22
Source File: SnapShotGenerationTests.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private void resolveFixtures(SnapShotGenerationTestsContext context) {
  if (context.fixtures == null) {
    context.fixtures = new HashMap<>();
    for (TestScriptFixtureComponent fd : context.tests.getFixture()) {
      Resource r = TestingUtilities.context.fetchResource(Resource.class, fd.getResource().getReference());
      context.fixtures.put(fd.getId(), r);
    }
  }
}
 
Example #23
Source File: ClaimRepository.java    From careconnect-reference-implementation with Apache License 2.0 5 votes vote down vote up
List<Resource> search(
        FhirContext ctx,
        @OptionalParam(name = Claim.SP_PATIENT) ReferenceParam patient
        , @OptionalParam(name = Claim.SP_IDENTIFIER) TokenParam identifier
        , @OptionalParam(name = Claim.SP_RES_ID) StringParam id
        , @OptionalParam(name = Claim.SP_USE) TokenParam use
        , @OptionalParam(name = "status") TokenParam status
);
 
Example #24
Source File: ClientUtils.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
/**
 * @param resourceFormat
 * @param options
 * @return
 */
protected <T extends Resource> ResourceRequest<T> issueResourceRequest(String resourceFormat, HttpUriRequest request, byte[] payload, List<Header> headers) {
  configureFhirRequest(request, resourceFormat, headers);
  HttpResponse response = null;
  if(request instanceof HttpEntityEnclosingRequest && payload != null) {
    response = sendPayload((HttpEntityEnclosingRequestBase)request, payload, proxy);
  } else if (request instanceof HttpEntityEnclosingRequest && payload == null){
    throw new EFhirClientException("PUT and POST requests require a non-null payload");
  } else {
    response = sendRequest(request);
  }
  T resource = unmarshalReference(response, resourceFormat);
  return new ResourceRequest<T>(resource, response.getStatusLine().getStatusCode(), getLocationHeader(response));
}
 
Example #25
Source File: Unbundler.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private static void unbundle(String src) throws FHIRFormatError, FileNotFoundException, IOException {
  String folder = Utilities.getDirectoryForFile(src);
  Bundle bnd = (Bundle) new JsonParser().parse(new FileInputStream(src));
  for (BundleEntryComponent be : bnd.getEntry()) {
    Resource r = be.getResource();
    if (r != null) {
      String tgt = Utilities.path(folder, r.fhirType()+"-"+r.getId()+".json");
      new JsonParser().compose(new FileOutputStream(tgt), r);
    }
  }
}
 
Example #26
Source File: FHIRToolingClient.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
public <T extends Resource> T read(Class<T> resourceClass, String id) {//TODO Change this to AddressableResource
	ResourceRequest<T> result = null;
	try {
		result = utils.issueGetResourceRequest(resourceAddress.resolveGetUriFromResourceClassAndId(resourceClass, id), getPreferredResourceFormat());
		result.addErrorStatus(410);//gone
		result.addErrorStatus(404);//unknown
		result.addSuccessStatus(200);//Only one for now
		if(result.isUnsuccessfulRequest()) {
			throw new EFhirClientException("Server returned error code " + result.getHttpStatus(), (OperationOutcome)result.getPayload());
		}
	} catch (Exception e) {
		handleException("An error has occurred while trying to read this resource", e);
	}
	return result.getPayload();
}
 
Example #27
Source File: SnapShotGenerationTests.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private boolean hasSource(String sourceId) {
  for (TestScriptFixtureComponent ds : tests.getFixture()) {
    if (sourceId.equals(ds.getId()))
      return true;
  }
  for (Resource r : tests.getContained()) {
    if (sourceId.equals(r.getId()))
      return true;
  }
  return false;
}
 
Example #28
Source File: ResourceAddress.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
public <T extends Resource> String nameForClass(Class<T> resourceClass) {
  if (resourceClass == null)
    return null;
	String res = resourceClass.getSimpleName();
	if (res.equals("List_"))
		return "List";
	else
		return res;
}
 
Example #29
Source File: FHIRToolingClient.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
public Parameters lookupCode(Map<String, String> params) {
  ResourceRequest<Resource> result = utils.issueGetResourceRequest(resourceAddress.resolveOperationUri(CodeSystem.class, "lookup", params), getPreferredResourceFormat());
  result.addErrorStatus(410);//gone
  result.addErrorStatus(404);//unknown
  result.addErrorStatus(405);
  result.addErrorStatus(422);//Unprocessable Entity
  result.addSuccessStatus(200);
  result.addSuccessStatus(201);
  if(result.isUnsuccessfulRequest()) {
    throw new EFhirClientException("Server returned error code " + result.getHttpStatus(), (OperationOutcome)result.getPayload());
  }
  return (Parameters) result.getPayload();
}
 
Example #30
Source File: ObservationRepository.java    From careconnect-reference-implementation with Apache License 2.0 5 votes vote down vote up
List<Resource> search (FhirContext ctx,
               @OptionalParam(name= Observation.SP_CATEGORY) TokenParam category,
               @OptionalParam(name= Observation.SP_CODE) TokenOrListParam codes,
               @OptionalParam(name= Observation.SP_DATE) DateRangeParam effectiveDate,
               @OptionalParam(name = Observation.SP_PATIENT) ReferenceParam patient
, @OptionalParam(name = Observation.SP_IDENTIFIER) TokenParam identifier
, @OptionalParam(name= Observation.SP_RES_ID) StringParam id
, @OptionalParam(name = Observation.SP_SUBJECT) ReferenceParam subject

, @IncludeParam(allow = { "Observation.related" ,  "*" }) Set<Include> includes
);