Search in sources :

Example 6 with DefaultConsole

use of com.beust.jcommander.internal.DefaultConsole in project quality-measure-and-cohort-service by Alvearie.

the class CohortCLI method runWithArgs.

/**
 * Simulate main method behavior in a non-static context for use in testing
 * tools. This method is intended to be called only once. Multiple calls for the
 * same library path will attempt duplicate library loading.
 *
 * @param args parameter values
 * @param out  location where contents that would normally go to stdout should
 *             be written
 * @return CQLEvaluator
 * @throws IOException IOException
 */
public CqlEvaluator runWithArgs(String[] args, PrintStream out) throws IOException {
    Arguments arguments = new Arguments();
    Console console = new DefaultConsole(out);
    JCommander jc = JCommander.newBuilder().programName("cql-engine").console(console).addObject(arguments).build();
    jc.parse(args);
    CqlEvaluator wrapper = null;
    if (arguments.isDisplayHelp) {
        jc.usage();
    } else {
        FhirClientBuilderFactory factory = FhirClientBuilderFactory.newInstance();
        FhirClientBuilder fhirClientBuilder = factory.newFhirClientBuilder();
        readConnectionConfiguration(arguments);
        MapCqlLibraryProviderFactory libraryProviderFactory = new MapCqlLibraryProviderFactory();
        String[] filters = null;
        if (arguments.filters != null) {
            filters = arguments.filters.toArray(new String[arguments.filters.size()]);
        }
        CqlLibraryProvider backingLibraryProvider;
        Path libraryFolder = Paths.get(arguments.libraryPath);
        if (libraryFolder.toFile().isDirectory()) {
            out.println(String.format("Loading libraries from folder '%s'", libraryFolder.toString()));
            backingLibraryProvider = libraryProviderFactory.fromDirectory(libraryFolder, filters);
        } else if (FileHelpers.isZip(libraryFolder.toFile())) {
            out.println(String.format("Loading libraries from ZIP '%s'", libraryFolder.toString()));
            backingLibraryProvider = libraryProviderFactory.fromZipFile(libraryFolder, filters);
        } else {
            out.println(String.format("Loading libraries from FHIR Library '%s'", libraryFolder.toString()));
            IGenericClient measureClient = fhirClientBuilder.createFhirClient(measureServerConfig);
            FhirResourceResolver<Library> libraryResolver = R4FhirServerResourceResolverFactory.createLibraryResolver(measureClient);
            R4LibraryDependencyGatherer dependencyGatherer = new R4LibraryDependencyGatherer(libraryResolver);
            List<Library> cqlLibraries = dependencyGatherer.gatherForLibraryId(arguments.libraryPath);
            Map<CqlLibraryDescriptor, CqlLibrary> cqlLibraryMap = toCqlLibraryMap(cqlLibraries);
            backingLibraryProvider = new MapCqlLibraryProvider(cqlLibraryMap);
        }
        CqlLibraryProvider fhirClasspathProvider = new ClasspathCqlLibraryProvider();
        backingLibraryProvider = new PriorityCqlLibraryProvider(backingLibraryProvider, fhirClasspathProvider);
        CqlToElmTranslator translator = new CqlToElmTranslator();
        if (arguments.modelInfoFile != null && arguments.modelInfoFile.exists()) {
            translator.registerModelInfo(arguments.modelInfoFile);
        }
        boolean isForceTranslation = arguments.sourceFormat == Format.CQL;
        CqlLibraryProvider libraryProvider = new TranslatingCqlLibraryProvider(backingLibraryProvider, translator, isForceTranslation);
        IGenericClient dataClient = fhirClientBuilder.createFhirClient(dataServerConfig);
        IGenericClient termClient = fhirClientBuilder.createFhirClient(terminologyServerConfig);
        CqlTerminologyProvider termProvider = new R4RestFhirTerminologyProvider(termClient);
        Map<String, com.ibm.cohort.cql.evaluation.parameters.Parameter> parameters = null;
        if (arguments.parameters != null) {
            parameters = parseParameterArguments(arguments.parameters);
        }
        CqlVersionedIdentifier libraryIdentifier = new CqlVersionedIdentifier(arguments.libraryName, arguments.libraryVersion);
        List<Pair<String, String>> contexts;
        if (arguments.contextIds == null || arguments.contextIds.isEmpty()) {
            // If no context ids are provided, perform one run using a null context
            contexts = Collections.singletonList(null);
        } else {
            contexts = arguments.contextIds.stream().map(x -> new ImmutablePair<>(arguments.contextName, x)).collect(Collectors.toList());
        }
        try (RetrieveCacheContext cacheContext = new DefaultRetrieveCacheContext()) {
            CqlDataProvider dataProvider = R4DataProviderFactory.createDataProvider(dataClient, termProvider, cacheContext, R4FhirModelResolverFactory.createCachingResolver(), !arguments.enableTerminologyOptimization, arguments.searchPageSize);
            wrapper = new CqlEvaluator().setLibraryProvider(libraryProvider).setDataProvider(dataProvider).setTerminologyProvider(termProvider);
            ZonedDateTime evaluationDateTime = ZonedDateTime.now();
            for (Pair<String, String> context : contexts) {
                String contextLabel = context == null ? "null" : context.getRight();
                out.println("Context: " + contextLabel);
                CqlEvaluationResult result = wrapper.evaluate(libraryIdentifier, parameters, context, arguments.expressions, arguments.loggingLevel, evaluationDateTime);
                out.print(prettyPrintResult(result));
                out.println("---");
            }
        }
    }
    return wrapper;
}
Also used : FhirResourceResolver(com.ibm.cohort.cql.fhir.resolver.FhirResourceResolver) DefaultConsole(com.beust.jcommander.internal.DefaultConsole) TranslatingCqlLibraryProvider(com.ibm.cohort.cql.translation.TranslatingCqlLibraryProvider) IGenericClient(ca.uhn.fhir.rest.client.api.IGenericClient) R4RestFhirTerminologyProvider(com.ibm.cohort.engine.terminology.R4RestFhirTerminologyProvider) DefaultRetrieveCacheContext(com.ibm.cohort.engine.measure.cache.DefaultRetrieveCacheContext) RetrieveCacheContext(com.ibm.cohort.engine.measure.cache.RetrieveCacheContext) CqlToElmTranslator(com.ibm.cohort.cql.translation.CqlToElmTranslator) MapCqlLibraryProvider(com.ibm.cohort.cql.library.MapCqlLibraryProvider) CqlLibraryProvider(com.ibm.cohort.cql.library.CqlLibraryProvider) PriorityCqlLibraryProvider(com.ibm.cohort.cql.library.PriorityCqlLibraryProvider) TranslatingCqlLibraryProvider(com.ibm.cohort.cql.translation.TranslatingCqlLibraryProvider) ClasspathCqlLibraryProvider(com.ibm.cohort.cql.library.ClasspathCqlLibraryProvider) ZonedDateTime(java.time.ZonedDateTime) JCommander(com.beust.jcommander.JCommander) Console(com.beust.jcommander.internal.Console) DefaultConsole(com.beust.jcommander.internal.DefaultConsole) R4LibraryDependencyGatherer(com.ibm.cohort.cql.hapi.R4LibraryDependencyGatherer) List(java.util.List) MapCqlLibraryProviderFactory(com.ibm.cohort.cql.library.MapCqlLibraryProviderFactory) CqlTerminologyProvider(com.ibm.cohort.cql.terminology.CqlTerminologyProvider) CqlDataProvider(com.ibm.cohort.cql.data.CqlDataProvider) Pair(org.apache.commons.lang3.tuple.Pair) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) Path(java.nio.file.Path) FhirClientBuilder(com.ibm.cohort.fhir.client.config.FhirClientBuilder) ParameterHelper.parseParameterArguments(com.ibm.cohort.cli.ParameterHelper.parseParameterArguments) MapCqlLibraryProvider(com.ibm.cohort.cql.library.MapCqlLibraryProvider) CqlEvaluationResult(com.ibm.cohort.cql.evaluation.CqlEvaluationResult) DefaultRetrieveCacheContext(com.ibm.cohort.engine.measure.cache.DefaultRetrieveCacheContext) PriorityCqlLibraryProvider(com.ibm.cohort.cql.library.PriorityCqlLibraryProvider) FhirClientBuilderFactory(com.ibm.cohort.fhir.client.config.FhirClientBuilderFactory) Parameter(com.beust.jcommander.Parameter) ClasspathCqlLibraryProvider(com.ibm.cohort.cql.library.ClasspathCqlLibraryProvider) Map(java.util.Map) HashMap(java.util.HashMap) CqlEvaluator(com.ibm.cohort.cql.evaluation.CqlEvaluator) CqlVersionedIdentifier(com.ibm.cohort.cql.library.CqlVersionedIdentifier)

