Search in sources :

Example 1 with Configuration

use of org.hl7.fhir.core.generator.codegen.Configuration in project health-patterns by LinuxForHealth.

the class TerminologyService method translateResource.

/**
 * Translates the given single FHIR resource represented as a {@link JsonNode}.
 *
 * @param resource the FHIR resource to translate
 * @returns true if there was something to translate, false otherwise
 * @throws DeIdentifierException if there is an error in the de-identification REST API or parsing the JSON
 * @throws IllegalArgumentException if the given JSON does not have a 'resource' object
 */
private boolean translateResource(JsonNode resource) {
    boolean translatedSomething = false;
    String resourceType = getResourceType(resource);
    boolean isTranslatable = StringUtils.equalsAny(resourceType, TRANSLATABLE_FHIR_TYPES);
    if (!isTranslatable) {
        return translatedSomething;
    }
    ArrayNode extensions = (ArrayNode) resource.get(EXTENSION_OBJECT);
    if (extensions == null) {
        return translatedSomething;
    }
    for (int i = 0; i < extensions.size(); i++) {
        JsonNode extension = extensions.get(i);
        JsonNode urlJson = extension.get(URL_OBJECT);
        JsonNode valueCodeJson = extension.get(VALUE_CODE_OBJECT);
        if (urlJson == null || valueCodeJson == null) {
            // In order to do a translation we need both the url and the valueCode
            continue;
        }
        // The resource's extension URL is the URL for the StructureDefinition, so we resolve a ValueSet if known
        String structureDefinitionURL = urlJson.asText();
        String valueSetURL = valueSetForStructureDefinition.get(structureDefinitionURL);
        // and if known we check the FHIR Server's known ConceptMaps to see if there is a corresponding one
        // http://4603f72b-us-south.lb.appdomain.cloud/fhir-server/api/v4/ConceptMap?_format=json&source-uri=http://hl7.org/fhir/us/core/ValueSet/birthsex
        Bundle bundle = fhirClient.search().forResource(ConceptMap.class).where(ConceptMap.SOURCE_URI.hasId(valueSetURL)).returnBundle(Bundle.class).execute();
        String conceptMapId;
        if (!bundle.getEntry().isEmpty()) {
            Resource conceptMap = bundle.getEntry().get(0).getResource();
            if (bundle.getEntry().size() > 1) {
                System.err.println("Found multiple ConceptMaps that will map " + valueSetURL + " for this StructureDefinition, will use the first one " + conceptMap.getId());
            } else {
                System.out.println("Found ConceptMap for " + valueSetURL + ": " + conceptMap.getId() + " !!");
            }
            conceptMapId = conceptMap.getIdElement().getIdPart();
        } else {
            System.out.println("Did not find ConceptMap for " + valueSetURL + "!!");
            continue;
        }
        // "POST ${FHIR_URL}/${conceptMapID}/$translate?code=${code}&system=${valueSet}&_format=json
        String valueCode = valueCodeJson.asText();
        String url = String.format("%s/ConceptMap/%s/$translate?code=%s&system=%s&_format=json", fhirClient.getServerBase(), conceptMapId, valueCode, valueSetURL);
        Parameters translationResponse = fhirClient.fetchResourceFromUrl(Parameters.class, url);
        // This is what comes back from the server
        // {
        // "resourceType": "Parameters",
        // "parameter": [
        // {
        // "name": "result",
        // "valueBoolean": true
        // },
        // {
        // "name": "match",
        // "part": [
        // {
        // "name": "equivalence",
        // "valueCode": "equivalent"
        // },
        // {
        // "name": "concept",
        // "valueCoding": {
        // "system": "http://ibm.com/fhir/cdm/ValueSet/sex-assigned-at-birth",
        // "code": "male",
        // "display": "Male"
        // }
        // }
        // ]
        // }
        // ]
        // }
        Coding translatedCode = null;
        List<ParametersParameterComponent> parameters = translationResponse.getParameter();
        for (ParametersParameterComponent parameter : parameters) {
            if (parameter.getName().equals(MATCH_VALUE)) {
                List<ParametersParameterComponent> parts = parameter.getPart();
                for (ParametersParameterComponent part : parts) {
                    if (part.getName().equals(CONCEPT_VALUE)) {
                        try {
                            translatedCode = (Coding) part.getValue();
                        } catch (ClassCastException e) {
                            String jsonResponse = fhirClient.getFhirContext().newJsonParser().encodeResourceToString(translationResponse);
                            System.err.println("Found a ConceptMap that will map " + valueSetURL + " for this StructureDefinition, but the FHIR server returned an unknown $translate response (expected a 'valueCoding' part): " + jsonResponse);
                        }
                    }
                }
            }
        }
        if (translatedCode == null) {
            String jsonResponse = fhirClient.getFhirContext().newJsonParser().encodeResourceToString(translationResponse);
            System.err.println("Found a ConceptMap that will map " + valueSetURL + " for this StructureDefinition, but the FHIR server returned an unknown $translate response: " + jsonResponse);
            continue;
        }
        System.out.printf("Found ConceptMap %s which translates (valueCode, system) = (%s, %s) for StructureDefinition %s to (valueCode, system) = (%s, %s) %n", conceptMapId, valueCode, valueSetURL, structureDefinitionURL, translatedCode.getCode(), translatedCode.getSystem());
        String translatedStructuredData = valueSetForStructureDefinition.get(translatedCode.getSystem());
        if (translatedStructuredData == null) {
            System.err.printf("Cannot find the mapping from ValueSet '%s' to its corresponding StructureData for this translation, make sure the corresponding mappings configuration file has it.%n", translatedCode.getSystem());
            continue;
        }
        ((ObjectNode) extension).set(URL_OBJECT, JsonNodeFactory.instance.textNode(translatedStructuredData));
        ((ObjectNode) extension).set(VALUE_CODE_OBJECT, JsonNodeFactory.instance.textNode(translatedCode.getCode()));
        translatedSomething = true;
    }
    return translatedSomething;
}
Also used : Parameters(org.hl7.fhir.r4.model.Parameters) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) Bundle(org.hl7.fhir.r4.model.Bundle) IBaseResource(org.hl7.fhir.instance.model.api.IBaseResource) Resource(org.hl7.fhir.r4.model.Resource) JsonNode(com.fasterxml.jackson.databind.JsonNode) Coding(org.hl7.fhir.r4.model.Coding) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) ConceptMap(org.hl7.fhir.r4.model.ConceptMap) ParametersParameterComponent(org.hl7.fhir.r4.model.Parameters.ParametersParameterComponent)

