Search in sources :

Example 1 with ValueSetArtifact

use of com.ibm.cohort.valueset.ValueSetArtifact 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;
}
Also used : FhirClientBuilder(com.ibm.cohort.fhir.client.config.FhirClientBuilder) IGenericClient(ca.uhn.fhir.rest.client.api.IGenericClient) ZipInputStream(java.util.zip.ZipInputStream) InputStream(java.io.InputStream) ValueSetArtifact(com.ibm.cohort.valueset.ValueSetArtifact) IAttachment(com.ibm.websphere.jaxrs20.multipart.IAttachment) Response(javax.ws.rs.core.Response) ApiResponse(io.swagger.annotations.ApiResponse) FhirServerConfig(com.ibm.cohort.fhir.client.config.FhirServerConfig) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Path(javax.ws.rs.Path) ApiImplicitParams(io.swagger.annotations.ApiImplicitParams) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 2 with ValueSetArtifact

use of com.ibm.cohort.valueset.ValueSetArtifact 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

IGenericClient (ca.uhn.fhir.rest.client.api.IGenericClient)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 FhirServerConfig (com.ibm.cohort.fhir.client.config.FhirServerConfig)2 ValueSetArtifact (com.ibm.cohort.valueset.ValueSetArtifact)2 InputStream (java.io.InputStream)2 FhirContext (ca.uhn.fhir.context.FhirContext)1 AmazonS3 (com.amazonaws.services.s3.AmazonS3)1 JCommander (com.beust.jcommander.JCommander)1 Console (com.beust.jcommander.internal.Console)1 DefaultConsole (com.beust.jcommander.internal.DefaultConsole)1 FhirClientBuilder (com.ibm.cohort.fhir.client.config.FhirClientBuilder)1 S3Configuration (com.ibm.cohort.tooling.s3.S3Configuration)1 IAttachment (com.ibm.websphere.jaxrs20.multipart.IAttachment)1 ApiImplicitParams (io.swagger.annotations.ApiImplicitParams)1 ApiOperation (io.swagger.annotations.ApiOperation)1 ApiResponse (io.swagger.annotations.ApiResponse)1 ApiResponses (io.swagger.annotations.ApiResponses)1 BufferedWriter (java.io.BufferedWriter)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 File (java.io.File)1