summaryrefslogtreecommitdiff
path: root/same/src/main/java/com/orbekk/same/MasterServiceImpl.java
blob: a080b1edac24318f49410b4121b0dd5f8cf4fb82 (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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package com.orbekk.same;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.orbekk.same.State.Component;

public class MasterServiceImpl implements MasterService, UrlReceiver, Runnable {
    private Logger logger = LoggerFactory.getLogger(getClass());
    private final ConnectionManager connections;
    private State state;
    private boolean stopped = false;
    private Broadcaster broadcaster;
    private List<String> _fullStateReceivers = new ArrayList<String>();
    
    public MasterServiceImpl(State initialState, ConnectionManager connections,
            Broadcaster broadcaster) {
        state = initialState;
        this.connections = connections;
        this.broadcaster = broadcaster;
    }
    
    @Override
    public void joinNetworkRequest(String clientUrl) {
        logger.info("JoinNetworkRequest({})", clientUrl);
        List<String> participants = participants();
        if (!participants.contains(clientUrl)) {
            participants.add(clientUrl);
            _fullStateReceivers.add(clientUrl);
            synchronized(this) {
                state.updateFromObject(".participants", participants,
                        state.getRevision(".participants") + 1);
                notifyAll();
            }
        } else {                
            logger.warn("Client {} already part of network. " +
                    "Ignoring participation request", clientUrl);
        }
    }
    
    public boolean _sendUpdatedComponents() {
        boolean worked = false;
        for (final String component : state.getAndClearUpdatedComponents()) {
            logger.info("Broadcasting new component {}", state.show(component));
            broadcaster.broadcast(participants(), new ServiceOperation() {
                @Override public void run(String url) {
                    ClientService client = connections.getClient(url);
                    try {
                        client.setState(component, state.getDataOf(component),
                                state.getRevision(component));
                    } catch (Exception e) {
                        logger.warn("Exception when connecting to client.", e);
                    }
               }
            });
            worked = true;
        }
        return worked;
    }
    
    public synchronized boolean _sendFullState() {
        boolean hasWork = _fullStateReceivers.size() != 0;
        if (hasWork) {
            final List<State.Component> components = state.getComponents();
            broadcaster.broadcast(_fullStateReceivers, new ServiceOperation() {
                @Override public void run(String url) {
                    ClientService client = connections.getClient(url);
                    for (Component c : components) {
                        try {
                            client.setState(c.getName(), c.getData(), c.getRevision());
                        } catch (Exception e) {
                            logger.warn("Exception when connecting to client.", e);
                        }
                    }
                }
            });
            _fullStateReceivers.clear();
        }
        return hasWork;
    }
    
    private List<String> participants() {
        return state.getList(".participants");
    }
    
    
    @Override
    public synchronized boolean updateStateRequest(String component,
            String newData, long revision) {
        boolean updated = state.update(component, newData, revision + 1);
        if (updated) {
            notifyAll();
        }
        return updated;
    }

    @Override
    public void setUrl(String url) {
        String myUrl = url + "MasterService.json";
        logger.info("Master URL is " + myUrl);
        state.update(".masterUrl", myUrl, 1);
    }

    boolean _performWork() {
        boolean worked = false;
        worked |= _sendUpdatedComponents();
        worked |= _sendFullState();
        return worked;
    }
    
    @Override
    public void run() {
        while (!stopped) {
            if (_performWork()) {
                synchronized (this) {
                    try {
                        wait(500);
                    } catch (InterruptedException e) {
                        // Ignore interrupt in wait loop.
                    }
                }
            }
        }
    }
}