Example 2 with Configuration

use of org.hl7.fhir.core.generator.codegen.Configuration in project org.hl7.fhir.core by hapifhir.

the class JavaCoreGenerator method genClass.

public void genClass(String version, String dest, Date date, Configuration config, String jid, NpmPackage npm, Definitions master, JavaParserJsonGenerator jgen, JavaParserXmlGenerator xgen, JavaParserRdfGenerator rgen, StructureDefinition sd) throws Exception, IOException, UnsupportedEncodingException, FileNotFoundException {
    String name = javaName(sd.getName());
    System.out.println(" .. " + name);
    Analyser jca = new Analyser(master, config, version);
    Analysis analysis = jca.analyse(sd);
    String fn = Utilities.path(dest, "src", "main", "java", "org", "hl7", "fhir", jid, "model", name + ".java");
    JavaResourceGenerator gen = new JavaResourceGenerator(new FileOutputStream(fn), master, config, date, npm.version(), jid);
    gen.generate(analysis);
    gen.close();
    jgen.seeClass(analysis);
    xgen.seeClass(analysis);
    rgen.seeClass(analysis);
}
Also used : Analyser(org.hl7.fhir.core.generator.analysis.Analyser) Analysis(org.hl7.fhir.core.generator.analysis.Analysis) FileOutputStream(java.io.FileOutputStream) JavaResourceGenerator(org.hl7.fhir.core.generator.codegen.JavaResourceGenerator)

