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

com.geotab.model.serialization.serdes.DefectDeserializer Maven / Gradle / Ivy

package com.geotab.model.serialization.serdes;

import static com.geotab.util.Util.listOf;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.geotab.model.entity.group.Defect;
import com.geotab.model.entity.group.DefectSeverity;
import java.io.IOException;
import java.util.Iterator;

public class DefectDeserializer extends JsonDeserializer {

  @Override
  public Defect deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException {
    ObjectCodec oc = jsonParser.getCodec();
    JsonNode node = oc.readTree(jsonParser);
    return deserializeWithChildren(node);
  }

  public static Defect deserializeWithChildren(JsonNode node) {
    if (node == null) return null;
    Defect defect = DefectDeserializer.buildDefect(node);
    if (DefectDeserializer.hasChildren(node)) {
      addDescendants(node.get("children").elements(), defect);
    }
    return defect;
  }

  private static void addDescendants(Iterator children, Defect parent) {
    while (children.hasNext()) {
      JsonNode child = children.next();

      Defect defect = buildDefect(child);
      if (parent.getChildren() == null) parent.setChildren(listOf());
      parent.getChildren().add(defect);

      if (hasChildren(child)) {
        addDescendants(child.get("children").elements(), defect);
      }
    }
  }

  private static boolean hasChildren(JsonNode node) {
    if (node.get("children") == null) return false;
    Iterator grandChildren = node.get("children").elements();
    return grandChildren.hasNext();
  }

  private static Defect buildDefect(JsonNode node) {
    String id = node.get("id") != null ? node.get("id").textValue() : null;
    String name = node.get("name") != null ? node.get("name").textValue() : null;
    String severity = node.get("severity") != null ? node.get("severity").textValue() : null;
    String comments = node.get("comments") != null ? node.get("comments").textValue() : null;
    String reference = node.get("reference") != null ? node.get("reference").textValue() : null;
    Boolean isDefectList = node.get("isDefectList") != null ? node.get("isDefectList").booleanValue() : null;
    return Defect.defectBuilder().id(id).name(name).severity(DefectSeverity.findOrDefault(severity))
        .comments(comments).reference(reference).isDefectList(isDefectList).isGlobalReportingGroup(null).build();
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy