All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.adgear.anoa.read.ProtobufMapReader Maven / Gradle / Ivy

package com.adgear.anoa.read;

import com.google.protobuf.Descriptors;
import com.google.protobuf.Message;

import com.adgear.anoa.AnoaJacksonTypeException;
import com.fasterxml.jackson.core.JsonParser;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

class ProtobufMapReader extends AbstractReader> {

  final Descriptors.FieldDescriptor keyDescriptor;
  final Descriptors.FieldDescriptor valueDescriptor;
  final Message.Builder mapEntryBuilder;
  final MapReader mapReader;

  ProtobufMapReader(Descriptors.FieldDescriptor keyDescriptor,
                    Descriptors.FieldDescriptor valueDescriptor,
                    Message.Builder mapEntryBuilder,
                    AbstractReader valueElementReader) {
    this.mapReader = new MapReader(valueElementReader);
    this.mapEntryBuilder = mapEntryBuilder.clone().clear();
    this.keyDescriptor = keyDescriptor;
    this.valueDescriptor = valueDescriptor;
  }

  private List toEntryList(Map map) {
    ArrayList result = new ArrayList<>();
    if (map != null) {
      for (Map.Entry entry : map.entrySet()) {
        mapEntryBuilder.clear();
        mapEntryBuilder.setField(keyDescriptor, entry.getKey());
        if (valueDescriptor.isRepeated()) {
          for (Object element : (Iterable) entry.getValue()) {
            mapEntryBuilder.addRepeatedField(valueDescriptor, element);
          }
        } else {
          mapEntryBuilder.setField(valueDescriptor, entry.getValue());
        }
        result.add(mapEntryBuilder.build());
      }
    }
    return result;
  }

  @Override
  protected List read(JsonParser jacksonParser) throws IOException {
    return toEntryList(mapReader.read(jacksonParser));
  }

  @Override
  protected List readStrict(JsonParser jacksonParser)
      throws AnoaJacksonTypeException, IOException {
    return toEntryList(mapReader.readStrict(jacksonParser));
  }
}