- @Override
- public void serialize(
- Set<SignalServiceAddress> addresses, JsonGenerator json, SerializerProvider serializerProvider
- ) throws IOException {
- json.writeStartArray();
- for (var address : addresses) {
- json.writeStartObject();
- json.writeStringField("name", address.getNumber().get());
- json.writeStringField("uuid", address.getUuid().get().toString());
- json.writeEndObject();
+ private Optional<RecipientId> findByUuid(final UUID uuid) {
+ return recipients.entrySet()
+ .stream()
+ .filter(entry -> entry.getValue().getUuid().isPresent() && uuid.equals(entry.getValue()
+ .getUuid()
+ .get()))
+ .findFirst()
+ .map(Map.Entry::getKey);
+ }
+
+ private RecipientId nextId() {
+ return new RecipientId(++this.lastId);
+ }
+
+ private void save() {
+ // Write to memory first to prevent corrupting the file in case of serialization errors
+ try (var inMemoryOutput = new ByteArrayOutputStream()) {
+ var storage = new Storage(recipients.entrySet()
+ .stream()
+ .map(pair -> new Storage.Recipient(pair.getKey().getId(),
+ pair.getValue().getNumber().orNull(),
+ pair.getValue().getUuid().transform(UUID::toString).orNull()))
+ .collect(Collectors.toList()), lastId);
+ objectMapper.writeValue(inMemoryOutput, storage);
+
+ var input = new ByteArrayInputStream(inMemoryOutput.toByteArray());
+ try (var outputStream = new FileOutputStream(file)) {
+ input.transferTo(outputStream);
+ }
+ } catch (Exception e) {
+ logger.error("Error saving recipient store file: {}", e.getMessage());
+ }
+ }
+
+ public boolean isEmpty() {
+ synchronized (recipients) {
+ return recipients.isEmpty();
+ }
+ }
+
+ private static class Storage {
+
+ private List<Recipient> recipients;
+
+ private long lastId;
+
+ // For deserialization
+ private Storage() {
+ }
+
+ public Storage(final List<Recipient> recipients, final long lastId) {
+ this.recipients = recipients;
+ this.lastId = lastId;
+ }
+
+ public List<Recipient> getRecipients() {
+ return recipients;
+ }
+
+ public long getLastId() {
+ return lastId;
+ }
+
+ public static class Recipient {
+
+ private long id;
+ private String name;
+ private String uuid;
+
+ // For deserialization
+ private Recipient() {
+ }
+
+ public Recipient(final long id, final String name, final String uuid) {
+ this.id = id;
+ this.name = name;
+ this.uuid = uuid;
+ }
+
+ public long getId() {
+ return id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getUuid() {
+ return uuid;