Example 7 with DefaultConsole

use of com.beust.jcommander.internal.DefaultConsole in project quality-measure-and-cohort-service by Alvearie.

the class MeasureCLI method runWithArgs.

public MeasureEvaluator runWithArgs(String[] args, PrintStream out) throws IOException {
    MeasureEvaluator evaluator = null;
    Arguments arguments = new Arguments();
    Console console = new DefaultConsole(out);
    JCommander jc = JCommander.newBuilder().programName("measure-engine").console(console).addObject(arguments).build();
    jc.parse(args);
    if (arguments.isDisplayHelp) {
        jc.usage();
    } else {
        arguments.validate();
        readDataServerConfiguration(arguments);
        readTerminologyServerConfiguration(arguments);
        FhirClientBuilderFactory fhirClientBuilderFactory = getFhirClientBuilderFactory();
        IGenericClient dataServerClient = fhirClientBuilderFactory.newFhirClientBuilder().createFhirClient(dataServerConfig);
        IGenericClient terminologyServerClient = fhirClientBuilderFactory.newFhirClientBuilder().createFhirClient(terminologyServerConfig);
        String[] filters = (arguments.filters != null) ? arguments.filters.toArray(new String[arguments.filters.size()]) : null;
        IParser parser = getFhirContext().newJsonParser().setPrettyPrint(true);
        R4QualityMeasureResolverFactory resolverFactory = new R4QualityMeasureResolverFactory(parser);
        FhirResourceResolver<Library> libraryResolver;
        FhirResourceResolver<Measure> measureResolver;
        if (arguments.measureServerConfigFile != null && FileHelpers.isZip(arguments.measureServerConfigFile)) {
            R4QualityMeasureResolvers resolvers = resolverFactory.fromZipFile(arguments.measureServerConfigFile.toPath(), filters);
            libraryResolver = resolvers.getLibraryResolver();
            measureResolver = resolvers.getMeasureResolver();
        } else if (arguments.measureServerConfigFile != null && arguments.measureServerConfigFile.isDirectory()) {
            R4QualityMeasureResolvers resolvers = resolverFactory.fromDirectory(arguments.measureServerConfigFile.toPath(), filters);
            libraryResolver = resolvers.getLibraryResolver();
            measureResolver = resolvers.getMeasureResolver();
        } else {
            readMeasureServerConfiguration(arguments);
            IGenericClient measureServerClient = fhirClientBuilderFactory.newFhirClientBuilder().createFhirClient(measureServerConfig);
            libraryResolver = R4FhirServerResourceResolverFactory.createLibraryResolver(measureServerClient);
            measureResolver = R4FhirServerResourceResolverFactory.createMeasureResolver(measureServerClient);
        }
        List<MeasureContext> measureContexts;
        if (arguments.measureConfigurationFile != null) {
            measureContexts = MeasureContextProvider.getMeasureContexts(arguments.measureConfigurationFile);
        } else {
            measureContexts = MeasureContextProvider.getMeasureContexts(arguments.resourceId, arguments.parameters);
        }
        validateMeasureContexts(measureContexts);
        R4LibraryDependencyGatherer libraryDependencyGatherer = new R4LibraryDependencyGatherer(libraryResolver);
        CqlTerminologyProvider terminologyProvider = new R4RestFhirTerminologyProvider(terminologyServerClient);
        try (RetrieveCacheContext retrieveCacheContext = arguments.disableRetrieveCache ? null : new DefaultRetrieveCacheContext()) {
            Map<String, CqlDataProvider> dataProviders = R4DataProviderFactory.createDataProviderMap(dataServerClient, terminologyProvider, retrieveCacheContext, R4FhirModelResolverFactory.createCachingResolver(), !arguments.enableTerminologyOptimization, arguments.searchPageSize);
            evaluator = new MeasureEvaluator(measureResolver, libraryResolver, libraryDependencyGatherer, terminologyProvider, dataProviders);
            for (String contextId : arguments.contextIds) {
                out.println("Evaluating: " + contextId);
                // Reports only returned for measures where patient is in initial population
                List<MeasureReport> reports = evaluator.evaluatePatientMeasures(contextId, measureContexts, new MeasureEvidenceOptions(arguments.includeEvaluatedResources, arguments.defineReturnOption));
                for (MeasureReport report : reports) {
                    if (arguments.reportFormat == ReportFormat.TEXT) {
                        out.println("Result for " + report.getMeasure());
                        for (MeasureReport.MeasureReportGroupComponent group : report.getGroup()) {
                            for (MeasureReport.MeasureReportGroupPopulationComponent pop : group.getPopulation()) {
                                String popCode = pop.getCode().getCodingFirstRep().getCode();
                                if (pop.getId() != null) {
                                    popCode += "(" + pop.getId() + ")";
                                }
                                out.println(String.format("Population: %s = %d", popCode, pop.getCount()));
                            }
                        }
                    } else {
                        out.println(parser.encodeResourceToString(report));
                    }
                    out.println("---");
                }
                if (reports.isEmpty()) {
                    out.println("---");
                }
            }
        }
    }
    return evaluator;
}
Also used : DefaultConsole(com.beust.jcommander.internal.DefaultConsole) IGenericClient(ca.uhn.fhir.rest.client.api.IGenericClient) R4QualityMeasureResolverFactory(com.ibm.cohort.cql.hapi.resolver.R4QualityMeasureResolverFactory) R4RestFhirTerminologyProvider(com.ibm.cohort.engine.terminology.R4RestFhirTerminologyProvider) DefaultRetrieveCacheContext(com.ibm.cohort.engine.measure.cache.DefaultRetrieveCacheContext) RetrieveCacheContext(com.ibm.cohort.engine.measure.cache.RetrieveCacheContext) MeasureEvidenceOptions(com.ibm.cohort.engine.measure.evidence.MeasureEvidenceOptions) MeasureContext(com.ibm.cohort.engine.measure.MeasureContext) JCommander(com.beust.jcommander.JCommander) Console(com.beust.jcommander.internal.Console) DefaultConsole(com.beust.jcommander.internal.DefaultConsole) Measure(org.hl7.fhir.r4.model.Measure) R4LibraryDependencyGatherer(com.ibm.cohort.cql.hapi.R4LibraryDependencyGatherer) CqlTerminologyProvider(com.ibm.cohort.cql.terminology.CqlTerminologyProvider) CqlDataProvider(com.ibm.cohort.cql.data.CqlDataProvider) MeasureReport(org.hl7.fhir.r4.model.MeasureReport) MeasureEvaluator(com.ibm.cohort.engine.measure.MeasureEvaluator) DefaultRetrieveCacheContext(com.ibm.cohort.engine.measure.cache.DefaultRetrieveCacheContext) FhirClientBuilderFactory(com.ibm.cohort.fhir.client.config.FhirClientBuilderFactory) R4QualityMeasureResolvers(com.ibm.cohort.cql.hapi.resolver.R4QualityMeasureResolvers) Library(org.hl7.fhir.r4.model.Library) IParser(ca.uhn.fhir.parser.IParser)

Example 8 with DefaultConsole

use of com.beust.jcommander.internal.DefaultConsole in project quality-measure-and-cohort-service by Alvearie.

the class MeasureImporter method runWithArgs.

/**
 * Execute measure import process with given arguments. Console logging is
 * redirected to the provided stream.
 *
 * @param args Program arguments
 * @param out  Sink for console output
 * @return number of errors encountered during processing
 * @throws Exception on any error.
 */
public static int runWithArgs(String[] args, PrintStream out) throws Exception {
    int resultCode = 0;
    Arguments arguments = new Arguments();
    Console console = new DefaultConsole(out);
    JCommander jc = JCommander.newBuilder().programName("measure-importer").console(console).addObject(arguments).build();
    jc.parse(args);
    if (arguments.isDisplayHelp) {
        jc.usage();
        resultCode = 1;
    } else {
        FhirContext fhirContext = FhirContext.forR4();
        ObjectMapper om = new ObjectMapper();
        FhirServerConfig config = om.readValue(arguments.measureServerConfigFile, FhirServerConfig.class);
        IGenericClient client = FhirClientBuilderFactory.newInstance().newFhirClientBuilder(fhirContext).createFhirClient(config);
        MeasureImporter importer = new MeasureImporter(client);
        resultCode = importer.importFiles(arguments.artifactPaths, arguments.outputPath);
        if (resultCode == 0) {
            out.println("Process completed with no errors.");
        } else {
            out.println(String.format("Process completed with errors. Failed to process %d artifacts.", resultCode));
        }
    }
    return resultCode;
}
Also used : FhirContext(ca.uhn.fhir.context.FhirContext) DefaultConsole(com.beust.jcommander.internal.DefaultConsole) JCommander(com.beust.jcommander.JCommander) IGenericClient(ca.uhn.fhir.rest.client.api.IGenericClient) Console(com.beust.jcommander.internal.Console) DefaultConsole(com.beust.jcommander.internal.DefaultConsole) FhirServerConfig(com.ibm.cohort.fhir.client.config.FhirServerConfig) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 9 with DefaultConsole

