-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraph.java
More file actions
103 lines (83 loc) · 3.13 KB
/
Copy pathGraph.java
File metadata and controls
103 lines (83 loc) · 3.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package test;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import java.util.logging.Level;
public class Graph extends ArrayList<Node> {
private static final Logger LOGGER = Logger.getLogger(Graph.class.getName());
public boolean hasCycles() {
Set<Node> visited = new HashSet<>();
Set<Node> recursionStack = new HashSet<>();
for (Node node : this) {
if (hasCycle(node, visited, recursionStack)) {
return true;
}
}
return false;
}
private boolean hasCycle(Node node, Set<Node> visited, Set<Node> recursionStack) {
if (recursionStack.contains(node)) {
return true;
}
if (visited.contains(node)) {
return false;
}
visited.add(node);
recursionStack.add(node);
for (Node neighbor : node.getEdges()) {
if (hasCycle(neighbor, visited, recursionStack)) {
return true;
}
}
recursionStack.remove(node);
return false;
}
public void createFromTopics() {
clear();
TopicManagerSingleton.TopicManager tm = TopicManagerSingleton.get();
if (tm == null) {
LOGGER.severe("TopicManager is null. Cannot create graph.");
return;
}
Collection<Topic> topics = tm.getTopics();
if (topics == null || topics.isEmpty()) {
LOGGER.warning("No topics found. Cannot create graph.");
return;
}
Map<String, Node> nodes = new HashMap<>();
for (Topic topic : topics) {
if (topic == null || topic.name == null) {
LOGGER.warning("Skipping null topic");
continue;
}
String topicNodeName = "T" + topic.name;
Node topicNode = nodes.computeIfAbsent(topicNodeName, k -> {
Node newNode = new Node(topicNodeName);
add(newNode);
return newNode;
});
for (Agent agent : topic.getSubs()) {
String agentNodeName = "A" + agent.getName();
Node agentNode = nodes.computeIfAbsent(agentNodeName, k -> {
Node newNode = new Node(agentNodeName);
add(newNode);
return newNode;
});
topicNode.addEdge(agentNode);
}
for (Agent agent : topic.getPubs()) {
String agentNodeName = "A" + agent.getName();
Node agentNode = nodes.computeIfAbsent(agentNodeName, k -> {
Node newNode = new Node(agentNodeName);
add(newNode);
return newNode;
});
agentNode.addEdge(topicNode);
}
}
}
}