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