001package org.hl7.fhir.dstu3.hapi.fluentpath;
002
003import ca.uhn.fhir.context.FhirContext;
004import ca.uhn.fhir.fluentpath.FluentPathExecutionException;
005import ca.uhn.fhir.fluentpath.IFluentPath;
006import org.hl7.fhir.dstu3.hapi.ctx.HapiWorkerContext;
007import org.hl7.fhir.dstu3.hapi.ctx.IValidationSupport;
008import org.hl7.fhir.dstu3.model.Base;
009import org.hl7.fhir.dstu3.utils.FHIRPathEngine;
010import org.hl7.fhir.exceptions.FHIRException;
011import org.hl7.fhir.instance.model.api.IBase;
012
013import java.util.List;
014
015public class FluentPathDstu3 implements IFluentPath {
016
017        private FHIRPathEngine myEngine;
018
019        public FluentPathDstu3(FhirContext theCtx) {
020                if (!(theCtx.getValidationSupport() instanceof IValidationSupport)) {
021                        throw new IllegalStateException("Validation support module configured on context appears to be for the wrong FHIR version- Does not extend " + IValidationSupport.class.getName());
022                }
023                IValidationSupport validationSupport = (IValidationSupport) theCtx.getValidationSupport();
024                myEngine = new FHIRPathEngine(new HapiWorkerContext(theCtx, validationSupport));
025        }
026
027        @SuppressWarnings("unchecked")
028        @Override
029        public <T extends IBase> List<T> evaluate(IBase theInput, String thePath, Class<T> theReturnType) {
030                List<Base> result;
031                try {
032                        result = myEngine.evaluate((Base)theInput, thePath);
033                } catch (FHIRException e) {
034                        throw new FluentPathExecutionException(e);
035                }
036
037                for (Base next : result) {
038                        if (!theReturnType.isAssignableFrom(next.getClass())) {
039                                throw new FluentPathExecutionException("FluentPath expression \"" + thePath + "\" returned unexpected type " + next.getClass().getSimpleName() + " - Expected " + theReturnType.getName());
040                        }
041                }
042                
043                return (List<T>) result;
044        }
045
046}