001package org.hl7.fhir.dstu3.hapi.fluentpath;
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.dstu3.hapi.ctx.HapiWorkerContext;
009import org.hl7.fhir.dstu3.model.Base;
010import org.hl7.fhir.dstu3.utils.FHIRPathEngine;
011import org.hl7.fhir.exceptions.FHIRException;
012import org.hl7.fhir.instance.model.api.IBase;
013
014import java.util.List;
015import java.util.Optional;
016
017public class FhirPathDstu3 implements IFhirPath {
018
019        private FHIRPathEngine myEngine;
020
021        public FhirPathDstu3(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(607) + e);
034                }
035
036                for (Base next : result) {
037                        if (!theReturnType.isAssignableFrom(next.getClass())) {
038                                throw new FhirPathExecutionException(Msg.code(608) + "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}