Example 3 with Configuration

use of org.hl7.fhir.core.generator.codegen.Configuration in project org.hl7.fhir.core by hapifhir.

the class JavaCoreGenerator method generate.

private void generate(String version, String src, String dest) throws Exception {
    long start = System.currentTimeMillis();
    Date date = new Date();
    String ap = Utilities.path(src);
    System.out.println("Load Configuration from " + ap);
    Configuration config = new Configuration(ap);
    String pid = VersionUtilities.isR4BVer(version) ? "r4b" : "r5";
    String jid = VersionUtilities.isR4BVer(version) ? "r4b" : "r5";
    FilesystemPackageCacheManager pcm = new FilesystemPackageCacheManager(true, ToolsVersion.TOOLS_VERSION);
    System.out.println("Cache: " + pcm.getFolder());
    System.out.println("Load hl7.fhir." + pid + ".core");
    NpmPackage npm = pcm.loadPackage("hl7.fhir." + pid + ".core", version);
    Definitions master = VersionUtilities.isR4BVer(version) ? DefinitionsLoaderR4B.load(npm) : DefinitionsLoaderR5.load(npm);
    master.fix();
    markValueSets(master, config);
    System.out.println("Load hl7.fhir." + pid + ".expansions");
    Definitions expansions = DefinitionsLoaderR5.load(pcm.loadPackage("hl7.fhir." + pid + ".expansions", version));
    System.out.println("Process Expansions");
    updateExpansions(master, expansions);
    System.out.println("Generate Model");
    System.out.println(" .. Constants");
    JavaConstantsGenerator cgen = new JavaConstantsGenerator(new FileOutputStream(Utilities.path(dest, "src", "main", "java", "org", "hl7", "fhir", jid, "model", "Constants.java")), master, config, date, npm.version(), jid);
    cgen.generate();
    cgen.close();
    System.out.println(" .. Enumerations");
    JavaEnumerationsGenerator egen = new JavaEnumerationsGenerator(new FileOutputStream(Utilities.path(dest, "src", "main", "java", "org", "hl7", "fhir", jid, "model", "Enumerations.java")), master, config, date, npm.version(), jid);
    egen.generate();
    egen.close();
    JavaFactoryGenerator fgen = new JavaFactoryGenerator(new FileOutputStream(Utilities.path(dest, "src", "main", "java", "org", "hl7", "fhir", jid, "model", "ResourceFactory.java")), master, config, date, npm.version(), jid);
    JavaTypeGenerator tgen = new JavaTypeGenerator(new FileOutputStream(Utilities.path(dest, "src", "main", "java", "org", "hl7", "fhir", jid, "model", "ResourceType.java")), master, config, date, npm.version(), jid);
    JavaParserJsonGenerator jgen = new JavaParserJsonGenerator(new FileOutputStream(Utilities.path(dest, "src", "main", "java", "org", "hl7", "fhir", jid, "formats", "JsonParser.java")), master, config, date, npm.version(), jid);
    JavaParserXmlGenerator xgen = new JavaParserXmlGenerator(new FileOutputStream(Utilities.path(dest, "src", "main", "java", "org", "hl7", "fhir", jid, "formats", "XmlParser.java")), master, config, date, npm.version(), jid);
    JavaParserRdfGenerator rgen = new JavaParserRdfGenerator(new FileOutputStream(Utilities.path(dest, "src", "main", "java", "org", "hl7", "fhir", jid, "formats", "RdfParser.java")), master, config, date, npm.version(), jid);
    if (VersionUtilities.isR4BVer(version)) {
        StructureDefinition sd = master.getStructures().get("http://hl7.org/fhir/StructureDefinition/Element");
        genClass(version, dest, date, config, jid, npm, master, jgen, xgen, rgen, sd);
    }
    for (StructureDefinition sd : master.getStructures().getList()) {
        if (sd.getDerivation() == TypeDerivationRule.SPECIALIZATION && sd.getKind() == StructureDefinitionKind.COMPLEXTYPE) {
            if (!Utilities.existsInList(sd.getName(), "Base", "PrimitiveType") && !sd.getName().contains(".") && sd.getAbstract()) {
                genClass(version, dest, date, config, jid, npm, master, jgen, xgen, rgen, sd);
            }
        }
    }
    for (StructureDefinition sd : master.getStructures().getList()) {
        if (sd.getDerivation() == TypeDerivationRule.SPECIALIZATION && sd.getKind() == StructureDefinitionKind.COMPLEXTYPE) {
            if (!Utilities.existsInList(sd.getName(), "Base", "PrimitiveType") && !sd.getName().contains(".") && !sd.getAbstract()) {
                genClass(version, dest, date, config, jid, npm, master, jgen, xgen, rgen, sd);
            }
        }
    }
    if (VersionUtilities.isR4BVer(version)) {
        StructureDefinition sd = master.getStructures().get("http://hl7.org/fhir/StructureDefinition/Resource");
        genClass(version, dest, date, config, jid, npm, master, jgen, xgen, rgen, sd);
    }
    for (StructureDefinition sd : master.getStructures().getList()) {
        if (sd.getDerivation() == TypeDerivationRule.SPECIALIZATION && sd.getKind() == StructureDefinitionKind.RESOURCE) {
            if (!Utilities.existsInList(sd.getName(), "Base", "PrimitiveType") && !sd.getName().contains(".") && sd.getAbstract()) {
                genClass(version, dest, date, config, jid, npm, master, jgen, xgen, rgen, sd);
            }
        }
    }
    for (StructureDefinition sd : master.getStructures().getList()) {
        if (sd.getDerivation() == TypeDerivationRule.SPECIALIZATION && sd.getKind() == StructureDefinitionKind.RESOURCE) {
            if (!Utilities.existsInList(sd.getName(), "Base", "PrimitiveType") && !sd.getName().contains(".") && !sd.getAbstract()) {
                genClass(version, dest, date, config, jid, npm, master, jgen, xgen, rgen, sd);
            }
        }
    }
    System.out.println(" .. Factory");
    fgen.generate();
    fgen.close();
    System.out.println(" .. Types");
    tgen.generate();
    tgen.close();
    System.out.println(" .. JsonParser");
    jgen.generate();
    jgen.close();
    System.out.println(" .. XmlParser");
    xgen.generate();
    xgen.close();
    System.out.println(" .. RdfParser");
    rgen.generate();
    rgen.close();
    System.out.println("Done (" + Long.toString(System.currentTimeMillis() - start) + "ms)");
}
Also used : JavaEnumerationsGenerator(org.hl7.fhir.core.generator.codegen.JavaEnumerationsGenerator) FilesystemPackageCacheManager(org.hl7.fhir.utilities.npm.FilesystemPackageCacheManager) JavaTypeGenerator(org.hl7.fhir.core.generator.codegen.JavaTypeGenerator) Configuration(org.hl7.fhir.core.generator.codegen.Configuration) JavaParserRdfGenerator(org.hl7.fhir.core.generator.codegen.JavaParserRdfGenerator) JavaParserJsonGenerator(org.hl7.fhir.core.generator.codegen.JavaParserJsonGenerator) JavaParserXmlGenerator(org.hl7.fhir.core.generator.codegen.JavaParserXmlGenerator) Date(java.util.Date) StructureDefinition(org.hl7.fhir.r5.model.StructureDefinition) NpmPackage(org.hl7.fhir.utilities.npm.NpmPackage) JavaFactoryGenerator(org.hl7.fhir.core.generator.codegen.JavaFactoryGenerator) FileOutputStream(java.io.FileOutputStream) JavaConstantsGenerator(org.hl7.fhir.core.generator.codegen.JavaConstantsGenerator)

