001package org.hl7.fhir.r5.hapi.fhirpath;
002
003import ca.uhn.fhir.i18n.Msg;
004import ca.uhn.fhir.context.FhirContext;
005import ca.uhn.fhir.context.support.IValidationSupport;
006import ca.uhn.fhir.fhirpath.FhirPathExecutionException;
007import ca.uhn.fhir.fhirpath.IFhirPath;
008import org.hl7.fhir.exceptions.FHIRException;
009import org.hl7.fhir.instance.model.api.IBase;
010import org.hl7.fhir.r5.hapi.ctx.HapiWorkerContext;
011import org.hl7.fhir.r5.model.Base;
012import org.hl7.fhir.r5.utils.FHIRPathEngine;
013
014import java.util.List;
015import java.util.Optional;
016
017public class FhirPathR5 implements IFhirPath {
018
019  private FHIRPathEngine myEngine;
020
021  public FhirPathR5(FhirContext theCtx) {
022          IValidationSupport validationSupport = theCtx.getValidationSupport();
023    myEngine = new FHIRPathEngine(new HapiWorkerContext(theCtx, validationSupport));
024  }
025
026  @SuppressWarnings("unchecked")
027  @Override
028  public <T extends IBase> List<T> evaluate(IBase theInput, String thePath, Class<T> theReturnType) {
029    List<Base> result;
030    try {
031      result = myEngine.evaluate((Base) theInput, thePath);
032    } catch (FHIRException e) {
033      throw new FhirPathExecutionException(Msg.code(198) + e);
034         }
035
036          for (Base next : result) {
037      if (!theReturnType.isAssignableFrom(next.getClass())) {
038        throw new FhirPathExecutionException(Msg.code(199) + "FluentPath expression \"" + thePath + "\" returned unexpected type " + next.getClass().getSimpleName() + " - Expected " + theReturnType.getName());
039      }
040    }
041
042    return (List<T>) result;
043  }
044
045  @Override
046  public <T extends IBase> Optional<T> evaluateFirst(IBase theInput, String thePath, Class<T> theReturnType) {
047    return evaluate(theInput, thePath, theReturnType).stream().findFirst();
048  }
049
050        @Override
051        public void parse(String theExpression) {
052                myEngine.parse(theExpression);
053        }
054
055
056}