123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- package classes.holonControlUnit;
- import classes.Holon;
- import classes.holonControlUnit.messages.Message;
- import classes.holonControlUnit.messages.NeighborhoodMsg;
- import java.util.ArrayList;
- import java.util.HashSet;
- import java.util.Set;
- import com.google.gson.Gson;
- /**
- * this class is responsable for communication between holons
- * @author Jonas
- *
- */
- public class CommunicationModule {
-
- private HolonControlUnit hcu;
- private Gson gson;
- public enum MessageType {
- ORDER, NEIGHBORHOOD
- }
-
- public CommunicationModule(HolonControlUnit owner) {
- this.hcu = owner;
- this.gson = new Gson();
- }
- public void sendMsg(String receiver, MessageType type, String body) {
- //send msg to holon receiver
- Message msg = new Message(this.hcu.getHolon().getUniqueID(), receiver, type, body);
- // System.out.println("Holon "+hcu.getHolon().getUniqueID()+" send message: "+msg);
- //get receiver through his uniqueID
- Holon h = this.hcu.getHolon().model.getHolonsByID().get(receiver);
- if(h == null) {
- System.err.println("Could not find Holon: "+receiver+"\t in holons: "+this.hcu.getHolon().model.getHolonsByID());
- return;
- }
- h.holonControlUnit.getCommunicator().receiveMsg(gson.toJson(msg));
- }
-
- public void receiveMsg(String message) {
- Message msg = this.gson.fromJson(message, Message.class);
- // System.out.println("Holon "+hcu.getHolon().getUniqueID()+" received message: "+message);
-
- if(!msg.getReceiver().equals(this.hcu.getHolon().getUniqueID()))
- throw new RuntimeException("Missleaded message:\n"+message);
-
- switch (msg.getType()) {
- case ORDER:
- break;
- case NEIGHBORHOOD:
- receiveNewVNeighbor(msg);
- break;
- default:
- throw new RuntimeException("Unknown message type:\n"+message);
- }
- }
-
- private void receiveNewVNeighbor(Message msg) {
- NeighborhoodMsg nMsg = this.gson.fromJson(msg.getBody(), NeighborhoodMsg.class);
- ArrayList<String> neighbors = nMsg.getNeighbors();
- switch(nMsg.getType()) {
- case NEW_VIRTUAL_NEIGHBOR:
- this.hcu.getHierarchyController().addVirtualNeighbors(neighbors);
- break;
- case REMOVE_VIRTUAL_NEIGHBOR:
- this.hcu.getHierarchyController().removeVirtualNeighbors(neighbors);
- break;
- case NEW_PHYSICAL_NEIGHBOR:
- break;
- case REMOVE_PHYSICAL_NEIGHBOR:
- break;
- default:
- throw new RuntimeException("Unknown neighborhood type:\n"+msg);
- }
- // System.out.println("Holon "+hcu.getHolon().name+" received new v neighbor "+v.getNewVirtualNeighbor());
- }
-
- public Gson getGson() {
- return this.gson;
- }
-
- }
|