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

com.geotab.model.serialization.DefectGroupChildrenDeserializer Maven / Gradle / Ivy

package com.geotab.model.serialization;

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.enumeration.DefectSeverity;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class DefectGroupChildrenDeserializer extends JsonDeserializer> {

  @Override
  public List deserialize(JsonParser jsonParser, DeserializationContext context)
      throws IOException {
    List defects = new ArrayList<>();
    ObjectCodec oc = jsonParser.getCodec();
    JsonNode node = oc.readTree(jsonParser);
    Iterator elements = node.elements();

    while (elements.hasNext()) {
      JsonNode nextNode = elements.next();
      Defect defect = buildDefect(nextNode);

      if (hasChildren(nextNode)) {
        addDescendants(nextNode.get("children").elements(), defect);
      }
      defects.add(defect);
    }
    return defects;
  }

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

      Defect defect = buildDefect(child);
      parent.getChildren().add(defect);

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

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

  private 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;

    return Defect.defectBuilder()
        .id(id)
        .name(name)
        .severity(DefectSeverity.findOrDefault(severity))
        .comments(comments)
        .reference(reference)
        .build();
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy