m-chrzan.xyz
aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/pl/edu/mimuw/cloudatlas/agent/EventBus.java
blob: 3d3d279584d4d2b27570a98a07eb0b6cd759285e (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
54
55
56
57
58
59
package pl.edu.mimuw.cloudatlas.agent;

import pl.edu.mimuw.cloudatlas.agent.messages.AgentMessage;
import pl.edu.mimuw.cloudatlas.agent.modules.ModuleType;

import java.util.HashMap;
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<ModuleType, Executor> executors;

    void setEventBusReference() {
        for (Map.Entry<ModuleType, Executor> executorEntry : this.executors.entrySet()) {
            executorEntry.getValue().setEventBus(this);
        }
    }

    // Allows for testing with a mock EventBus
    protected EventBus() {
        this.events = new LinkedBlockingQueue<AgentMessage>();
    }

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

    public void setEvents(LinkedBlockingQueue<AgentMessage> events) {
        this.events = events;
    }

    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 {
        executors.get(msg.getDestinationModule()).addMessage(msg);
    }

    public void addMessage(AgentMessage msg) throws InterruptedException {
        System.out.println("INFO: message added for " + msg.getDestinationModule().toString());
        this.events.put(msg);
    }
}