Codota Logo
IParser.parseResource
Code IndexAdd Codota to your IDE (free)

How to use
parseResource
method
in
ca.uhn.fhir.parser.IParser

Best Java code snippets using ca.uhn.fhir.parser.IParser.parseResource (Showing top 20 results out of 315)

  • Common ways to obtain IParser
private void myMethod () {
IParser i =
  • Codota IconFhirContext fhirContext;fhirContext.newJsonParser()
  • Codota IconFhirContext fhirContext;fhirContext.newXmlParser()
  • Smart code suggestions by Codota
}
origin: jamesagnew/hapi-fhir

public IBaseResource getPayload(FhirContext theCtx) {
  IBaseResource retVal = myPayload;
  if (retVal == null && isNotBlank(myPayloadString)) {
    retVal = theCtx.newJsonParser().parseResource(myPayloadString);
    myPayload = retVal;
  }
  return retVal;
}
origin: jamesagnew/hapi-fhir

public IBaseResource getNewPayload(FhirContext theCtx) {
  if (myPayloadDecoded == null && isNotBlank(myPayload)) {
    myPayloadDecoded = theCtx.newJsonParser().parseResource(myPayload);
  }
  return myPayloadDecoded;
}
origin: jamesagnew/hapi-fhir

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;
}
origin: jamesagnew/hapi-fhir

/**
 * 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));
}
origin: jamesagnew/hapi-fhir

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);
}
origin: jamesagnew/hapi-fhir

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;
}
origin: jamesagnew/hapi-fhir

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());
  
  
}
origin: jamesagnew/hapi-fhir

/**
 * 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));
}
origin: jamesagnew/hapi-fhir

  @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;
  }
}
origin: jamesagnew/hapi-fhir

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);
  }
}
origin: jamesagnew/hapi-fhir

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);
  }
}
origin: jamesagnew/hapi-fhir

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);
 }
}
origin: jamesagnew/hapi-fhir

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
}
origin: jamesagnew/hapi-fhir

@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);
  }
}
origin: jamesagnew/hapi-fhir

@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);
  }
}
origin: jamesagnew/hapi-fhir

@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);
}
origin: jamesagnew/hapi-fhir

@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;
}
origin: jamesagnew/hapi-fhir

@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;
}
origin: jamesagnew/hapi-fhir

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;
}
origin: jamesagnew/hapi-fhir

@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);
}
ca.uhn.fhir.parserIParserparseResource

Javadoc

Parses a resource

Popular methods of IParser

  • encodeResourceToString
  • setPrettyPrint
    Sets the "pretty print" flag, meaning that the parser will encode resources with human-readable spac
  • setParserErrorHandler
    Registers an error handler which will be invoked when any parse errors are found
  • encodeResourceToWriter
  • setDontEncodeElements
    If provided, specifies the elements which should NOT be encoded. Valid values for this field would i
  • setPreferTypes
    If set, when parsing resources the parser will try to use the given types when possible, in the orde
  • setServerBaseUrl
    Sets the server's base URL used by this parser. If a value is set, resource references will be turne
  • getEncoding
    Which encoding does this parser instance produce?
  • setDontStripVersionsFromReferencesAtPaths
    If supplied value(s), any resource references at the specified paths will have their resource versio
  • setEncodeElements
    If provided, specifies the elements which should be encoded, to the exclusion of all others. Valid v
  • setEncodeElementsAppliesToChildResourcesOnly
    If set to true (default is false), the values supplied to #setEncodeElements(Set) will not be applie
  • setEncodeElementsAppliesToResourceTypes
  • setEncodeElementsAppliesToChildResourcesOnly,
  • setEncodeElementsAppliesToResourceTypes,
  • setEncodeForceResourceId,
  • setOmitResourceId,
  • setStripVersionsFromReferences,
  • setSummaryMode,
  • setOverrideResourceIdWithBundleEntryFullUrl,
  • setSuppressNarratives

Popular in Java

  • Parsing JSON documents to java classes using gson
  • getSupportFragmentManager (FragmentActivity)
  • compareTo (BigDecimal)
    Compares this BigDecimal with the specified BigDecimal. Two BigDecimal objects that are equal in val
  • getOriginalFilename (MultipartFile)
    Return the original filename in the client's filesystem.This may contain path information depending
  • Graphics2D (java.awt)
    This Graphics2D class extends the Graphics class to provide more sophisticated control overgraphics
  • BufferedWriter (java.io)
    Wraps an existing Writer and buffers the output. Expensive interaction with the underlying reader is
  • UnknownHostException (java.net)
    Thrown when a hostname can not be resolved.
  • Date (java.util)
    A specific moment in time, with millisecond precision. Values typically come from System#currentTime
  • XPath (javax.xml.xpath)
    XPath provides access to the XPath evaluation environment and expressions. Evaluation of XPath Expr
  • StringUtils (org.apache.commons.lang)
    Operations on java.lang.String that arenull safe. * IsEmpty/IsBlank - checks if a String contains
Codota Logo
  • Products

    Search for Java codeSearch for JavaScript codeEnterprise
  • IDE Plugins

    IntelliJ IDEAWebStormAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimAtomGoLandRubyMineEmacsJupyter
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogCodota Academy Plugin user guide Terms of usePrivacy policyJava Code IndexJavascript Code Index
Get Codota for your IDE now