use of com.beust.jcommander.internal.DefaultConsole in project quality-measure-and-cohort-service by Alvearie.

the class ValueSetImporter method runWithArgs.

void runWithArgs(String[] args, PrintStream out) throws IOException {
    ValueSetImporterArguments arguments = new ValueSetImporterArguments();
    Console console = new DefaultConsole(out);
    JCommander jc = JCommander.newBuilder().programName("value-set-importer").console(console).addObject(arguments).build();
    jc.parse(args);
    if (arguments.isDisplayHelp) {
        jc.usage();
    } else {
        arguments.validate();
        FhirContext fhirContext = FhirContext.forR4();
        // only connect to fhir server if we are not writing it to file system
        IGenericClient client = null;
        ObjectMapper om = new ObjectMapper();
        if (arguments.fileOutputLocation == OutputLocations.NONE) {
            FhirServerConfig config = om.readValue(arguments.measureServerConfigFile, FhirServerConfig.class);
            client = FhirClientBuilderFactory.newInstance().newFhirClientBuilder(fhirContext).createFhirClient(config);
        }
        Map<String, String> codeSystemMappings = null;
        if (arguments.filename != null) {
            codeSystemMappings = ValueSetUtil.getMapFromInputStream(new FileInputStream(new File(arguments.filename)));
        }
        for (String arg : arguments.spreadsheets) {
            try (InputStream is = new FileInputStream(arg)) {
                ValueSetArtifact artifact = ValueSetUtil.createArtifact(is, codeSystemMappings);
                // only import the value set to fhir server if we are not writing the value set to file system
                if (arguments.fileOutputLocation == OutputLocations.NONE) {
                    String retVal = ValueSetUtil.importArtifact(client, artifact, arguments.overrideValueSets);
                    if (retVal == null) {
                        logger.error("Value set already exists! Please provide the override option if you would like to override this value set.");
                    }
                } else {
                    // write value set to file system
                    ValueSet vs = artifact.getFhirResource();
                    // If the valueset id contains urn:oid, remove it to make a valid filename
                    String valueSetId = vs.getId().startsWith("urn:oid:") ? vs.getId().replace("urn:oid:", "") : vs.getId();
                    String vsFileName = valueSetId + "." + arguments.filesystemOutputFormat.toString().toLowerCase();
                    if (arguments.fileOutputLocation == OutputLocations.BOTH || arguments.fileOutputLocation == OutputLocations.S3) {
                        S3Configuration S3Config = om.readValue(arguments.S3JsonConfigs, S3Configuration.class);
                        AmazonS3 S3Client = createClient(S3Config.getAccess_key_id(), S3Config.getSecret_access_key(), S3Config.getEndpoint(), S3Config.getLocation());
                        putToS3(arguments, fhirContext, vs, vsFileName, S3Client);
                    }
                    if (arguments.fileOutputLocation == OutputLocations.BOTH || arguments.fileOutputLocation == OutputLocations.LOCAL) {
                        try (BufferedWriter writer = new BufferedWriter(new FileWriter(arguments.fileSystemOutputPath + System.getProperty("file.separator") + vsFileName))) {
                            // create the output dir if it doesn't exist
                            File outputDir = new File(arguments.fileSystemOutputPath);
                            if (!outputDir.exists()) {
                                outputDir.mkdir();
                            }
                            // write to xml or json format
                            if (arguments.filesystemOutputFormat == FileFormat.JSON) {
                                fhirContext.newJsonParser().encodeResourceToWriter(vs, writer);
                            } else if (arguments.filesystemOutputFormat == FileFormat.XML) {
                                fhirContext.newXmlParser().encodeResourceToWriter(vs, writer);
                            }
                        }
                    }
                }
            }
        }
    }
}
Also used : AmazonS3(com.amazonaws.services.s3.AmazonS3) FhirContext(ca.uhn.fhir.context.FhirContext) DefaultConsole(com.beust.jcommander.internal.DefaultConsole) IGenericClient(ca.uhn.fhir.rest.client.api.IGenericClient) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) FileWriter(java.io.FileWriter) ValueSetArtifact(com.ibm.cohort.valueset.ValueSetArtifact) FileInputStream(java.io.FileInputStream) BufferedWriter(java.io.BufferedWriter) S3Configuration(com.ibm.cohort.tooling.s3.S3Configuration) JCommander(com.beust.jcommander.JCommander) Console(com.beust.jcommander.internal.Console) DefaultConsole(com.beust.jcommander.internal.DefaultConsole) FhirServerConfig(com.ibm.cohort.fhir.client.config.FhirServerConfig) File(java.io.File) ValueSet(org.hl7.fhir.r4.model.ValueSet) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Aggregations

