X-Git-Url: https://git.nmode.ca/signal-cli/blobdiff_plain/a4e22539a3d87262f43d399fbd79823c4dc2fde0..82cecfff85ef29e627d4238e3237222b492d5248:/src/main/java/org/asamk/signal/JsonThreadStore.java diff --git a/src/main/java/org/asamk/signal/JsonThreadStore.java b/src/main/java/org/asamk/signal/JsonThreadStore.java new file mode 100644 index 00000000..3a8eb830 --- /dev/null +++ b/src/main/java/org/asamk/signal/JsonThreadStore.java @@ -0,0 +1,56 @@ +package org.asamk.signal; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class JsonThreadStore { + @JsonProperty("threads") + @JsonSerialize(using = JsonThreadStore.MapToListSerializer.class) + @JsonDeserialize(using = ThreadsDeserializer.class) + private Map threads = new HashMap<>(); + + private static final ObjectMapper jsonProcessor = new ObjectMapper(); + + void updateThread(ThreadInfo thread) { + threads.put(thread.id, thread); + } + + ThreadInfo getThread(String id) { + return threads.get(id); + } + + List getThreads() { + return new ArrayList<>(threads.values()); + } + + public static class MapToListSerializer extends JsonSerializer> { + @Override + public void serialize(final Map value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException { + jgen.writeObject(value.values()); + } + } + + public static class ThreadsDeserializer extends JsonDeserializer> { + @Override + public Map deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { + Map threads = new HashMap<>(); + JsonNode node = jsonParser.getCodec().readTree(jsonParser); + for (JsonNode n : node) { + ThreadInfo t = jsonProcessor.treeToValue(n, ThreadInfo.class); + threads.put(t.id, t); + } + + return threads; + } + } +}