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, boolean noXhtml) { 019 ByteArrayOutputStream baos = null; 020 byte[] byteArray = null; 021 baos = new ByteArrayOutputStream(); 022 try { 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 if (noXhtml) { 031 parser.setSuppressXhtml("Narrative removed"); 032 } 033 parser.compose(baos, resource); 034 baos.close(); 035 byteArray = baos.toByteArray(); 036 baos.close(); 037 } catch (Exception e) { 038 try { 039 baos.close(); 040 } catch (Exception ex) { 041 throw new EFhirClientException(0, "Error closing output stream", ex); 042 } 043 throw new EFhirClientException(0, "Error converting output stream to byte array", e); 044 } 045 return byteArray; 046 } 047 048 public static byte[] encodeFormSubmission(Map<String, String> parameters, String resourceName, Resource resource, String boundary) throws IOException { 049 ByteArrayOutputStream b = new ByteArrayOutputStream(); 050 OutputStreamWriter w = new OutputStreamWriter(b, StandardCharsets.UTF_8); 051 for (String name : parameters.keySet()) { 052 w.write("--"); 053 w.write(boundary); 054 w.write("\r\nContent-Disposition: form-data; name=\"" + name + "\"\r\n\r\n"); 055 w.write(parameters.get(name) + "\r\n"); 056 } 057 w.write("--"); 058 w.write(boundary); 059 w.write("\r\nContent-Disposition: form-data; name=\"" + resourceName + "\"\r\n\r\n"); 060 w.close(); 061 JsonParser json = new JsonParser(); 062 json.setOutputStyle(IParser.OutputStyle.NORMAL); 063 json.compose(b, resource); 064 b.close(); 065 w = new OutputStreamWriter(b, StandardCharsets.UTF_8); 066 w.write("\r\n--"); 067 w.write(boundary); 068 w.write("--"); 069 w.close(); 070 return b.toByteArray(); 071 } 072}