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