Skip to content

Instantly share code, notes, and snippets.

@bartolli
Last active July 7, 2024 19:47
Show Gist options
  • Save bartolli/3bd1d991fdac6cf7422e149427541474 to your computer and use it in GitHub Desktop.
Save bartolli/3bd1d991fdac6cf7422e149427541474 to your computer and use it in GitHub Desktop.
FhirConverter_v1.java
package com.example;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.parser.IParser;
import org.apache.jena.query.ARQ;
import org.hl7.fhir.instance.model.api.IBaseResource;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class FhirConverter {
private FhirContext ctx;
public FhirConverter() {
// Initialize FHIR context for R4
this.ctx = FhirContext.forR4();
// Initialize ARQ context
ARQ.init();
}
// Method to convert JSON to XML
public String convertJsonToXml(String json) {
// Create a JSON parser
IParser jsonParser = ctx.newJsonParser().setPrettyPrint(true);
// Parse JSON to a FHIR resource
IBaseResource resource = jsonParser.parseResource(json);
// Create an XML parser
IParser xmlParser = ctx.newXmlParser().setPrettyPrint(true);
// Encode the FHIR resource to XML
return xmlParser.encodeResourceToString(resource);
}
// Method to convert XML to JSON
public String convertXmlToJson(String xml) {
// Create an XML parser
IParser xmlParser = ctx.newXmlParser().setPrettyPrint(true);
// Parse XML to a FHIR resource
IBaseResource resource = xmlParser.parseResource(xml);
// Create a JSON parser
IParser jsonParser = ctx.newJsonParser().setPrettyPrint(true);
// Encode the FHIR resource to JSON
return jsonParser.encodeResourceToString(resource);
}
// Method to convert JSON to RDF (Turtle)
public String convertJsonToTurtle(String json) {
// Create a JSON parser
IParser jsonParser = ctx.newJsonParser();
// Parse JSON to a FHIR resource
IBaseResource resource = jsonParser.parseResource(json);
// Create an RDF parser (Turtle format)
IParser rdfParser = ctx.newRDFParser(); // This returns an instance of RDFParser
// Encode the FHIR resource to RDF (Turtle format)
return rdfParser.encodeResourceToString(resource);
}
// Method to convert RDF (Turtle) to JSON
public String convertTurtleToJson(String turtle) {
// Create an RDF parser (Turtle format)
IParser rdfParser = ctx.newRDFParser(); // This returns an instance of RDFParser
// Parse RDF (Turtle format) to a FHIR resource
IBaseResource resource = rdfParser.parseResource(turtle);
// Create a JSON parser
IParser jsonParser = ctx.newJsonParser().setPrettyPrint(true);
// Encode the FHIR resource to JSON
return jsonParser.encodeResourceToString(resource);
}
public static void main(String[] args) {
if (args.length != 3) {
System.err.println("Usage: java -jar fhir-converter.jar <inputFile> <outputFile> <format>");
System.err.println("<format>: xml-to-json, json-to-xml, json-to-turtle, turtle-to-json");
System.exit(1);
}
String inputFile = args[0];
String outputFile = args[1];
String format = args[2];
try {
FhirConverter converter = new FhirConverter();
// Read the input file content
String inputContent = new String(Files.readAllBytes(Paths.get(inputFile)));
String outputContent = null;
// Perform the conversion based on the specified format
switch (format) {
case "xml-to-json":
outputContent = converter.convertXmlToJson(inputContent);
break;
case "json-to-xml":
outputContent = converter.convertJsonToXml(inputContent);
break;
case "json-to-turtle":
outputContent = converter.convertJsonToTurtle(inputContent);
break;
case "turtle-to-json":
outputContent = converter.convertTurtleToJson(inputContent);
break;
default:
System.err.println("Unknown format: " + format);
System.exit(1);
}
// Write the output content to the specified file
Files.write(Paths.get(outputFile), (outputContent != null ? outputContent.getBytes() : "Error during conversion. Output content is null.".getBytes()));
System.out.println("Conversion successful! Output written to " + outputFile);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
}
package com.example;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.context.support.DefaultProfileValidationSupport;
// import ca.uhn.fhir.context.support.IValidationSupport;
import ca.uhn.fhir.context.support.ValidationSupportContext;
import ca.uhn.fhir.parser.IParser;
import org.hl7.fhir.common.hapi.validation.support.ValidationSupportChain;
import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.common.hapi.validation.support.SnapshotGeneratingValidationSupport;
import org.hl7.fhir.instance.model.api.IBaseResource;
import org.hl7.fhir.r4.model.StructureDefinition;
import org.hl7.fhir.r4.elementmodel.Element;
import org.hl7.fhir.r4.elementmodel.JsonParser;
import org.hl7.fhir.r4.elementmodel.TurtleParser;
import org.hl7.fhir.r4.context.SimpleWorkerContext;
import org.hl7.fhir.r4.hapi.ctx.HapiWorkerContext;
import org.hl7.fhir.r4.utils.formats.Turtle;
import org.slf4j.LoggerFactory;
// import org.hl7.fhir.utilities.npm.NpmPackage;
// import org.hl7.fhir.r4.context.IWorkerContext;
// import org.hl7.fhir.r4.terminologies.ValueSetExpander.ValueSetExpansionOutcome; // Import for ValueSetExpander
// import org.hl7.fhir.instance.model.api.IBaseResource;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.slf4j.Logger;
// import org.slf4j.LoggerFactory;
public class FhirConverter {
private static final Logger logger = LoggerFactory.getLogger(FhirConverter.class);
private FhirContext ctx;
private ValidationSupportChain validationSupportChain;
private HapiWorkerContext workerContext;
public FhirConverter() throws IOException {
this.ctx = FhirContext.forR4();
DefaultProfileValidationSupport defaultValidationSupport = new DefaultProfileValidationSupport(ctx);
SnapshotGeneratingValidationSupport snapshotGenerator = new SnapshotGeneratingValidationSupport(ctx);
this.validationSupportChain = new ValidationSupportChain(defaultValidationSupport, snapshotGenerator);
this.workerContext = new HapiWorkerContext(ctx, validationSupportChain);
logger.info("FhirConverter initialized");
}
private void loadLocalResource(SimpleWorkerContext swc, String filePath) throws IOException {
Path path = Paths.get(filePath);
String xmlContent = Files.readString(path);
IParser xmlParser = ctx.newXmlParser();
IBaseResource resource = xmlParser.parseResource(xmlContent);
if (resource instanceof StructureDefinition) {
StructureDefinition sd = (StructureDefinition) resource;
swc.cacheResource(sd); // Using cacheResource instead of loadResource
} else {
logger.error("Resource at " + filePath + " is not a StructureDefinition");
throw new IllegalArgumentException("Resource at " + filePath + " is not a StructureDefinition");
}
}
public String convertJsonToTurtle(String json) {
logger.debug("Starting JSON to Turtle conversion");
try {
IParser parser = ctx.newJsonParser();
IBaseResource resource = parser.parseResource(json);
if (resource instanceof StructureDefinition) {
StructureDefinition sd = (StructureDefinition) resource;
logger.debug("Processing StructureDefinition");
if (!sd.hasSnapshot()) {
logger.debug("Generating snapshot for StructureDefinition");
String definitionsPath = "/Users/bartolli/Projects/java/fhir-converter/src/main/resources/org/hl7/fhir/r4/model/profile"; // Update this path!!!
SimpleWorkerContext swc = new SimpleWorkerContext();
loadLocalResource(swc, definitionsPath + "/profiles-resources.xml");
loadLocalResource(swc, definitionsPath + "/profiles-types.xml");
loadLocalResource(swc, definitionsPath + "/profiles-others.xml");
validationSupportChain.generateSnapshot(new ValidationSupportContext(validationSupportChain), sd, sd.getUrl(), null, sd.getName());
json = parser.encodeResourceToString(sd);
}
}
JsonParser jsonParser = new JsonParser(workerContext);
Element element = jsonParser.parse(new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)));
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
TurtleParser turtleParser = new TurtleParser(workerContext);
Turtle turtle = new Turtle();
turtleParser.compose(element, turtle, null); // base can be null or your base URI
turtle.commit(outputStream, false); // Write the composed Turtle to the output stream
logger.info("Conversion completed successfully");
return outputStream.toString(StandardCharsets.UTF_8);
} catch (FileNotFoundException e) {
logger.error("File not found while initializing SimpleWorkerContext or loading resources", e);
} catch (IOException e) {
logger.error("IO exception while initializing SimpleWorkerContext, loading resources, or parsing", e);
} catch (FHIRException e) {
logger.error("FHIR exception while initializing SimpleWorkerContext, loading resources, or serializing", e);
}
return null; // Return null if any exceptions are caught
}
// Existing methods for XML and JSON conversion
public String convertJsonToXml(String json) {
IParser jsonParser = ctx.newJsonParser();
IBaseResource resource = jsonParser.parseResource(json);
IParser xmlParser = ctx.newXmlParser().setPrettyPrint(true);
return xmlParser.encodeResourceToString(resource);
}
public String convertXmlToJson(String xml) {
IParser xmlParser = ctx.newXmlParser();
IBaseResource resource = xmlParser.parseResource(xml);
IParser jsonParser = ctx.newJsonParser().setPrettyPrint(true);
return jsonParser.encodeResourceToString(resource);
}
public static void main(String[] args) {
logger.info("Starting FHIR Converter");
if (args.length != 3) {
logger.error("Usage: java -jar fhir-converter.jar <inputFile> <outputFile> <format>");
System.exit(1);
}
String inputFile = args[0];
String outputFile = args[1];
String format = args[2];
try {
FhirConverter converter = new FhirConverter();
String inputContent = new String(Files.readAllBytes(Paths.get(inputFile)));
String outputContent = null;
switch (format) {
case "xml-to-json":
outputContent = converter.convertXmlToJson(inputContent);
break;
case "json-to-xml":
outputContent = converter.convertJsonToXml(inputContent);
break;
case "json-to-turtle":
outputContent = converter.convertJsonToTurtle(inputContent);
break;
case "turtle-to-json":
// Implement turtle to json conversion if required
System.err.println("Turtle to JSON conversion not implemented.");
break;
default:
logger.error("Unknown format: " + format);
System.exit(1);
}
if (outputContent != null) {
Files.write(Paths.get(outputFile), outputContent.getBytes(StandardCharsets.UTF_8));
logger.info("Conversion successful! Output written to " + outputFile);
} else {
logger.error("Conversion failed: output content is null");
System.exit(1);
}
} catch (IOException e) {
logger.error("Error during conversion", e);
System.exit(1);
}
}
}
(base) Projects/java/fhir-converter ❯ java -Dlogback.configurationFile=file:logback.xml -jar target/fhir-converter-1.0-SNAPSHOT-jar-with-dependencies.jar /Users/bartolli/Projects/fhirtordf/Darrick836_Wunsch504_cb6aca68-e6a3-ee70-5876-9f255c3eac48.json output.ttl json-to-turtle
[main] INFO com.example.FhirConverter - Starting FHIR Converter
[main] INFO ca.uhn.fhir.util.VersionUtil - HAPI FHIR version 7.2.1 - Rev 547c9320f1
[main] INFO ca.uhn.fhir.context.FhirContext - Creating new FHIR context for FHIR version [R4]
[main] INFO com.example.FhirConverter - FhirConverter initialized
[main] INFO ca.uhn.fhir.util.XmlUtil - Unable to determine StAX implementation: java.xml/META-INF/MANIFEST.MF not found
[main] INFO ca.uhn.fhir.context.support.DefaultProfileValidationSupport - Loading structure definitions from classpath: /org/hl7/fhir/r4/model/profile/profiles-resources.xml
[main] INFO ca.uhn.fhir.context.support.DefaultProfileValidationSupport - Loading structure definitions from classpath: /org/hl7/fhir/r4/model/profile/profiles-types.xml
[main] INFO ca.uhn.fhir.context.support.DefaultProfileValidationSupport - Loading structure definitions from classpath: /org/hl7/fhir/r4/model/profile/profiles-others.xml
[main] INFO ca.uhn.fhir.context.support.DefaultProfileValidationSupport - Loading structure definitions from classpath: /org/hl7/fhir/r4/model/extension/extension-definitions.xml
Exception in thread "main" java.lang.UnsupportedOperationException: HAPI-0269:
at org.hl7.fhir.r4.hapi.ctx.HapiWorkerContext.generateSnapshot(HapiWorkerContext.java:297)
at org.hl7.fhir.r4.elementmodel.ParserBase.getDefinition(ParserBase.java:145)
at org.hl7.fhir.r4.elementmodel.JsonParser.parse(JsonParser.java:132)
at org.hl7.fhir.r4.elementmodel.JsonParser.parse(JsonParser.java:113)
at com.example.FhirConverter.convertJsonToTurtle(FhirConverter.java:96)
at com.example.FhirConverter.main(FhirConverter.java:159)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment