ballerina-platform / ballerina-library

The Ballerina Library
https://ballerina.io/learn/api-docs/ballerina/
Apache License 2.0
136 stars 64 forks source link

[FHIR] Add FHIR XML resource parsing support #7220

Open sameeragunarathne opened 11 months ago

sameeragunarathne commented 11 months ago

Description: This issue is to track the FHIR XML resource payload parse support to the ballerina fhir healthcare package.

nimsara66 commented 11 months ago

Here's an implementation of a working Proof of Concept (PoC) for FHIR XML resource payload parse support in Ballerina:

FHIRParser.java

package nimsara66.fhir;

import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.parser.DataFormatException;
import ca.uhn.fhir.parser.IParser;
import org.hl7.fhir.instance.model.api.IBaseResource;
import io.ballerina.runtime.api.values.BXml;
import io.ballerina.runtime.api.values.BString;
import io.ballerina.runtime.api.utils.StringUtils;
import io.ballerina.runtime.api.utils.JsonUtils;
import io.ballerina.runtime.internal.ValueConverter;

public class FHIRParser {
    private static final FhirContext context = FhirContext.forR4();

    public static Object fhirXmlToJson(final BXml content) throws DataFormatException {
        IParser source = context.newXmlParser(); // new XML parser
        IBaseResource resource = source.parseResource(content.toString()); // parse the resource
        IParser target = context.newJsonParser(); // new JSON parser
        String jsonString = target.setPrettyPrint(true).encodeResourceToString(resource); // output JSON
        BString bstring = StringUtils.fromString(jsonString);
        return JsonUtils.parse(bstring);
    }
}

fair-lib.bal

import ballerina/jballerina.java;

public type Error distinct error;

# Convert FHIR XML to JSON
#
# + xmlValue - FHIR XML to be converted to JSON
# + return - Converted JSON or Error
public isolated function fhirXmlToJson(xml xmlValue) returns json|Error = @java:Method {
    'class: "nimsara66.fhir.FHIRParser"
} external;

Note:

This PoC demonstrates the conversion of FHIR XML to JSON using a Java method invocation in Ballerina. Feel free to review and integrate it into the Ballerina FHIR healthcare package. If you have any questions or suggestions, please let me know!

sameeragunarathne commented 11 months ago

Thanks @nimsara66 for the contributions. We will evaluate this and come back.