001package org.hl7.fhir.r4.utils.client.network;
002
003import java.io.ByteArrayOutputStream;
004import java.io.IOException;
005import java.io.OutputStreamWriter;
006import java.nio.charset.StandardCharsets;
007import java.util.Map;
008
009import org.hl7.fhir.r4.formats.IParser;
010import org.hl7.fhir.r4.formats.JsonParser;
011import org.hl7.fhir.r4.formats.XmlParser;
012import org.hl7.fhir.r4.model.Resource;
013import org.hl7.fhir.r4.utils.client.EFhirClientException;
014
015public class ByteUtils {
016
017  public static <T extends Resource> byte[] resourceToByteArray(T resource, boolean pretty, boolean isJson) {
018    ByteArrayOutputStream baos = null;
019    byte[] byteArray = null;
020    try {
021      baos = new ByteArrayOutputStream();
022      IParser parser = null;
023      if (isJson) {
024        parser = new JsonParser();
025      } else {
026        parser = new XmlParser();
027      }
028      parser.setOutputStyle(pretty ? IParser.OutputStyle.PRETTY : IParser.OutputStyle.NORMAL);
029      parser.compose(baos, resource);
030      baos.close();
031      byteArray = baos.toByteArray();
032      baos.close();
033    } catch (Exception e) {
034      try {
035        baos.close();
036      } catch (Exception ex) {
037        throw new EFhirClientException("Error closing output stream", ex);
038      }
039      throw new EFhirClientException("Error converting output stream to byte array", e);
040    }
041    return byteArray;
042  }
043
044  public static byte[] encodeFormSubmission(Map<String, String> parameters, String resourceName, Resource resource,
045      String boundary) throws IOException {
046    ByteArrayOutputStream b = new ByteArrayOutputStream();
047    OutputStreamWriter w = new OutputStreamWriter(b, StandardCharsets.UTF_8);
048    for (String name : parameters.keySet()) {
049      w.write("--");
050      w.write(boundary);
051      w.write("\r\nContent-Disposition: form-data; name=\"" + name + "\"\r\n\r\n");
052      w.write(parameters.get(name) + "\r\n");
053    }
054    w.write("--");
055    w.write(boundary);
056    w.write("\r\nContent-Disposition: form-data; name=\"" + resourceName + "\"\r\n\r\n");
057    w.close();
058    JsonParser json = new JsonParser();
059    json.setOutputStyle(IParser.OutputStyle.NORMAL);
060    json.compose(b, resource);
061    b.close();
062    w = new OutputStreamWriter(b, StandardCharsets.UTF_8);
063    w.write("\r\n--");
064    w.write(boundary);
065    w.write("--");
066    w.close();
067    return b.toByteArray();
068  }
069}