001package org.hl7.fhir.dstu3.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.dstu3.formats.IParser;
010import org.hl7.fhir.dstu3.formats.JsonParser;
011import org.hl7.fhir.dstu3.formats.XmlParser;
012import org.hl7.fhir.dstu3.model.Resource;
013import org.hl7.fhir.dstu3.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, String boundary) throws IOException {
045    ByteArrayOutputStream b = new ByteArrayOutputStream();
046    OutputStreamWriter w = new OutputStreamWriter(b, StandardCharsets.UTF_8);
047    for (String name : parameters.keySet()) {
048      w.write("--");
049      w.write(boundary);
050      w.write("\r\nContent-Disposition: form-data; name=\"" + name + "\"\r\n\r\n");
051      w.write(parameters.get(name) + "\r\n");
052    }
053    w.write("--");
054    w.write(boundary);
055    w.write("\r\nContent-Disposition: form-data; name=\"" + resourceName + "\"\r\n\r\n");
056    w.close();
057    JsonParser json = new JsonParser();
058    json.setOutputStyle(IParser.OutputStyle.NORMAL);
059    json.compose(b, resource);
060    b.close();
061    w = new OutputStreamWriter(b, StandardCharsets.UTF_8);
062    w.write("\r\n--");
063    w.write(boundary);
064    w.write("--");
065    w.close();
066    return b.toByteArray();
067  }
068}