001package org.hl7.fhir.r4.utils;
002
003import java.io.File;
004import java.io.FileOutputStream;
005import java.io.FileNotFoundException;
006import java.io.IOException;
007import java.util.Arrays;
008import java.util.Set;
009import java.util.HashSet;
010
011import org.hl7.fhir.r4.formats.IParser.OutputStyle;
012import org.hl7.fhir.r4.formats.JsonParser;
013import org.hl7.fhir.r4.model.Resource;
014import org.hl7.fhir.r4.model.MetadataResource;
015import org.hl7.fhir.r4.model.Parameters;
016import org.hl7.fhir.utilities.TextFile;
017
018/**
019 * Used to take an overload dump from tx.fhir.org and turn it into a parameters resource
020 * 
021 * @author grahamegrieve
022 *
023 */
024public class ParametersBuilder {
025
026  public static void main(String[] args) throws FileNotFoundException, IOException {
027    new ParametersBuilder(args[0], args[1]).process(args[2]);
028  }
029
030
031
032  private String folder;
033  private String baseId;
034
035  protected ParametersBuilder(String folder, String baseId) {
036    super();
037    this.folder = folder;
038    this.baseId = baseId;
039  }
040
041  private void process(String output) throws FileNotFoundException, IOException {
042    Parameters p = new Parameters();
043    Set<String> ids = new HashSet<>();
044    for (File f : new File(folder).listFiles()) {
045      if (f.getName().startsWith(baseId)) {
046        if (f.getName().startsWith(baseId)) {
047          byte[] cnt = TextFile.fileToBytes(f);
048          cnt = shaveZeros(cnt); // bug in tx.fhir.org
049          MetadataResource r = (MetadataResource) new JsonParser().parse(cnt);
050          if (!ids.contains(r.getUrl()+"|"+r.getVersion())) {
051            ids.add(r.getUrl()+"|"+r.getVersion());
052            p.addParameter().setName("tx-resource").setResource(r);
053          }
054        }
055      }
056    }
057    new JsonParser().setOutputStyle(OutputStyle.PRETTY).compose(new FileOutputStream(output), p);
058  }
059
060  private byte[] shaveZeros(byte[] cnt) {
061    for (int i = 0; i < cnt.length; i++) {
062      if (cnt[i] == 0) {
063        return Arrays.copyOf(cnt, i-1);
064      }
065    }
066    return cnt;
067  }
068}