|
| 1 | +package ca.uhn.fhir.jpa.packages; |
| 2 | + |
| 3 | +import ca.uhn.fhir.context.FhirContext; |
| 4 | +import ca.uhn.fhir.util.BundleBuilder; |
| 5 | +import org.hl7.fhir.instance.model.api.IBaseBundle; |
| 6 | +import org.hl7.fhir.instance.model.api.IBaseResource; |
| 7 | +import org.hl7.fhir.utilities.npm.NpmPackage; |
| 8 | +import org.jetbrains.annotations.NotNull; |
| 9 | +import org.springframework.stereotype.Service; |
| 10 | + |
| 11 | +import java.io.ByteArrayInputStream; |
| 12 | +import java.io.IOException; |
| 13 | +import java.util.stream.Collectors; |
| 14 | +import java.util.*; |
| 15 | + |
| 16 | +@Service |
| 17 | +public class AdditionalResourcesParser { |
| 18 | + |
| 19 | + public IBaseBundle collectAdditionalResources( |
| 20 | + Set<String> additionalResources, PackageInstallationSpec packageInstallationSpec, FhirContext fhirContext) { |
| 21 | + NpmPackage npmPackage; |
| 22 | + try { |
| 23 | + npmPackage = NpmPackage.fromPackage(new ByteArrayInputStream(packageInstallationSpec.getPackageContents())); |
| 24 | + } catch (IOException e) { |
| 25 | + throw new RuntimeException(e); |
| 26 | + } |
| 27 | + var resources = getAdditionalResources(additionalResources, npmPackage, fhirContext); |
| 28 | + |
| 29 | + var bundleBuilder = new BundleBuilder(fhirContext); |
| 30 | + resources.forEach(bundleBuilder::addTransactionUpdateEntry); |
| 31 | + return bundleBuilder.getBundle(); |
| 32 | + } |
| 33 | + |
| 34 | + @NotNull |
| 35 | + public List<IBaseResource> getAdditionalResources( |
| 36 | + Set<String> folderNames, NpmPackage npmPackage, FhirContext fhirContext) { |
| 37 | + |
| 38 | + var npmFolders = folderNames.stream() |
| 39 | + .map(name -> npmPackage.getFolders().get(name)) |
| 40 | + .filter(Objects::nonNull) |
| 41 | + .collect(Collectors.toList()); |
| 42 | + |
| 43 | + var resources = new LinkedList<IBaseResource>(); |
| 44 | + for (var folder : npmFolders) { |
| 45 | + List<String> fileNames; |
| 46 | + try { |
| 47 | + fileNames = folder.getTypes().values().stream() |
| 48 | + .flatMap(Collection::stream) |
| 49 | + .collect(Collectors.toList()); |
| 50 | + } catch (IOException e) { |
| 51 | + throw new RuntimeException(e.getMessage(), e); |
| 52 | + } |
| 53 | + |
| 54 | + resources.addAll(fileNames.stream() |
| 55 | + .map(fileName -> { |
| 56 | + try { |
| 57 | + return new String(folder.fetchFile(fileName)); |
| 58 | + } catch (IOException e) { |
| 59 | + throw new RuntimeException(e.getMessage(), e); |
| 60 | + } |
| 61 | + }) |
| 62 | + .map(fhirContext.newJsonParser().setSuppressNarratives(true)::parseResource) |
| 63 | + .collect(Collectors.toList())); |
| 64 | + } |
| 65 | + return resources; |
| 66 | + } |
| 67 | +} |
0 commit comments