1 package com.github.dexecutor.executor.graph;
2
3 import java.util.ArrayList;
4 import java.util.Collection;
5 import java.util.HashMap;
6 import java.util.LinkedHashSet;
7 import java.util.Map;
8 import java.util.Set;
9
10
11
12
13
14
15
16
17 public final class DefaultGraph<T extends Comparable<T>> implements Graph<T> {
18
19 private Map<T, Node<T>> nodes = new HashMap<T, Node<T>>();
20
21 public void addIndependent(T nodeValue) {
22 doAdd(nodeValue);
23 }
24
25 public void addDependency(final T evalFirstNode, final T evalLaterNode) {
26 Node<T> firstNode = doAdd(evalFirstNode);
27 Node<T> afterNode = doAdd(evalLaterNode);
28
29 if (!firstNode.equals(afterNode)) {
30 firstNode.addOutGoingNode(afterNode);
31 afterNode.addInComingNode(firstNode);
32 }
33 }
34
35 private Node<T> doAdd(final T nodeValue) {
36 Node<T> graphNode = null;
37 if (nodes.containsKey(nodeValue)) {
38 graphNode = nodes.get(nodeValue);
39 } else {
40 graphNode = createNode(nodeValue);
41 nodes.put(nodeValue, graphNode);
42 }
43 return graphNode;
44 }
45
46 private Node<T> createNode(final T value) {
47 Node<T> node = new Node<T>(value);
48 return node;
49 }
50
51 public Set<Node<T>> getInitialNodes() {
52 Set<Node<T>> initialNodes = new LinkedHashSet<Node<T>>();
53 Set<T> keys = nodes.keySet();
54 for (T key : keys) {
55 Node<T> node = nodes.get(key);
56 if (node.getInComingNodes().isEmpty()) {
57 initialNodes.add(node);
58 }
59 }
60 return initialNodes;
61 }
62
63 public int size() {
64 return nodes.size();
65 }
66
67 public Collection<Graph.Node<T>> allNodes() {
68 return new ArrayList<Graph.Node<T>>(this.nodes.values());
69 }
70
71 public Set<Graph.Node<T>> getLeafNodes() {
72 Set<Node<T>> leafNodes = new LinkedHashSet<Node<T>>();
73 Set<T> keys = nodes.keySet();
74 for (T key : keys) {
75 Node<T> node = nodes.get(key);
76 if (node.getOutGoingNodes().isEmpty()) {
77 leafNodes.add(node);
78 }
79 }
80 return leafNodes;
81 }
82 }