mirror of
https://github.com/AsamK/signal-cli
synced 2025-09-02 04:20:38 +00:00
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:
parent
188149a51a
commit
d36d32b600
3 changed files with 31 additions and 7 deletions
|
@ -47,17 +47,15 @@ public class GetAttachmentCommand implements JsonRpcLocalCommand {
|
|||
final var id = ns.getString("id");
|
||||
|
||||
try(InputStream attachment = m.retrieveAttachment(id)) {
|
||||
|
||||
final var bytes = attachment.readAllBytes();
|
||||
final var base64 = Base64.getEncoder().encodeToString(bytes);
|
||||
|
||||
if (outputWriter instanceof PlainTextWriter writer) {
|
||||
final var bytes = attachment.readAllBytes();
|
||||
final var base64 = Base64.getEncoder().encodeToString(bytes);
|
||||
writer.println(base64);
|
||||
} else if (outputWriter instanceof JsonWriter writer) {
|
||||
writer.write(new JsonAttachmentData(base64));
|
||||
writer.write(new JsonAttachmentData(attachment));
|
||||
}
|
||||
} 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) {
|
||||
throw new UnexpectedErrorException("An error occurred reading attachment: " + id, ex);
|
||||
}
|
||||
|
|
|
@ -1,3 +1,9 @@
|
|||
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
|
||||
) {}
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue