package csx55.overlay.dijkstra; import java.util.HashMap; import java.util.ArrayList; import csx55.overlay.wireformats.LinkWeights; /** * This class is used by the MessagingNodes to cache their routes to every other node in the * overlay. After the nodes receive link weights from the registry using the send-overlay-link-weights * command, it creates a RoutingCache object, which creates an instance of the ShortestPath class. * It is used to send messages to nodes in the overlay when the task-initiate message is received. */ public class RoutingCache { private HashMap msgRoutes;//stores the peer info and a list of the nodes required to get to that node private String ip; private int port; private ArrayList allConnections; public RoutingCache(LinkWeights weights, String ip, int port) { this.ip = ip; this.port = port; this.msgRoutes = new HashMap<>(); allConnections = new ArrayList<>(); //create a ShortestPath object ShortestPath sp = new ShortestPath(); //loop through each link weights and split it by spaces; each link weight is in the format: ip:port ip:port weight //if the node does not exist in the set, add it; this accounts for all nodes in the overlay for (String link: weights.getLinks()) { String[] splitLink = link.split("\\s+"); if (!allConnections.contains(splitLink[0])) allConnections.add(splitLink[0]); if (!allConnections.contains(splitLink[1])) allConnections.add(splitLink[1]); } //pass a reference to the msgRoutes hashmap, along with the node's info and a list of all nodes in the overlay to the ShortestPath's createSP method sp.createSP(msgRoutes, weights, ip + ":" + port, allConnections); //remove itself from the list of allConnections so it is not chosen at random when sending messages allConnections.remove(ip + ":" + port); } /** * Called by the messaging node using print-shortest-path to print the shortest * path from this node to every other node. The format will be: ip:port--weight--ip:port. * There could be multiple nodes in between the start node and the sink node, forming a * chain of nodes and their edge weights between the dashes. */ public void printSP(LinkWeights weights) { for (HashMap.Entry node: msgRoutes.entrySet()) { String curr = ip + ":" + port; String str = curr; for (String neighbor: node.getValue()) { str += "--"; str += weights.getWeight(curr, neighbor); str += "--"; str += neighbor; curr = neighbor; } System.out.println(str); } } //returns the cached route for a node public String[] getMsgRoute(String endpoint) throws NullPointerException { return msgRoutes.get(endpoint); } //returns the size of allConnections public int size() { return allConnections.size(); } //returns the node information at a specified index public String get(int index) { return allConnections.get(index); } }