Use JSON serializer to serialize binary data

Serializing the stream is better for memory handling than
loading the whole thing into the file.
This commit is contained in:
cedb 2022-11-01 16:53:07 -04:00
parent 188149a51a
commit d36d32b600
3 changed files with 31 additions and 7 deletions

View file

@ -47,17 +47,15 @@ public class GetAttachmentCommand implements JsonRpcLocalCommand {
final var id = ns.getString("id"); final var id = ns.getString("id");
try(InputStream attachment = m.retrieveAttachment(id)) { try(InputStream attachment = m.retrieveAttachment(id)) {
if (outputWriter instanceof PlainTextWriter writer) {
final var bytes = attachment.readAllBytes(); final var bytes = attachment.readAllBytes();
final var base64 = Base64.getEncoder().encodeToString(bytes); final var base64 = Base64.getEncoder().encodeToString(bytes);
if (outputWriter instanceof PlainTextWriter writer) {
writer.println(base64); writer.println(base64);
} else if (outputWriter instanceof JsonWriter writer) { } else if (outputWriter instanceof JsonWriter writer) {
writer.write(new JsonAttachmentData(base64)); writer.write(new JsonAttachmentData(attachment));
} }
} catch (FileNotFoundException ex) { } catch (FileNotFoundException ex) {
throw new UserErrorException("Could not find attachment with ID: " + id); throw new UserErrorException("Could not find attachment with ID: " + id, ex);
} catch (IOException ex) { } catch (IOException ex) {
throw new UnexpectedErrorException("An error occurred reading attachment: " + id, ex); throw new UnexpectedErrorException("An error occurred reading attachment: " + id, ex);
} }

View file

@ -1,3 +1,9 @@
package org.asamk.signal.json; package org.asamk.signal.json;
public record JsonAttachmentData(String data) {} import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.io.InputStream;
public record JsonAttachmentData(
@JsonSerialize(using=JsonStreamSerializer.class) InputStream data
) {}

View file

@ -0,0 +1,20 @@
package org.asamk.signal.json;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.io.InputStream;
public class JsonStreamSerializer extends JsonSerializer<InputStream> {
@Override
public void serialize(
final InputStream value,
final JsonGenerator jsonGenerator,
final SerializerProvider serializers
) throws IOException {
jsonGenerator.writeBinary(value, -1);
}
}