Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Publish binary resources #194

Merged
merged 3 commits into from
Jun 3, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,12 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.TimeZone;
import java.util.UUID;
import java.util.*;
import net.jimblackler.jsonschemafriend.GenerationException;
import net.jimblackler.jsonschemafriend.ValidationException;
import org.apache.http.HttpResponse;
Expand Down Expand Up @@ -98,6 +94,12 @@ public class PublishFhirResourcesCommand implements Runnable {
required = false)
String validateResource = "true";

@CommandLine.Option(
names = {"-c", "--composition"},
description = "path of the composition configuration file",
required = false)
String compositionFilePath;

@Override
public void run() {
long start = System.currentTimeMillis();
Expand All @@ -111,7 +113,11 @@ public void run() {
}
}
try {
publishResources();
if (compositionFilePath != null) {
ArrayList<JSONObject> resourceObjects = buildBinaries(compositionFilePath, projectFolder);
buildBundle(resourceObjects);
}
buildResources();
stateManagement();
} catch (IOException | ValidationException | GenerationException e) {
throw new RuntimeException(e);
Expand Down Expand Up @@ -171,32 +177,98 @@ void setProperties(Properties properties) {
}
}

void publishResources() throws IOException, ValidationException, GenerationException {
ArrayList<String> resourceFiles = getResourceFiles(projectFolder);
String getFileName(String name) {
if ((name.endsWith("Register")) || (name.endsWith("Profile"))) {
String regex = "([a-z])([A-Z]+)";
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

assuming here that we are always converting from camel case

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you add that to a docstring for this function?

String replacer = "$1_$2";
name = name.replaceAll(regex, replacer).toLowerCase();
}
if (name.startsWith("strings")) {
name = name + "_config.properties";
} else {
name = name + "_config.json";
}
return name;
}

HashMap<String, String> getDetails(JSONObject jsonObject) {
JSONObject focus = jsonObject.getJSONObject("focus");
String reference = focus.getString("reference");
JSONObject identifier = focus.getJSONObject("identifier");
String name = identifier.getString("value");

HashMap<String, String> map = new HashMap<>();
map.put("reference", reference);
map.put("name", getFileName(name));
return map;
}

String getBinaryContent(String fileName, String projectFolder) throws IOException {
String pathToFile;
if (fileName.contains("register")) {
pathToFile = projectFolder + "/registers/" + fileName;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

assuming we're always using this agreed on file/folder structure

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yea seems reasonable, on that note, should we to the validation checker (and later the app content from template creator) something to verify the repo follows file structure?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sure, created an issue here #195

} else if (fileName.contains("profile")) {
pathToFile = projectFolder + "/profiles/" + fileName;
} else if (fileName.startsWith("strings_")) {
pathToFile = projectFolder + "/translations/" + fileName;
} else {
pathToFile = projectFolder + "/" + fileName;
}

String fileContent = FctUtils.readFile(pathToFile).getContent();
return Base64.getEncoder().encodeToString(fileContent.getBytes(StandardCharsets.UTF_8));
}

ArrayList<JSONObject> buildBinaries(String compositionFilePath, String projectFolder)
throws IOException {
FctFile compositionFile = FctUtils.readFile(compositionFilePath);
JSONObject compositionResource = new JSONObject(compositionFile.getContent());
List<Map<String, String>> mapList = new ArrayList<>();
Map<String, String> detailsMap = new HashMap<>();
ArrayList<JSONObject> resourceObjects = new ArrayList<>();
boolean validateResourceBoolean = Boolean.parseBoolean(validateResource);

for (String f : resourceFiles) {
if (validateResourceBoolean) {
FctUtils.printInfo(String.format("Validating file \u001b[35m%s\u001b[0m", f));
ValidateFhirResourcesCommand.validateFhirResources(f);
} else {
FctUtils.printInfo(String.format("Publishing \u001b[35m%s\u001b[0m Without Validation", f));
if (compositionResource.has("section")) {
JSONArray compositionObjects = compositionResource.getJSONArray("section");

for (Object obj : compositionObjects) {
JSONObject jsonObject = new JSONObject(obj.toString());
if (jsonObject.has("section")) {
JSONArray section = jsonObject.getJSONArray("section");
for (Object subObj : section) {
JSONObject jo = new JSONObject(subObj.toString());
detailsMap = getDetails(jo);
}
} else {
detailsMap = getDetails(jsonObject);
}
mapList.add(detailsMap);
}

FctFile inputFile = FctUtils.readFile(f);
JSONObject resourceObject = buildResourceObject(inputFile);
resourceObjects.add(resourceObject);
}
for (Map<String, String> e : mapList) {
String filename = e.get("name");
String binaryContent = getBinaryContent(filename, projectFolder);
String contentType;

// build the bundle
JSONObject bundle = new JSONObject();
bundle.put("resourceType", "Bundle");
bundle.put("type", "transaction");
bundle.put("entry", resourceObjects);
FctUtils.printToConsole("Full Payload to POST: ");
FctUtils.printToConsole(bundle.toString());
if (filename.startsWith("strings_")) {
contentType = "text/plain";
} else {
contentType = "application/json";
}

JSONObject binaryResourceObject = new JSONObject();
binaryResourceObject.put("resourceType", "Binary");
binaryResourceObject.put("id", e.get("reference").substring(7));
binaryResourceObject.put("contentType", contentType);
binaryResourceObject.put("data", binaryContent);

JSONObject finalResourceObject = buildResourceObject(binaryResourceObject.toString());
resourceObjects.add(finalResourceObject);
}
}
return resourceObjects;
}

String getToken() {
if (accessToken == null || accessToken.isBlank()) {
if (clientId == null || clientId.isBlank()) {
throw new IllegalArgumentException(
Expand All @@ -217,7 +289,38 @@ void publishResources() throws IOException, ValidationException, GenerationExcep
accessToken =
getAccessToken(clientId, clientSecret, accessTokenUrl, grantType, username, password);
}
postRequest(bundle.toString(), accessToken);
return accessToken;
}

void buildBundle(ArrayList<JSONObject> resourceObjects) throws IOException {
JSONObject bundle = new JSONObject();
bundle.put("resourceType", "Bundle");
bundle.put("type", "transaction");
bundle.put("entry", resourceObjects);
FctUtils.printToConsole("Full Payload to POST: ");
FctUtils.printToConsole(bundle.toString());

postRequest(bundle.toString(), getToken());
}

void buildResources() throws IOException, ValidationException, GenerationException {
ArrayList<String> resourceFiles = getResourceFiles(projectFolder);
ArrayList<JSONObject> resourceObjects = new ArrayList<>();
boolean validateResourceBoolean = Boolean.parseBoolean(validateResource);

for (String f : resourceFiles) {
if (validateResourceBoolean) {
FctUtils.printInfo(String.format("Validating file \u001b[35m%s\u001b[0m", f));
ValidateFhirResourcesCommand.validateFhirResources(f);
} else {
FctUtils.printInfo(String.format("Publishing \u001b[35m%s\u001b[0m Without Validation", f));
}

FctFile inputFile = FctUtils.readFile(f);
JSONObject resourceObject = buildResourceObject(inputFile.getContent());
resourceObjects.add(resourceObject);
}
buildBundle(resourceObjects);
}

static ArrayList<String> getResourceFiles(String pathToFolder) throws IOException {
Expand Down Expand Up @@ -259,8 +362,8 @@ private static void addFhirResource(String filePath, List<String> filesArray) {
}
}

JSONObject buildResourceObject(FctFile inputFile) {
JSONObject resource = new JSONObject(inputFile.getContent());
JSONObject buildResourceObject(String fileContent) {
JSONObject resource = new JSONObject(fileContent);
String resourceType = null;
String resourceID;
if (resource.has("resourceType")) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import net.jimblackler.jsonschemafriend.GenerationException;
import net.jimblackler.jsonschemafriend.ValidationException;
import org.json.JSONObject;
Expand Down Expand Up @@ -89,7 +90,8 @@ void testBuildResourceObject() throws IOException {
writer.close();

FctFile testFile = FctUtils.readFile(resourceFile.toString());
JSONObject resourceObject = publishFhirResourcesCommand.buildResourceObject(testFile);
JSONObject resourceObject =
publishFhirResourcesCommand.buildResourceObject(testFile.getContent());

// assert that object has request
assertEquals(
Expand Down Expand Up @@ -127,8 +129,8 @@ void testPublishResourcesValidationFalse()
doNothing()
.when(mockPublishFhirResourcesCommand)
.postRequest(Mockito.anyString(), Mockito.anyString());
doCallRealMethod().when(mockPublishFhirResourcesCommand).publishResources();
mockPublishFhirResourcesCommand.publishResources();
doCallRealMethod().when(mockPublishFhirResourcesCommand).buildResources();
mockPublishFhirResourcesCommand.buildResources();
}
System.setOut(System.out);
String printedOutput = outputStream.toString().trim();
Expand Down Expand Up @@ -156,11 +158,124 @@ void testPublishResourcesValidationTrue()
doNothing()
.when(mockPublishFhirResourcesCommand)
.postRequest(Mockito.anyString(), Mockito.anyString());
doCallRealMethod().when(mockPublishFhirResourcesCommand).publishResources();
mockPublishFhirResourcesCommand.publishResources();
doCallRealMethod().when(mockPublishFhirResourcesCommand).buildResources();
mockPublishFhirResourcesCommand.buildResources();
}
System.setOut(System.out);
String printedOutput = outputStream.toString().trim();
assertTrue(printedOutput.contains("Validating file"));
}

@Test
void testGetFileName() {
String profileFile = "householdProfile";
assertEquals(
publishFhirResourcesCommand.getFileName(profileFile), "household_profile_config.json");

String registerFile = "sickChildRegister";
assertEquals(
publishFhirResourcesCommand.getFileName(registerFile), "sick_child_register_config.json");

String translationFile = "strings_fr";
assertEquals(
publishFhirResourcesCommand.getFileName(translationFile), "strings_fr_config.properties");

String basicFile = "navigation";
assertEquals(publishFhirResourcesCommand.getFileName(basicFile), "navigation_config.json");
}

@Test
void testGetDetails() {
String obj =
"{"
+ "\n \"title\": \"PNC register configuration\","
+ "\n \"focus\": {"
+ "\n \"reference\": \"Binary/9aa6bbb6-df76-42a4-bdbe-72dc197378ca\","
+ "\n \"identifier\": {"
+ "\n \"value\": \"pncRegister\""
+ "\n }}}";
JSONObject testObject = new JSONObject(obj);

HashMap<String, String> result = new HashMap<>();
result.put("reference", "Binary/9aa6bbb6-df76-42a4-bdbe-72dc197378ca");
result.put("name", "pnc_register_config.json");
assertEquals(publishFhirResourcesCommand.getDetails(testObject), result);
}

@Test
void testGetBinaryContent() throws IOException {
String filename = "sample.json";
Path testFolder = Files.createDirectory(tempDirectory.resolve("testBinaryFolder"));
Path resourceFile = Files.createFile(testFolder.resolve(filename));
String sampleResource =
"{\"appId\":\"testApp\",\"configType\":\"application\",\"theme\":\"DEFAULT\",\"appTitle\":\"TestApp\"}";
FileWriter writer = new FileWriter(String.valueOf(resourceFile));
writer.write(sampleResource);
writer.flush();
writer.close();

String actualResult =
publishFhirResourcesCommand.getBinaryContent(filename, String.valueOf(testFolder));
String expectedResult =
"eyJhcHBJZCI6InRlc3RBcHAiLCJjb25maWdUeXBlIjoiYXBwbGljYXRpb24iLCJ0aGVtZSI6IkRFRkFVTFQiLCJhcHBUaXRsZSI6IlRlc3RBcHAifQo=";
assertEquals(expectedResult, actualResult);
}

@Test
void testPublishBinaries() throws IOException {
Path testFolder = Files.createDirectory(tempDirectory.resolve("testPublishBinaryFolder"));
Path compositionFile = Files.createFile(testFolder.resolve("composition_config.json"));
Path applicationFile = Files.createFile(testFolder.resolve("application_config.json"));
Path profilesFolder = Files.createDirectory(testFolder.resolve("profiles"));
Path householdProfile =
Files.createFile(profilesFolder.resolve("household_profile_config.json"));
Path registersFolder = Files.createDirectory(testFolder.resolve("registers"));
Path ancRegister = Files.createFile(registersFolder.resolve("anc_register_config.json"));

String compositionString =
"{\"resourceType\":\"Composition\",\"id\":\"bf131f26-5c94-4bd2-9c88-bfc673dcd27d\",\"section\":[{\"title\":\"Application configuration\",\"focus\":{\"reference\":\"Binary/98cc3379-454c-4820-bec3-06c1e0aee45e\",\"identifier\":{\"value\":\"application\"}}},{\"title\":\"Register configurations\",\"section\":[{\"title\":\"ANC register configuration\",\"focus\":{\"reference\":\"Binary/5321c50d-fd84-45ba-a1a9-7424c8f9e1fc\",\"identifier\":{\"value\":\"ancRegister\"}}}]},{\"title\":\"Profile configurations\",\"section\":[{\"title\":\"Household profile configuration\",\"focus\":{\"reference\":\"Binary/64c10d9b-ac39-4b85-8d00-f82e8f9f2211\",\"identifier\":{\"value\":\"householdProfile\"}}}]}]}";
String applicationString =
"{\"appId\":\"test\",\"configType\":\"application\",\"theme\":\"DEFAULT\",\"appTitle\":\"TestApp\",\"useDarkTheme\":false}";
String householdProfileString =
"{\"appId\":\"test\",\"configType\":\"profile\",\"id\":\"householdProfile\",\"fhirResource\":{\"baseResource\":{\"resource\":\"Group\"}}}";
String ancRegisterString =
"{\"appId\":\"test\",\"configType\":\"register\",\"id\":\"ancRegister\",\"fhirResource\":{\"baseResource\":{\"resource\":\"Patient\"}}}";

FileWriter writer = new FileWriter(String.valueOf(compositionFile));
writer.write(compositionString);
writer.flush();
writer = new FileWriter(String.valueOf(applicationFile));
writer.write(applicationString);
writer.flush();
writer = new FileWriter(String.valueOf(householdProfile));
writer.write(householdProfileString);
writer.flush();
writer = new FileWriter(String.valueOf(ancRegister));
writer.write(ancRegisterString);
writer.flush();
writer.close();

ArrayList<JSONObject> resources =
publishFhirResourcesCommand.buildBinaries(
String.valueOf(compositionFile), String.valueOf(testFolder));
assertEquals(3, resources.size());
assertEquals(
resources.get(0).getJSONObject("request").getString("url"),
"Binary/98cc3379-454c-4820-bec3-06c1e0aee45e");
assertTrue(
resources
.get(1)
.getJSONObject("resource")
.getString("data")
.startsWith("eyJhcHBJZCI6InRlc3Qi"));
assertEquals(
resources
.get(2)
.getJSONObject("resource")
.getJSONObject("meta")
.getJSONArray("tag")
.getJSONObject(0)
.getString("code"),
"2.3.4-SNAPSHOT");
}
}
Loading