Search in sources :

Example 36 with ResourceType

use of org.hl7.fhir.r4.model.ResourceType in project org.hl7.fhir.core by hapifhir.

the class JsonParser method compose.

private void compose(String path, Element element) throws IOException {
    String name = element.getName();
    if (element.isPrimitive() || isPrimitive(element.getType())) {
        if (element.hasValue())
            primitiveValue(name, element);
        name = "_" + name;
    }
    if (element.hasChildren()) {
        open(name, linkResolver == null ? null : linkResolver.resolveProperty(element.getProperty()));
        if (element.getProperty().isResource()) {
            prop("resourceType", element.getType(), linkResolver == null ? null : linkResolver.resolveType(element.getType()));
        }
        Set<String> done = new HashSet<String>();
        for (Element child : element.getChildren()) {
            compose(path + "." + element.getName(), element, done, child);
        }
        close();
    }
}
Also used : SpecialElement(org.hl7.fhir.r4.elementmodel.Element.SpecialElement) JsonElement(com.google.gson.JsonElement) HashSet(java.util.HashSet)

Example 37 with ResourceType

use of org.hl7.fhir.r4.model.ResourceType in project fhir-bridge by ehrbase.

the class FhirProfileValidator method validateProfiles.

/**
 * Validates the profiles for the given resource.
 *
 * @param resource the submitted resource
 * @param exchange the current exchange
 */
private void validateProfiles(Resource resource, Exchange exchange) {
    Set<Profile> supportedProfiles = Profile.resolveAll(resource);
    Class<? extends Resource> resourceType = resource.getClass();
    OperationOutcome outcome = new OperationOutcome();
    if (supportedProfiles.isEmpty()) {
        outcome.addIssue(new OperationOutcomeIssueComponent().setSeverity(IssueSeverity.FATAL).setCode(IssueType.VALUE).setDiagnostics(messages.getMessage("validation.profile.missingSupported", new Object[] { Profile.getSupportedProfiles(resourceType) })).addExpression(profileExpression(resource)));
    } else if (supportedProfiles.size() > 1) {
        outcome.addIssue(new OperationOutcomeIssueComponent().setSeverity(IssueSeverity.FATAL).setCode(IssueType.VALUE).setDiagnostics(messages.getMessage("validation.profile.moreThanOneSupported")).addExpression(profileExpression(resource)));
    }
    if (outcome.hasIssue()) {
        throw new UnprocessableEntityException(fhirContext, outcome);
    }
    exchange.getMessage().setHeader(CamelConstants.PROFILE, supportedProfiles.iterator().next());
}
Also used : UnprocessableEntityException(ca.uhn.fhir.rest.server.exceptions.UnprocessableEntityException) OperationOutcomeIssueComponent(org.hl7.fhir.r4.model.OperationOutcome.OperationOutcomeIssueComponent) OperationOutcome(org.hl7.fhir.r4.model.OperationOutcome) Profile(org.ehrbase.fhirbridge.fhir.common.Profile)

Example 38 with ResourceType

use of org.hl7.fhir.r4.model.ResourceType in project geoprism-registry by terraframe.

the class FhirBulkDataImporter method synchronize.

public void synchronize() {
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS);
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setConnectionManager(connectionManager);
    CloseableHttpClient myClient = builder.build();
    FhirContext ctx = FhirContext.forR4();
    String statusUrl = initiateBulkExport(myClient, ctx);
    if (statusUrl != null) {
        final List<String> outputs = getExportResults(myClient, statusUrl);
        IGenericClient client = ctx.newRestfulGenericClient(this.system.getUrl());
        for (String binaryUrl : outputs) {
            Binary binary = client.fetchResourceFromUrl(Binary.class, binaryUrl);
            String base64 = binary.getContentAsBase64();
            byte[] result = Base64.getDecoder().decode(base64);
            IParser parser = ctx.newJsonParser();
            String message = new String(result);
            try (BufferedReader reader = new BufferedReader(new StringReader(message))) {
                String line = null;
                while ((line = reader.readLine()) != null) {
                    IBaseResource resource = parser.parseResource(line);
                    IIdType id = resource.getIdElement();
                    String resourceType = id.getResourceType();
                    if (resourceType.equals(ResourceTypes.LOCATION.toCode())) {
                        Location location = (Location) resource;
                        this.processor.process(location);
                    } else if (resourceType.equals(ResourceTypes.ORGANIZATION.toCode())) {
                        Organization organization = (Organization) resource;
                        this.processor.process(organization);
                    }
                }
            } catch (IOException e) {
                throw new ProgrammingErrorException(e);
            }
        }
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) FhirContext(ca.uhn.fhir.context.FhirContext) Organization(org.hl7.fhir.r4.model.Organization) IGenericClient(ca.uhn.fhir.rest.client.api.IGenericClient) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) IOException(java.io.IOException) ProgrammingErrorException(com.runwaysdk.dataaccess.ProgrammingErrorException) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) BufferedReader(java.io.BufferedReader) StringReader(java.io.StringReader) Binary(org.hl7.fhir.r4.model.Binary) IBaseResource(org.hl7.fhir.instance.model.api.IBaseResource) IParser(ca.uhn.fhir.parser.IParser) IIdType(org.hl7.fhir.instance.model.api.IIdType) Location(org.hl7.fhir.r4.model.Location)

Example 39 with ResourceType

use of org.hl7.fhir.r4.model.ResourceType in project pathling by aehrc.

the class ReverseResolveFunction method invoke.

@Nonnull
@Override
public FhirPath invoke(@Nonnull final NamedFunctionInput input) {
    checkUserInput(input.getInput() instanceof ResourcePath, "Input to " + NAME + " function must be a resource: " + input.getInput().getExpression());
    final ResourcePath inputPath = (ResourcePath) input.getInput();
    final String expression = NamedFunction.expressionFromInput(input, NAME);
    checkUserInput(input.getArguments().size() == 1, "reverseResolve function accepts a single argument: " + expression);
    final FhirPath argument = input.getArguments().get(0);
    checkUserInput(argument instanceof ReferencePath, "Argument to reverseResolve function must be a Reference: " + argument.getExpression());
    final ReferencePath referencePath = (ReferencePath) argument;
    // Check that the input type is one of the possible types specified by the argument.
    final Set<ResourceType> argumentTypes = ((ReferencePath) argument).getResourceTypes();
    final ResourceType inputType = inputPath.getResourceType();
    checkUserInput(argumentTypes.contains(inputType), "Reference in argument to reverseResolve does not support input resource type: " + expression);
    // Do a left outer join from the input to the argument dataset using the reference field in the
    // argument.
    final Column joinCondition = referencePath.getResourceEquality(inputPath);
    final Dataset<Row> dataset = join(referencePath.getDataset(), inputPath.getDataset(), joinCondition, JoinType.RIGHT_OUTER);
    // Check the argument for information about the current resource that it originated from - if it
    // is not present, reverse reference resolution will not be possible.
    final NonLiteralPath nonLiteralArgument = (NonLiteralPath) argument;
    checkUserInput(nonLiteralArgument.getCurrentResource().isPresent(), "Argument to reverseResolve must be an element that is navigable from a " + "target resource type: " + expression);
    final ResourcePath currentResource = nonLiteralArgument.getCurrentResource().get();
    final Optional<Column> thisColumn = inputPath.getThisColumn();
    // TODO: Consider removing in the future once we separate ordering from element ID.
    // Create an synthetic element ID column for reverse resolved resources.
    final Column currentResourceValue = currentResource.getValueColumn();
    final WindowSpec windowSpec = Window.partitionBy(inputPath.getIdColumn(), inputPath.getOrderingColumn()).orderBy(currentResourceValue);
    // row_number() is 1-based, and we use 0-based indexes - thus (minus(1)).
    final Column currentResourceIndex = when(currentResourceValue.isNull(), lit(null)).otherwise(row_number().over(windowSpec).minus(lit(1)));
    // We need to add the synthetic EID column to the parser context so that it can be used within
    // joins in certain situations, e.g. extract.
    final Column syntheticEid = inputPath.expandEid(currentResourceIndex);
    final DatasetWithColumn datasetWithEid = QueryHelpers.createColumn(dataset, syntheticEid);
    input.getContext().getNodeIdColumns().putIfAbsent(expression, datasetWithEid.getColumn());
    final ResourcePath result = currentResource.copy(expression, datasetWithEid.getDataset(), inputPath.getIdColumn(), Optional.of(syntheticEid), currentResource.getValueColumn(), false, thisColumn);
    result.setCurrentResource(currentResource);
    return result;
}
Also used : FhirPath(au.csiro.pathling.fhirpath.FhirPath) ResourceType(org.hl7.fhir.r4.model.Enumerations.ResourceType) ResourcePath(au.csiro.pathling.fhirpath.ResourcePath) DatasetWithColumn(au.csiro.pathling.QueryHelpers.DatasetWithColumn) Column(org.apache.spark.sql.Column) DatasetWithColumn(au.csiro.pathling.QueryHelpers.DatasetWithColumn) ReferencePath(au.csiro.pathling.fhirpath.element.ReferencePath) Row(org.apache.spark.sql.Row) NonLiteralPath(au.csiro.pathling.fhirpath.NonLiteralPath) WindowSpec(org.apache.spark.sql.expressions.WindowSpec) Nonnull(javax.annotation.Nonnull)

Example 40 with ResourceType

use of org.hl7.fhir.r4.model.ResourceType in project pathling by aehrc.

the class ManifestConverter method populateScope.

void populateScope(@Nonnull final PassportScope passportScope, @Nonnull final VisaManifest manifest) {
    // Create a filter for the Patient resource.
    final String patientIdCollection = manifest.getPatientIds().stream().map(id -> "'" + id + "'").collect(Collectors.joining(" combine "));
    final String patientIdFilter = "identifier.where(system = '" + StringLiteralPath.escapeFhirPathString(patientIdSystem) + "').where(value in (" + patientIdCollection + "))" + ".empty().not()";
    final Set<String> patientFilters = passportScope.get(ResourceType.PATIENT);
    if (patientFilters == null) {
        passportScope.put(ResourceType.PATIENT, new HashSet<>(List.of(patientIdFilter)));
    } else {
        patientFilters.add(patientIdFilter);
    }
    // See: https://www.hl7.org/fhir/r4/compartmentdefinition-patient.html
    for (final ResourceType resourceType : ResourceType.values()) {
        if (resourceType.equals(ResourceType.DOMAINRESOURCE) || resourceType.equals(ResourceType.RESOURCE) || resourceType.equals(ResourceType.NULL)) {
            continue;
        }
        final RuntimeResourceDefinition definition = fhirContext.getResourceDefinition(resourceType.toCode());
        final List<RuntimeSearchParam> searchParams = definition.getSearchParamsForCompartmentName("Patient");
        for (final RuntimeSearchParam searchParam : searchParams) {
            final String path = searchParam.getPath();
            // Remove the leading "[resource type]." from the path.
            final String pathTrimmed = path.replaceFirst("^" + resourceType.toCode() + "\\.", "");
            // Paths that end with this resolve pattern are polymorphic references, and will need
            // to be resolved using `ofType()` within our implementation.
            final String resolvePattern = ".where(resolve() is Patient)";
            final String filter;
            if (pathTrimmed.endsWith(resolvePattern)) {
                filter = pathTrimmed.replace(resolvePattern, ".resolve().ofType(Patient)." + patientIdFilter);
            } else {
                final Set<String> targets = searchParam.getTargets();
                if (targets.size() > 0 && !targets.contains("Patient")) {
                    // Patient, we need to skip it altogether.
                    continue;
                } else if (targets.size() == 1) {
                    // If the search parameter is monomorphic, we can resolve it without `ofType`.
                    filter = pathTrimmed + ".resolve()." + patientIdFilter;
                } else {
                    // If the search parameter is polymorphic, we also need to resolve it to Patient. Note
                    // that polymorphic references with an "Any" type have zero targets.
                    filter = pathTrimmed + ".resolve().ofType(Patient)." + patientIdFilter;
                }
            }
            // Add the filter to the map.
            final Set<String> filters = passportScope.get(resourceType);
            if (filters == null) {
                passportScope.put(resourceType, new HashSet<>(List.of(filter)));
            } else {
                filters.add(filter);
            }
        }
    }
}
Also used : RuntimeSearchParam(ca.uhn.fhir.context.RuntimeSearchParam) Configuration(au.csiro.pathling.Configuration) Set(java.util.Set) ResourceType(org.hl7.fhir.r4.model.Enumerations.ResourceType) Collectors(java.util.stream.Collectors) Profile(org.springframework.context.annotation.Profile) HashSet(java.util.HashSet) FhirContext(ca.uhn.fhir.context.FhirContext) List(java.util.List) Component(org.springframework.stereotype.Component) StringLiteralPath(au.csiro.pathling.fhirpath.literal.StringLiteralPath) RuntimeResourceDefinition(ca.uhn.fhir.context.RuntimeResourceDefinition) Nonnull(javax.annotation.Nonnull) RuntimeResourceDefinition(ca.uhn.fhir.context.RuntimeResourceDefinition) ResourceType(org.hl7.fhir.r4.model.Enumerations.ResourceType) RuntimeSearchParam(ca.uhn.fhir.context.RuntimeSearchParam)

Aggregations

JsonElement (com.google.gson.JsonElement)33 HashSet (java.util.HashSet)26 Bundle (org.hl7.fhir.r4.model.Bundle)24 ResourceType (org.hl7.fhir.r4.model.Enumerations.ResourceType)21 Test (org.junit.Test)20 Nonnull (javax.annotation.Nonnull)18 ArrayList (java.util.ArrayList)15 IBaseResource (org.hl7.fhir.instance.model.api.IBaseResource)10 FhirContext (ca.uhn.fhir.context.FhirContext)9 File (java.io.File)9 Row (org.apache.spark.sql.Row)9 IdType (org.hl7.fhir.dstu3.model.IdType)9 BundleEntryComponent (org.hl7.fhir.r4.model.Bundle.BundleEntryComponent)9 JsonObject (com.google.gson.JsonObject)8 Test (org.junit.jupiter.api.Test)8 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)8 IOException (java.io.IOException)7 List (java.util.List)7 Bundle (org.hl7.fhir.dstu3.model.Bundle)7 Resource (org.hl7.fhir.r4.model.Resource)7