public IBaseResource getPayload(FhirContext theCtx) { IBaseResource retVal = myPayload; if (retVal == null && isNotBlank(myPayloadString)) { retVal = theCtx.newJsonParser().parseResource(myPayloadString); myPayload = retVal; } return retVal; }
public IBaseResource getNewPayload(FhirContext theCtx) { if (myPayloadDecoded == null && isNotBlank(myPayload)) { myPayloadDecoded = theCtx.newJsonParser().parseResource(myPayload); } return myPayloadDecoded; }
public static <T extends IBaseResource> T apply(FhirContext theCtx, T theResourceToUpdate, String thePatchBody) { @SuppressWarnings("unchecked") Class<T> clazz = (Class<T>) theResourceToUpdate.getClass(); String inputResource = theCtx.newXmlParser().encodeResourceToString(theResourceToUpdate); ByteArrayOutputStream result = new ByteArrayOutputStream(); try { Patcher.patch(new ByteArrayInputStream(inputResource.getBytes(Constants.CHARSET_UTF8)), new ByteArrayInputStream(thePatchBody.getBytes(Constants.CHARSET_UTF8)), result); } catch (IOException e) { throw new InternalErrorException(e); } String resultString = new String(result.toByteArray(), Constants.CHARSET_UTF8); T retVal = theCtx.newXmlParser().parseResource(clazz, resultString); return retVal; }
/** * This method is called for nested bundles (e.g. if we received a transaction with an entry that * was a GET search, this method is called on the bundle for the search result, that will be placed in the * outer bundle). This method applies the _summary and _content parameters to the output of * that bundle. * <p> * TODO: This isn't the most efficient way of doing this.. hopefully we can come up with something better in the future. */ private IBaseResource filterNestedBundle(RequestDetails theRequestDetails, IBaseResource theResource) { IParser p = myContext.newJsonParser(); RestfulServerUtils.configureResponseParser(theRequestDetails, p); return p.parseResource(theResource.getClass(), p.encodeResourceToString(theResource)); }
protected IBaseResource parseResourceBody(String theResourceBody) { EncodingEnum encoding = EncodingEnum.detectEncodingNoDefault(theResourceBody); if (encoding == null) { throw new IllegalArgumentException(myContext.getLocalizer().getMessage(GenericClient.class, "cantDetermineRequestType")); } return encoding.newParser(myContext).parseResource(theResourceBody); }
private org.hl7.fhir.instance.model.Resource toDstu2(IBaseResource theResponseResource) { if (theResponseResource instanceof IResource) { return (org.hl7.fhir.instance.model.Resource) myCtxDstu2Hl7Org.newJsonParser().parseResource(myCtxDstu2.newJsonParser().encodeResourceToString(theResponseResource)); } return (org.hl7.fhir.instance.model.Resource) theResponseResource; }
public static void main(String[] args) throws Exception { FhirContext ctx = FhirContext.forDstu2(); String fileName = "src/main/resources/vs/dstu2/all-valuesets-bundle.xml"; FileReader fr = new FileReader(fileName); Bundle b = ctx.newXmlParser().parseResource(Bundle.class, fr); for (Entry nextEntry : b.getEntry()) { BaseResource nextRes = (BaseResource) nextEntry.getResource(); nextRes.setText(new NarrativeDt()); } File f = new File(fileName); OutputStreamWriter fw = new OutputStreamWriter(new FileOutputStream(f, false), "UTF-8"); ctx.newXmlParser().encodeResourceToWriter(b, fw); fw.close(); ourLog.info("Fixed {} valuesets", b.getEntry().size()); }
/** * This method is called for nested bundles (e.g. if we received a transaction with an entry that * was a GET search, this method is called on the bundle for the search result, that will be placed in the * outer bundle). This method applies the _summary and _content parameters to the output of * that bundle. * <p> * TODO: This isn't the most efficient way of doing this.. hopefully we can come up with something better in the future. */ private IBaseResource filterNestedBundle(RequestDetails theRequestDetails, IBaseResource theResource) { IParser p = getContext().newJsonParser(); RestfulServerUtils.configureResponseParser(theRequestDetails, p); return p.parseResource(theResource.getClass(), p.encodeResourceToString(theResource)); }
@Override public IBaseOperationOutcome invokeClient(String theResponseMimeType, InputStream theResponseInputStream, int theResponseStatusCode, Map<String, List<String>> theHeaders) throws BaseServerResponseException { EncodingEnum respType = EncodingEnum.forContentType(theResponseMimeType); if (respType == null) { return null; } IParser parser = respType.newParser(myContext); IBaseOperationOutcome retVal; try { // TODO: handle if something else than OO comes back retVal = (IBaseOperationOutcome) parser.parseResource(theResponseInputStream); } catch (DataFormatException e) { ourLog.warn("Failed to parse OperationOutcome response", e); return null; } MethodUtil.parseClientRequestResourceHeaders(null, theHeaders, retVal); return retVal; } }
private void loadStructureDefinitions(FhirContext theContext, Map<String, StructureDefinition> theCodeSystems, String theClasspath) { ourLog.info("Loading structure definitions from classpath: {}", theClasspath); InputStream valuesetText = DefaultProfileValidationSupport.class.getResourceAsStream(theClasspath); if (valuesetText != null) { InputStreamReader reader = new InputStreamReader(valuesetText, Charsets.UTF_8); Bundle bundle = theContext.newXmlParser().parseResource(Bundle.class, reader); for (BundleEntryComponent next : bundle.getEntry()) { if (next.getResource() instanceof StructureDefinition) { StructureDefinition nextSd = (StructureDefinition) next.getResource(); nextSd.getText().setDivAsString(""); String system = nextSd.getUrl(); if (isNotBlank(system)) { theCodeSystems.put(system, nextSd); } } } } else { ourLog.warn("Unable to load resource: {}", theClasspath); } }
private void loadStructureDefinitions(FhirContext theContext, Map<String, StructureDefinition> theCodeSystems, String theClasspath) { ourLog.info("Loading structure definitions from classpath: {}", theClasspath); InputStream valuesetText = DefaultProfileValidationSupport.class.getResourceAsStream(theClasspath); if (valuesetText != null) { InputStreamReader reader = new InputStreamReader(valuesetText, Charsets.UTF_8); Bundle bundle = theContext.newXmlParser().parseResource(Bundle.class, reader); for (BundleEntryComponent next : bundle.getEntry()) { if (next.getResource() instanceof StructureDefinition) { StructureDefinition nextSd = (StructureDefinition) next.getResource(); nextSd.getText().setDivAsString(""); String system = nextSd.getUrl(); if (isNotBlank(system)) { theCodeSystems.put(system, nextSd); } } } } else { ourLog.warn("Unable to load resource: {}", theClasspath); } }
private void loadStructureDefinitions(FhirContext theContext, Map<String, StructureDefinition> theCodeSystems, String theClasspath) { ourLog.info("Loading structure definitions from classpath: {}", theClasspath); InputStream valuesetText = DefaultProfileValidationSupport.class.getResourceAsStream(theClasspath); if (valuesetText != null) { InputStreamReader reader = new InputStreamReader(valuesetText, Constants.CHARSET_UTF8); Bundle bundle = theContext.newXmlParser().parseResource(Bundle.class, reader); for (BundleEntryComponent next : bundle.getEntry()) { if (next.getResource() instanceof StructureDefinition) { StructureDefinition nextSd = (StructureDefinition) next.getResource(); nextSd.getText().setDivAsString(""); String system = nextSd.getUrl(); if (isNotBlank(system)) { theCodeSystems.put(system, nextSd); } } } } else { ourLog.warn("Unable to load resource: {}", theClasspath); } }
public void parserValidation() { // START SNIPPET: parserValidation FhirContext ctx = FhirContext.forDstu3(); // Create a parser and configure it to use the strict error handler IParser parser = ctx.newXmlParser(); parser.setParserErrorHandler(new StrictErrorHandler()); // This example resource is invalid, as Patient.active can not repeat String input = "<Patient><active value=\"true\"/><active value=\"false\"/></Patient>"; // The following will throw a DataFormatException because of the StrictErrorHandler parser.parseResource(Patient.class, input); // END SNIPPET: parserValidation }
@Override public <T extends IBaseResource> T load(Class<T> theType, IIdType theId) throws ResourceNotFoundException { /* * The QuestionnaireResponse validator uses RI structures, so for now we need to convert between that and HAPI * structures. This is a bit hackish, but hopefully it will go away at some point. */ if ("ValueSet".equals(theType.getSimpleName())) { IFhirResourceDao<ValueSet> dao = getDao(ValueSet.class); ValueSet in = dao.read(theId, null); String encoded = getContext().newJsonParser().encodeResourceToString(in); // TODO: this is temporary until structures-dstu2 catches up to structures-hl7org.dstu2 encoded = encoded.replace("\"define\"", "\"codeSystem\""); return myRefImplCtx.newJsonParser().parseResource(theType, encoded); } else if ("Questionnaire".equals(theType.getSimpleName())) { IFhirResourceDao<Questionnaire> dao = getDao(Questionnaire.class); Questionnaire vs = dao.read(theId, null); return myRefImplCtx.newJsonParser().parseResource(theType, getContext().newJsonParser().encodeResourceToString(vs)); } else { // Should not happen, validator will only ask for these two throw new IllegalStateException("Unexpected request to load resource of type " + theType); } }
@Override public Object translateQueryParametersIntoServerArgument(RequestDetails theRequest, BaseMethodBinding<?> theMethodBinding) throws InternalErrorException, InvalidRequestException { // TODO: don't use a default encoding, just fail! EncodingEnum encoding = RestfulServerUtils.determineRequestEncoding(theRequest); IParser parser = encoding.newParser(theRequest.getServer().getFhirContext()); Reader reader = ResourceParameter.createRequestReader(theRequest); try { switch (myParamStyle) { case RESOURCE_LIST: { Class<? extends IBaseResource> type = myContext.getResourceDefinition("Bundle").getImplementingClass(); IBaseResource bundle = parser.parseResource(type, reader); List<IBaseResource> resourceList = BundleUtil.toListOfResources(myContext, (IBaseBundle) bundle); return resourceList; } case RESOURCE_BUNDLE: return parser.parseResource(myResourceBundleType, reader); } throw new IllegalStateException("Unknown type: " + myParamStyle); // should not happen } finally { IOUtils.closeQuietly(reader); } }
@Override protected List<ValidationMessage> validate(IValidationContext<?> theCtx) { Object resource = theCtx.getResource(); if (!(theCtx.getResource() instanceof IBaseResource)) { ourLog.debug("Not validating object of type {}", theCtx.getResource().getClass()); return Collections.emptyList(); } if (resource instanceof QuestionnaireResponse) { return doValidate(theCtx, (QuestionnaireResponse) resource); } RuntimeResourceDefinition def = theCtx.getFhirContext().getResourceDefinition((IBaseResource) resource); if ("QuestionnaireResponse".equals(def.getName()) == false) { return Collections.emptyList(); } /* * If we have a non-RI structure, convert it */ IParser p = theCtx.getFhirContext().newJsonParser(); String string = p.encodeResourceToString((IBaseResource) resource); QuestionnaireResponse qa = p.parseResource(QuestionnaireResponse.class, string); return doValidate(theCtx, qa); }
@Override public T invokeClient(String theResponseMimeType, InputStream theResponseInputStream, int theResponseStatusCode, Map<String, List<String>> theHeaders) throws BaseServerResponseException { EncodingEnum respType = EncodingEnum.forContentType(theResponseMimeType); if (respType == null) { if (myAllowHtmlResponse && theResponseMimeType.toLowerCase().contains(Constants.CT_HTML) && myReturnType != null) { return readHtmlResponse(theResponseInputStream); } throw NonFhirResponseException.newInstance(theResponseStatusCode, theResponseMimeType, theResponseInputStream); } IParser parser = respType.newParser(getFhirContext()); parser.setServerBaseUrl(getUrlBase()); if (myPreferResponseTypes != null) { parser.setPreferTypes(myPreferResponseTypes); } T retVal = parser.parseResource(myReturnType, theResponseInputStream); MethodUtil.parseClientRequestResourceHeaders(myId, theHeaders, retVal); return retVal; }
@Override public IBaseResource getResource() { if (myParsed == null) { IParser parser = getResourceAsStringEncoding().newParser(getFhirContext()); LenientErrorHandler errorHandler = new LenientErrorHandler(); errorHandler.setErrorOnInvalidValue(false); parser.setParserErrorHandler(errorHandler); myParsed = parser.parseResource(getResourceAsString()); } return myParsed; }
private ValueSet loadValueSetForExpansion(IIdType theId) { if (theId.getValue().startsWith("http://hl7.org/fhir/")) { org.hl7.fhir.instance.model.ValueSet valueSet = myValidationSupport.fetchResource(myRiCtx, org.hl7.fhir.instance.model.ValueSet.class, theId.getValue()); if (valueSet != null) { return getContext().newJsonParser().parseResource(ValueSet.class, myRiCtx.newJsonParser().encodeResourceToString(valueSet)); } } BaseHasResource sourceEntity = readEntity(theId); if (sourceEntity == null) { throw new ResourceNotFoundException(theId); } ValueSet source = (ValueSet) toResource(sourceEntity, false); return source; }
@Override public ValueSet expandByIdentifier(String theUri, String theFilter) { if (isBlank(theUri)) { throw new InvalidRequestException("URI must not be blank or missing"); } ValueSet source; org.hl7.fhir.instance.model.ValueSet defaultValueSet = myDefaultProfileValidationSupport.fetchResource(myRiCtx, org.hl7.fhir.instance.model.ValueSet.class, theUri); if (defaultValueSet != null) { source = getContext().newJsonParser().parseResource(ValueSet.class, myRiCtx.newJsonParser().encodeResourceToString(defaultValueSet)); } else { SearchParameterMap params = new SearchParameterMap(); params.setLoadSynchronousUpTo(1); params.add(ValueSet.SP_URL, new UriParam(theUri)); IBundleProvider ids = search(params); if (ids.size() == 0) { throw new InvalidRequestException("Unknown ValueSet URI: " + theUri); } source = (ValueSet) ids.getResources(0, 1).get(0); } return expand(source, theFilter); }