Skip to content

Commit

Permalink
[form-api] fix sorting in DAGToObjectConverter
Browse files Browse the repository at this point in the history
  • Loading branch information
clickout committed Jul 27, 2023
1 parent 11714e3 commit 4863eff
Showing 1 changed file with 24 additions and 20 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package ai.stapi.graphoperations.dagtoobjectconverter;

import ai.stapi.graph.traversableGraphElements.TraversableEdge;
import ai.stapi.graph.traversableGraphElements.TraversableNode;
import ai.stapi.graphoperations.dagtoobjectconverter.exceptions.CannotConvertDAGToObject;
import ai.stapi.identity.UniqueIdentifier;
Expand All @@ -9,7 +10,7 @@
import java.util.*;

public class DAGToObjectConverter {

private static final String ID_FIELD_NAME = "id";

private final StructureSchemaFinder structureSchemaFinder;
Expand All @@ -26,7 +27,7 @@ private static class Convertor {

private final NodeSet nodeSet;
private final StructureSchemaFinder structureSchemaFinder;

public Convertor(StructureSchemaFinder structureSchemaFinder) {
this.nodeSet = new NodeSet();
this.structureSchemaFinder = structureSchemaFinder;
Expand All @@ -35,23 +36,26 @@ public Convertor(StructureSchemaFinder structureSchemaFinder) {
public Map<String, Object> convert(TraversableNode startNode) throws CannotConvertDAGToObject {
this.nodeSet.saveNode(startNode);
var object = this.convertNodeToObject(startNode);
startNode.getOutgoingEdges().forEach(edge -> {
var nodeTo = edge.getNodeTo();
if (this.nodeSet.hasNode(nodeTo)) {
throw CannotConvertDAGToObject.becauseItContainsCycle(nodeTo);
}
var fieldDefinition = this.structureSchemaFinder.getFieldDefinitionOrFallback(
startNode.getType(),
edge.getType()
);
if (fieldDefinition.isList()) {
var list = (List<Object>) object.computeIfAbsent(edge.getType(), key -> new ArrayList<>());
list.add(this.convert(nodeTo));
} else {
object.put(edge.getType(), this.convert(nodeTo));
}
});

startNode.getOutgoingEdges()
.stream()
.sorted(Comparator.comparingInt(TraversableEdge::hashCode))
.forEach(edge -> {
var nodeTo = edge.getNodeTo();
if (this.nodeSet.hasNode(nodeTo)) {
throw CannotConvertDAGToObject.becauseItContainsCycle(nodeTo);
}
var fieldDefinition = this.structureSchemaFinder.getFieldDefinitionOrFallback(
startNode.getType(),
edge.getType()
);
if (fieldDefinition.isList()) {
var list = (List<Object>) object.computeIfAbsent(edge.getType(), key -> new ArrayList<>());
list.add(this.convert(nodeTo));
} else {
object.put(edge.getType(), this.convert(nodeTo));
}
});

return object;
}

Expand Down Expand Up @@ -81,7 +85,7 @@ public void saveNode(TraversableNode node) {
.computeIfAbsent(node.getType(), key -> new HashSet<>())
.add(node.getId());
}

public boolean hasNode(TraversableNode node) {
var nodesByType = this.visitedNodes.get(node.getType());
return nodesByType != null && nodesByType.contains(node.getId());
Expand Down

0 comments on commit 4863eff

Please sign in to comment.