private static void writeRelationships(
     final Map<Trace, Integer> traceIds, final JsonGenerator generator) throws IOException {
   generator.writeArrayFieldStart(JsonTraceCodec.RELATIONSHIPS);
   for (Map.Entry<Trace, Integer> entry : traceIds.entrySet()) {
     final Trace trace = entry.getKey();
     final int fromId = entry.getValue();
     for (Related<Trace> related : trace.getRelated()) {
       final int toId = traceIds.get(related.getRelated());
       final String relationship = related.getRelationship();
       generator.writeStartObject();
       generator.writeStringField(JsonTraceCodec.RELATIONSHIP_RELATIONSHIP, relationship);
       generator.writeNumberField(JsonTraceCodec.RELATIONSHIP_FROM, fromId);
       generator.writeNumberField(JsonTraceCodec.RELATIONSHIP_TO, toId);
       generator.writeEndObject();
     }
   }
   generator.writeEndArray();
 }
  private static Map<Trace, Integer> buildTraceIdMap(final Trace root) {
    final Map<Trace, Integer> traceIds = new HashMap<Trace, Integer>();
    final ArrayDeque<Trace> stack = new ArrayDeque<Trace>();
    stack.push(root);

    int counter = 0;
    while (!stack.isEmpty()) {
      final Trace trace = stack.pop();
      traceIds.put(trace, counter++);
      for (Related<Trace> related : trace.getRelated()) {
        final Trace relatedTrace = related.getRelated();
        if (!traceIds.containsKey(relatedTrace)) {
          stack.push(related.getRelated());
        }
      }
    }

    return traceIds;
  }