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