Example 4 with Configuration

use of org.hl7.fhir.core.generator.codegen.Configuration in project org.hl7.fhir.core by hapifhir.

the class ValidatorCli method main.

public static void main(String[] args) throws Exception {
    TimeTracker tt = new TimeTracker();
    TimeTracker.Session tts = tt.start("Loading");
    args = preProcessArgs(args);
    Display.displayVersion();
    Display.displaySystemInfo();
    if (Params.hasParam(args, Params.PROXY)) {
        assert Params.getParam(args, Params.PROXY) != null : "PROXY arg passed in was NULL";
        String[] p = Params.getParam(args, Params.PROXY).split(":");
        System.setProperty(HTTP_PROXY_HOST, p[0]);
        System.setProperty(HTTP_PROXY_PORT, p[1]);
    }
    if (Params.hasParam(args, Params.PROXY_AUTH)) {
        assert Params.getParam(args, Params.PROXY) != null : "Cannot set PROXY_AUTH without setting PROXY...";
        assert Params.getParam(args, Params.PROXY_AUTH) != null : "PROXY_AUTH arg passed in was NULL...";
        String[] p = Params.getParam(args, Params.PROXY_AUTH).split(":");
        String authUser = p[0];
        String authPass = p[1];
        /*
       * For authentication, use java.net.Authenticator to set proxy's configuration and set the system properties
       * http.proxyUser and http.proxyPassword
       */
        Authenticator.setDefault(new Authenticator() {

            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(authUser, authPass.toCharArray());
            }
        });
        System.setProperty(HTTP_PROXY_USER, authUser);
        System.setProperty(HTTP_PROXY_PASS, authPass);
        System.setProperty(JAVA_USE_SYSTEM_PROXIES, "true");
        /*
       * For Java 1.8 and higher you must set
       * -Djdk.http.auth.tunneling.disabledSchemes=
       * to make proxies with Basic Authorization working with https along with Authenticator
       */
        System.setProperty(JAVA_DISABLED_TUNNELING_SCHEMES, "");
        System.setProperty(JAVA_DISABLED_PROXY_SCHEMES, "");
    }
    CliContext cliContext = Params.loadCliContext(args);
    if (Params.hasParam(args, Params.TEST)) {
        Common.runValidationEngineTests();
    } else if (shouldDisplayHelpToUser(args)) {
        Display.displayHelpDetails();
    } else if (Params.hasParam(args, Params.COMPARE)) {
        if (destinationDirectoryValid(Params.getParam(args, Params.DESTINATION))) {
            doLeftRightComparison(args, cliContext, tt);
        }
    } else {
        Display.printCliArgumentsAndInfo(args);
        doValidation(tt, tts, cliContext);
    }
}
Also used : TimeTracker(org.hl7.fhir.utilities.TimeTracker) CliContext(org.hl7.fhir.validation.cli.model.CliContext) Authenticator(java.net.Authenticator) PasswordAuthentication(java.net.PasswordAuthentication)

