package org.opencds.cqf.config;

import ca.uhn.fhir.jpa.rp.dstu3.LibraryResourceProvider;

import org.cqframework.cql.cql2elm.FhirLibrarySourceProvider;
import org.cqframework.cql.cql2elm.LibrarySourceProvider;
import org.hl7.elm.r1.VersionedIdentifier;
import org.hl7.fhir.dstu3.model.Attachment;
import org.hl7.fhir.dstu3.model.IdType;
import org.hl7.fhir.dstu3.model.Library;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * Created by Christopher on 1/12/2017.
 */
public class STU3LibrarySourceProvider implements LibrarySourceProvider {

    private LibraryResourceProvider provider;
    private FhirLibrarySourceProvider innerProvider;

    public STU3LibrarySourceProvider(LibraryResourceProvider provider) {
        this.provider = provider;
        this.innerProvider = new FhirLibrarySourceProvider();
    }

    @Override
    public InputStream getLibrarySource(VersionedIdentifier versionedIdentifier) {
        Library lib = provider.getDao().read(new IdType(versionedIdentifier.getId()));

        if (lib != null) {
            for (Attachment content : lib.getContent()) {
                if (content.getContentType().equals("text/cql")) {
                    return new ByteArrayInputStream(content.getData());
                }
            }
        }

        return this.innerProvider.getLibrarySource(versionedIdentifier);
    }
}
@@ -931,24 +931,42 @@
 entifier) %7B%0A
+        try %7B%0A    
         Libr
@@ -1043,36 +1043,8 @@
 )));
-%0A%0A        if (lib != null) %7B
 %0A   
@@ -1274,24 +1274,53 @@
  %7D%0A        %7D
+%0A        catch(Exception e)%7B%7D
 %0A%0A        re

Put exception eating back in