use of com.ibm.cohort.fhir.client.config.FhirClientBuilder in project quality-measure-and-cohort-service by Alvearie.
the class CohortEngineRestStatusHandler method getHealthCheckEnhanced.
@POST
@Path("health_check_enhanced")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@ApiOperation(value = "Get the status of the cohorting service and dependent downstream services", notes = CohortEngineRestStatusHandler.HEALTH_CHECK_ENHANCED_API_NOTES, response = EnhancedHealthCheckResults.class, nickname = "health_check_enhanced")
@ApiImplicitParams({ @ApiImplicitParam(name = CohortEngineRestStatusHandler.FHIR_SERVER_CONNECTION_CONFIG, value = CohortEngineRestStatusHandler.EXAMPLE_HEALTH_CHECK_DATA_SERVER_CONFIG_JSON, dataTypeClass = EnhancedHealthCheckInput.class, required = true, paramType = "form", type = "file") })
@ApiResponses(value = { @ApiResponse(code = 200, message = "Successful Operation", response = EnhancedHealthCheckResults.class), @ApiResponse(code = 400, message = "Bad Request", response = ServiceErrorList.class), @ApiResponse(code = 500, message = "Server Error", response = ServiceErrorList.class) })
public Response getHealthCheckEnhanced(@ApiParam(value = ServiceBaseConstants.MINOR_VERSION_DESCRIPTION, required = true, defaultValue = ServiceBuildConstants.DATE) @QueryParam(CohortEngineRestHandler.VERSION) String version, @ApiParam(hidden = true, type = "file", required = true) IMultipartBody multipartBody) {
final String methodName = CohortEngineRestStatusHandler.GET_HEALTH_CHECK_ENCHANCED;
Response response = null;
try {
// Perform api setup
Response errorResponse = ServiceBaseUtility.apiSetup(version, logger, methodName);
if (errorResponse != null) {
return errorResponse;
}
// initialize results object
EnhancedHealthCheckResults results = new EnhancedHealthCheckResults();
FhirServerConnectionStatusInfo dataServerConnectionResults = new FhirServerConnectionStatusInfo();
dataServerConnectionResults.setServerConfigType(FhirServerConfigType.dataServerConfig);
dataServerConnectionResults.setConnectionResults(FhirConnectionStatus.notAttempted);
FhirServerConnectionStatusInfo terminologyServerConnectionResults = new FhirServerConnectionStatusInfo();
terminologyServerConnectionResults.setServerConfigType(FhirServerConfigType.terminologyServerConfig);
terminologyServerConnectionResults.setConnectionResults(FhirConnectionStatus.notAttempted);
results.setDataServerConnectionResults(dataServerConnectionResults);
results.setTerminologyServerConnectionResults(terminologyServerConnectionResults);
IAttachment dataSourceAttachment = multipartBody.getAttachment(CohortEngineRestStatusHandler.FHIR_SERVER_CONNECTION_CONFIG);
if (dataSourceAttachment == null) {
throw new IllegalArgumentException(String.format("Missing '%s' MIME attachment", CohortEngineRestStatusHandler.FHIR_SERVER_CONNECTION_CONFIG));
}
// deserialize the request input
ObjectMapper om = new ObjectMapper();
EnhancedHealthCheckInput fhirServerConfigs = om.readValue(dataSourceAttachment.getDataHandler().getInputStream(), EnhancedHealthCheckInput.class);
FhirServerConfig dataServerConfig = fhirServerConfigs.getDataServerConfig();
FhirServerConfig terminologyServerConfig = fhirServerConfigs.getTerminologyServerConfig();
// validate the contents of the dataServerConfig
CohortEngineRestHandler.validateBean(dataServerConfig);
// validate the contents of the terminologyServerConfig
if (terminologyServerConfig != null) {
CohortEngineRestHandler.validateBean(terminologyServerConfig);
}
// get the fhir client object used to call to FHIR
FhirClientBuilder clientBuilder = FhirClientBuilderFactory.newInstance().newFhirClientBuilder();
IGenericClient dataClient = clientBuilder.createFhirClient(fhirServerConfigs.getDataServerConfig());
// try a simple patient search to validate the connection info
try {
// used count=0 to minimize response size
dataClient.search().forResource(Patient.class).count(0).execute();
dataServerConnectionResults.setConnectionResults(FhirConnectionStatus.success);
} catch (Throwable ex) {
dataServerConnectionResults.setConnectionResults(FhirConnectionStatus.failure);
dataServerConnectionResults.setServiceErrorList(new CohortServiceExceptionMapper().toServiceErrorList(ex));
}
// try a simple valueset search to validate the connection info
if (terminologyServerConfig != null) {
IGenericClient terminologyClient = clientBuilder.createFhirClient(fhirServerConfigs.getTerminologyServerConfig());
try {
// used count=0 to minimize response size
terminologyClient.search().forResource(ValueSet.class).count(0).execute();
terminologyServerConnectionResults.setConnectionResults(FhirConnectionStatus.success);
} catch (Throwable ex) {
terminologyServerConnectionResults.setConnectionResults(FhirConnectionStatus.failure);
terminologyServerConnectionResults.setServiceErrorList(new CohortServiceExceptionMapper().toServiceErrorList(ex));
}
}
// return the results
response = Response.ok(results).build();
} catch (Throwable e) {
// map any exceptions caught into the proper REST error response objects
return new CohortServiceExceptionMapper().toResponse(e);
} finally {
// Perform api cleanup
Response errorResponse = ServiceBaseUtility.apiCleanup(logger, methodName);
if (errorResponse != null) {
response = errorResponse;
}
}
return response;
}
use of com.ibm.cohort.fhir.client.config.FhirClientBuilder in project health-patterns by LinuxForHealth.
the class CohortService method initializeCQLEngine.
/**
* Initialized the CQL engine (using the instance's FHIR connection info) runnig over the {@value #CQL_DIRECTORY}.
*/
private void initializeCQLEngine() {
FhirClientBuilderFactory factory = FhirClientBuilderFactory.newInstance();
FhirContext fhirContext = FhirContext.forR4();
// Currently the socket connection may time out on a FHIR server
// with several dozen patients so increasing the timeout to avoid that
fhirContext.getRestfulClientFactory().setSocketTimeout(60 * 1000);
FhirClientBuilder fhirBuilder = factory.newFhirClientBuilder(fhirContext);
fhir = fhirBuilder.createFhirClient(fhirConnectionInfo);
System.out.println("Created FHIR connection to " + fhirConnectionInfo.getEndpoint());
cqlEngine = new CqlEngineWrapper(fhirBuilder);
cqlEngine.setDataServerClient(fhir);
cqlEngine.setMeasureServerClient(fhir);
cqlEngine.setTerminologyServerClient(fhir);
resetCQLDirectory();
}
use of com.ibm.cohort.fhir.client.config.FhirClientBuilder 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;
}
use of com.ibm.cohort.fhir.client.config.FhirClientBuilder in project quality-measure-and-cohort-service by Alvearie.
the class CohortEngineRestHandler method createValueSet.
@POST
@Path("/valueset/")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces({ MediaType.APPLICATION_JSON })
@ApiImplicitParams({ // This is necessary for the dark launch feature
@ApiImplicitParam(access = DarkFeatureSwaggerFilter.DARK_FEATURE_CONTROLLED, paramType = "header", dataType = "string"), @ApiImplicitParam(name = FHIR_DATA_SERVER_CONFIG_PART, value = CohortEngineRestHandler.EXAMPLE_DATA_SERVER_CONFIG_JSON, dataTypeClass = FhirServerConfig.class, required = true, paramType = "form", type = "file"), @ApiImplicitParam(name = VALUE_SET_PART, value = VALUE_SET_DESC, dataTypeClass = File.class, required = true, paramType = "form", type = "file"), @ApiImplicitParam(name = CUSTOM_CODE_SYSTEM, value = CUSTOM_CODE_SYSTEM_DESC, dataTypeClass = File.class, paramType = "form", type = "file") })
@ApiResponses(value = { @ApiResponse(code = 201, message = "Successful Operation"), @ApiResponse(code = 400, message = "Bad Request", response = ServiceErrorList.class), @ApiResponse(code = 409, message = "Conflict", response = ServiceErrorList.class), @ApiResponse(code = 500, message = "Server Error", response = ServiceErrorList.class) })
@ApiOperation(value = "Insert a new value set to the fhir server or, if it already exists, update it in place", notes = CohortEngineRestHandler.VALUE_SET_API_NOTES, tags = { "ValueSet" }, nickname = "create_value_set", extensions = { @Extension(properties = { @ExtensionProperty(name = DarkFeatureSwaggerFilter.DARK_FEATURE_NAME, value = CohortEngineRestConstants.DARK_LAUNCHED_VALUE_SET_UPLOAD) }) })
public Response createValueSet(@DefaultValue(ServiceBuildConstants.DATE) @ApiParam(value = ServiceBaseConstants.MINOR_VERSION_DESCRIPTION, required = true, defaultValue = ServiceBuildConstants.DATE) @QueryParam(CohortEngineRestHandler.VERSION) String version, @ApiParam(hidden = true, type = "file", required = true) IMultipartBody multipartBody, @ApiParam(value = CohortEngineRestHandler.VALUE_SET_UPDATE_IF_EXISTS_DESC, defaultValue = "false") @DefaultValue("false") @QueryParam(CohortEngineRestHandler.UPDATE_IF_EXISTS_PARM) boolean updateIfExists) {
String methodName = MethodNames.CREATE_VALUE_SET.getName();
Response response;
ServiceBaseUtility.isDarkFeatureEnabled(CohortEngineRestConstants.DARK_LAUNCHED_VALUE_SET_UPLOAD);
try {
// Perform api setup
Response errorResponse = ServiceBaseUtility.apiSetup(version, logger, methodName);
if (errorResponse != null) {
return errorResponse;
}
IAttachment dataSourceAttachment = multipartBody.getAttachment(FHIR_DATA_SERVER_CONFIG_PART);
if (dataSourceAttachment == null) {
throw new IllegalArgumentException(String.format("Missing '%s' MIME attachment", FHIR_DATA_SERVER_CONFIG_PART));
}
// deserialize the MeasuresEvaluation request
ObjectMapper om = new ObjectMapper();
FhirServerConfig fhirServerConfig = om.readValue(dataSourceAttachment.getDataHandler().getInputStream(), FhirServerConfig.class);
// validate the contents of the fhirServerConfig
validateBean(fhirServerConfig);
// get the fhir client object used to call to FHIR
FhirClientBuilder clientBuilder = FhirClientBuilderFactory.newInstance().newFhirClientBuilder();
IGenericClient terminologyClient = clientBuilder.createFhirClient(fhirServerConfig);
IAttachment valueSetAttachment = multipartBody.getAttachment(VALUE_SET_PART);
if (valueSetAttachment == null) {
throw new IllegalArgumentException(String.format("Missing '%s' MIME attachment", VALUE_SET_PART));
}
IAttachment customCodes = multipartBody.getAttachment(CUSTOM_CODE_SYSTEM);
Map<String, String> customCodeMap = null;
if (customCodes != null) {
customCodeMap = ValueSetUtil.getMapFromInputStream(customCodes.getDataHandler().getInputStream());
}
ValueSetArtifact artifact;
try (InputStream is = valueSetAttachment.getDataHandler().getInputStream()) {
artifact = ValueSetUtil.createArtifact(is, customCodeMap);
}
ValueSetUtil.validateArtifact(artifact);
String valueSetId = ValueSetUtil.importArtifact(terminologyClient, artifact, updateIfExists);
if (valueSetId == null) {
return Response.status(Response.Status.CONFLICT).header("Content-Type", "application/json").entity("{\"message\":\"Value Set already exists! Rerun with updateIfExists set to true!\"}").build();
}
response = Response.status(Response.Status.CREATED).header("Content-Type", "application/json").entity("{\"valueSetId\":\"" + valueSetId + "\"}").build();
} catch (Throwable e) {
return new CohortServiceExceptionMapper().toResponse(e);
} finally {
// Perform api cleanup
Response errorResponse = ServiceBaseUtility.apiCleanup(logger, methodName);
if (errorResponse != null) {
response = errorResponse;
}
}
return response;
}
use of com.ibm.cohort.fhir.client.config.FhirClientBuilder in project quality-measure-and-cohort-service by Alvearie.
the class MeasureHelperTest method setUp.
@Before
public void setUp() {
FhirClientBuilderFactory factory = FhirClientBuilderFactory.newInstance();
FhirClientBuilder builder = factory.newFhirClientBuilder(fhirContext);
IGenericClient client = builder.createFhirClient(getFhirServerConfig());
resolver = R4FhirServerResourceResolverFactory.createMeasureResolver(client);
mockFhirResourceRetrieval("/metadata?_format=json", getCapabilityStatement());
}
Aggregations