DefaultConsole (com.beust.jcommander.internal.DefaultConsole)9 JCommander (com.beust.jcommander.JCommander)5 IGenericClient (ca.uhn.fhir.rest.client.api.IGenericClient)4 Console (com.beust.jcommander.internal.Console)4 FhirContext (ca.uhn.fhir.context.FhirContext)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 CqlDataProvider (com.ibm.cohort.cql.data.CqlDataProvider)2 R4LibraryDependencyGatherer (com.ibm.cohort.cql.hapi.R4LibraryDependencyGatherer)2 CqlTerminologyProvider (com.ibm.cohort.cql.terminology.CqlTerminologyProvider)2 DefaultRetrieveCacheContext (com.ibm.cohort.engine.measure.cache.DefaultRetrieveCacheContext)2 RetrieveCacheContext (com.ibm.cohort.engine.measure.cache.RetrieveCacheContext)2 R4RestFhirTerminologyProvider (com.ibm.cohort.engine.terminology.R4RestFhirTerminologyProvider)2 FhirClientBuilderFactory (com.ibm.cohort.fhir.client.config.FhirClientBuilderFactory)2 FhirServerConfig (com.ibm.cohort.fhir.client.config.FhirServerConfig)2 PrintStream (java.io.PrintStream)2 IParser (ca.uhn.fhir.parser.IParser)1 AmazonS3 (com.amazonaws.services.s3.AmazonS3)1 DefaultUsageFormatter (com.beust.jcommander.DefaultUsageFormatter)1 Parameter (com.beust.jcommander.Parameter)1 JDK6Console (com.beust.jcommander.internal.JDK6Console)1