001package org.hl7.fhir.convertors.misc;
002
003import java.io.File;
004import java.io.FileInputStream;
005import java.io.FileNotFoundException;
006import java.io.FileOutputStream;
007import java.io.IOException;
008import java.nio.charset.StandardCharsets;
009import java.util.Date;
010import java.util.HashSet;
011import java.util.Set;
012
013import org.hl7.fhir.convertors.factory.VersionConvertorFactory_30_50;
014import org.hl7.fhir.convertors.factory.VersionConvertorFactory_40_50;
015import org.hl7.fhir.exceptions.FHIRFormatError;
016import org.hl7.fhir.r4b.formats.JsonParser;
017import org.hl7.fhir.r4b.model.Bundle;
018import org.hl7.fhir.r4b.model.Bundle.BundleEntryComponent;
019import org.hl7.fhir.utilities.TextFile;
020import org.hl7.fhir.utilities.Utilities;
021import org.hl7.fhir.utilities.json.JsonTrackingParser;
022
023import com.google.gson.JsonArray;
024import com.google.gson.JsonObject;
025
026import org.hl7.fhir.r4b.model.SearchParameter;
027import org.hl7.fhir.r4b.utils.NPMPackageGenerator;
028import org.hl7.fhir.r4b.utils.NPMPackageGenerator.Category;
029
030public class ExamplesPackageBuilder {
031
032  public static void main(String[] args) throws FHIRFormatError, FileNotFoundException, IOException {
033    new ExamplesPackageBuilder().process(args[0]);
034
035  }
036
037  private void process(String source) throws FHIRFormatError, FileNotFoundException, IOException {
038    Set<String> set = new HashSet<>();
039    for (File f : new File(source).listFiles()) {
040      if (f.getName().endsWith(".json")) {
041        JsonObject obj = JsonTrackingParser.parseJson(new FileInputStream(f));
042        if (obj.has("resourceType") && obj.has("id")) {
043          String type = obj.get("resourceType").getAsString();
044          String id = obj.get("id").getAsString();
045          byte[] content = TextFile.fileToBytes(f);
046          if (type.equals("ConceptMap")) {
047            System.out.println("convert "+f.getName());
048            content = r5ToR4B(content);
049            TextFile.bytesToFile(content, f);
050          }
051//          TextFile.bytesToFile(content, Utilities.path(dest2, type+"-"+id+".json"));
052//          if (!set.contains(type+"/"+id)) {
053//            set.add(type+"/"+id);
054//            pck.addFile(Category.RESOURCE, type+"-"+id+".json", content);
055//          }
056        }
057      }
058    }
059//    pck.finish();
060//    
061  }
062
063  private byte[] r5ToR4B(byte[] content) throws FHIRFormatError, IOException {
064    try {
065      org.hl7.fhir.r5.model.Resource r5 = new org.hl7.fhir.r5.formats.JsonParser().parse(content);
066      org.hl7.fhir.r4.model.Resource r4 = VersionConvertorFactory_40_50.convertResource(r5);
067      return new org.hl7.fhir.r4.formats.JsonParser().composeBytes(r4);
068    } catch (Exception e) {
069      System.out.println("  .. failed: "+e.getMessage());
070      return content;
071    }
072  }
073
074}