college/ws2012/P2P/uebungen/4/src/analysis/NetworkDumper.java

85 lines
1.7 KiB
Java

package analysis;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import node.Node;
public class NetworkDumper implements Runnable {
Node node = null;
private boolean running = true;
public NetworkDumper(Node n) {
this.node = n;
new Thread(this).start();
}
public String networkToDot(Map<String, List<String>> network) {
StringBuilder result = new StringBuilder(512);
result.append("graph g{\n");
Set<String> alreadyIn = new HashSet<String>();
for (Map.Entry<String, List<String>> entry : network.entrySet()) {
for (String s : entry.getValue()) {
String nodeA = getName(entry.getKey());
String nodeB = getName(s);
if (!alreadyIn.contains(nodeB + nodeA)) {
result.append("\t");
result.append(nodeA).append(" -- ").append(nodeB);
result.append(";\n");
alreadyIn.add(nodeA + nodeB);
}
}
}
result.append("}\n");
return result.toString();
}
private String getName(String s) {
return s.split(":")[1];
}
private void write(String s) {
try {
// Create file
FileWriter fstream = new FileWriter("graphs/"
+ System.currentTimeMillis() + ".dot");
BufferedWriter out = new BufferedWriter(fstream);
out.write(s);
// Close the output stream
out.close();
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
@Override
public void run() {
while (running) {
try {
node.gatherInformationOfNetwork();
// Wait 1s to broadcast to network
Thread.sleep(1000);
write(networkToDot(node.getNetwork()));
// Wait 10s for update
Thread.sleep(10000);
} catch (InterruptedException e) {
}
}
}
}