Example 5 with Configuration

use of org.hl7.fhir.core.generator.codegen.Configuration in project pathling by aehrc.

the class ManifestConverterTest method convertsManifest.

@Test
void convertsManifest() {
    database = new Database(configuration, spark, fhirEncoders, executor);
    final PassportScope passportScope = new PassportScope();
    final VisaManifest manifest = new VisaManifest();
    manifest.setPatientIds(Arrays.asList(PATIENT_ID_1, PATIENT_ID_2, PATIENT_ID_3, PATIENT_ID_4));
    final ManifestConverter manifestConverter = new ManifestConverter(configuration, fhirContext);
    manifestConverter.populateScope(passportScope, manifest);
    // Convert the scope to JSON and compare it to a test fixture.
    final Gson gson = new GsonBuilder().create();
    final String json = gson.toJson(passportScope);
    assertJson("responses/ManifestConverterTest/convertsManifest.json", json);
    // our test patients.
    for (final ResourceType resourceType : passportScope.keySet()) {
        if (AVAILABLE_RESOURCE_TYPES.contains(resourceType)) {
            boolean found = false;
            for (final String filter : passportScope.get(resourceType)) {
                final Dataset<Row> dataset = assertThatResultOf(resourceType, filter).isElementPath(BooleanPath.class).selectResult().apply(result -> result.filter(result.columns()[1])).getDataset();
                if (dataset.count() > 0) {
                    found = true;
                }
            }
            assertTrue(found, "No results found for " + resourceType.toCode());
        }
    }
}
Also used : Arrays(java.util.Arrays) Dataset(org.apache.spark.sql.Dataset) DynamicPropertySource(org.springframework.test.context.DynamicPropertySource) Autowired(org.springframework.beans.factory.annotation.Autowired) DynamicPropertyRegistry(org.springframework.test.context.DynamicPropertyRegistry) ResourceType(org.hl7.fhir.r4.model.Enumerations.ResourceType) BooleanPath(au.csiro.pathling.fhirpath.element.BooleanPath) GsonBuilder(com.google.gson.GsonBuilder) FhirContext(ca.uhn.fhir.context.FhirContext) FhirEncoders(au.csiro.pathling.encoders.FhirEncoders) Gson(com.google.gson.Gson) Assertions.assertJson(au.csiro.pathling.test.assertions.Assertions.assertJson) Nonnull(javax.annotation.Nonnull) MockBean(org.springframework.boot.test.mock.mockito.MockBean) ThreadPoolTaskExecutor(org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor) Configuration(au.csiro.pathling.Configuration) TestPropertySource(org.springframework.test.context.TestPropertySource) Row(org.apache.spark.sql.Row) File(java.io.File) Test(org.junit.jupiter.api.Test) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) AbstractParserTest(au.csiro.pathling.fhirpath.parser.AbstractParserTest) Database(au.csiro.pathling.io.Database) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) GsonBuilder(com.google.gson.GsonBuilder) BooleanPath(au.csiro.pathling.fhirpath.element.BooleanPath) Gson(com.google.gson.Gson) ResourceType(org.hl7.fhir.r4.model.Enumerations.ResourceType) Database(au.csiro.pathling.io.Database) Row(org.apache.spark.sql.Row) Test(org.junit.jupiter.api.Test) AbstractParserTest(au.csiro.pathling.fhirpath.parser.AbstractParserTest)

Aggregations

List (java.util.List)4 Configuration (au.csiro.pathling.Configuration)2 FhirEncoders (au.csiro.pathling.encoders.FhirEncoders)2 Database (au.csiro.pathling.io.Database)2 Assertions.assertJson (au.csiro.pathling.test.assertions.Assertions.assertJson)2 FhirContext (ca.uhn.fhir.context.FhirContext)2 Gson (com.google.gson.Gson)2 FileOutputStream (java.io.FileOutputStream)2 ArrayList (java.util.ArrayList)2 Date (java.util.Date)2 HashSet (java.util.HashSet)2 Set (java.util.Set)2 Nonnull (javax.annotation.Nonnull)2 ValueSet (org.hl7.fhir.r4.model.ValueSet)2 Grouping (au.csiro.pathling.aggregate.AggregateResponse.Grouping)1 TerminologyServiceFactory (au.csiro.pathling.fhir.TerminologyServiceFactory)1 BooleanPath (au.csiro.pathling.fhirpath.element.BooleanPath)1 AbstractParserTest (au.csiro.pathling.fhirpath.parser.AbstractParserTest)1 SearchExecutor (au.csiro.pathling.search.SearchExecutor)1 TerminologyService (au.csiro.pathling.terminology.TerminologyService)1