m-chrzan.xyz
aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/pl/edu/mimuw/cloudatlas/agent/EventBus.java
blob: afb4e274087005822276c7daebaffaed35a3247b (plain)
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
package pl.edu.mimuw.cloudatlas.agent;

import pl.edu.mimuw.cloudatlas.agent.message.AgentMessage;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;

/*
 * The EventBus routes messages sent between Modules.
 */
public class EventBus implements Runnable {
    private LinkedBlockingQueue<AgentMessage> events;
    private HashMap<AgentMessage.AgentModule, Executor> executors;

    void setEventBusReference() {
        Iterator it = this.executors.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<AgentMessage.AgentModule, Executor> executorEntry =
                    (Map.Entry<AgentMessage.AgentModule, Executor>) it.next();
            executorEntry.getValue().setEventBus(this);
        }
    }

    EventBus(HashMap<AgentMessage.AgentModule, Executor> executors) {
        this.executors = executors;
        setEventBusReference();
        this.events = new LinkedBlockingQueue<AgentMessage>();
    }

    public void run() {
        System.out.println("Event bus running");
        while (!Thread.currentThread().interrupted()) {
            try {
                AgentMessage event = events.take();
                routeMessage(event);
            } catch (InterruptedException e) {
                System.out.println("Event bus interrupted. Exiting loop.");
                break;
            }
        }
    }

    public void routeMessage(AgentMessage msg) throws InterruptedException {
        System.out.println("Event bus routing message");
        executors.get(msg.getDestinationModule()).addMessage(msg);
    }

    public void addMessage(AgentMessage msg) throws InterruptedException {
        this.events.put(msg);
    }
}