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