001package org.hl7.fhir.r5.utils.client.network;
002
003import org.hl7.fhir.r5.formats.IParser;
004import org.hl7.fhir.r5.formats.JsonParser;
005import org.hl7.fhir.r5.formats.XmlParser;
006import org.hl7.fhir.r5.model.Bundle;
007import org.hl7.fhir.r5.model.Resource;
008import org.hl7.fhir.r5.utils.client.EFhirClientException;
009
010import java.io.ByteArrayOutputStream;
011import java.io.IOException;
012import java.io.OutputStreamWriter;
013import java.nio.charset.StandardCharsets;
014import java.util.Map;
015
016public class ByteUtils {
017
018  public static <T extends Resource> byte[] resourceToByteArray(T resource, boolean pretty, boolean isJson) {
019    ByteArrayOutputStream baos = null;
020    byte[] byteArray = null;
021    try {
022      baos = new ByteArrayOutputStream();
023      IParser parser = null;
024      if (isJson) {
025        parser = new JsonParser();
026      } else {
027        parser = new XmlParser();
028      }
029      parser.setOutputStyle(pretty ? IParser.OutputStyle.PRETTY : IParser.OutputStyle.NORMAL);
030      parser.compose(baos, resource);
031      baos.close();
032      byteArray = baos.toByteArray();
033      baos.close();
034    } catch (Exception e) {
035      try {
036        baos.close();
037      } catch (Exception ex) {
038        throw new EFhirClientException("Error closing output stream", ex);
039      }
040      throw new EFhirClientException("Error converting output stream to byte array", e);
041    }
042    return byteArray;
043  }
044
045  public static byte[] encodeFormSubmission(Map<String, String> parameters, String resourceName, Resource resource, 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}