001package com.box.sdk;
002
003import java.util.ArrayList;
004import java.util.Collection;
005
006import com.eclipsesource.json.JsonArray;
007import com.eclipsesource.json.JsonObject;
008import com.eclipsesource.json.JsonValue;
009
010/**
011 * Receives real-time events from the API and forwards them to {@link EventListener EventListeners}.
012 *
013 * <p>This class handles long polling the Box events endpoint in order to receive real-time user events.
014  * When an EventStream is started, it begins long polling on a separate thread until the {@link #stop} method
015  * is called.
016  * Since the API may return duplicate events, EventStream also maintains a small cache of the most recently received
017  * event IDs in order to automatically deduplicate events.</p>
018  * <p>Note: Enterprise Events can be accessed by admin users with the EventLog.getEnterpriseEvents method</p>
019 *
020 */
021public class EventStream {
022
023    private static final int LIMIT = 800;
024    private static final int STREAM_POSITION_NOW = -1;
025
026    /**
027     * Events URL.
028     */
029    public static final URLTemplate EVENT_URL = new URLTemplate("events?limit=" + LIMIT + "&stream_position=%s");
030
031    private final BoxAPIConnection api;
032    private final long startingPosition;
033    private final Collection<EventListener> listeners;
034    private final Object listenerLock;
035
036    private LRUCache<String> receivedEvents;
037    private boolean started;
038    private Poller poller;
039    private Thread pollerThread;
040
041    /**
042     * Constructs an EventStream using an API connection.
043     * @param  api the API connection to use.
044     */
045    public EventStream(BoxAPIConnection api) {
046        this(api, STREAM_POSITION_NOW);
047    }
048
049    /**
050     * Constructs an EventStream using an API connection and a starting initial position.
051     * @param api the API connection to use.
052     * @param startingPosition the starting position of the event stream.
053     */
054    public EventStream(BoxAPIConnection api, long startingPosition) {
055        this.api = api;
056        this.startingPosition = startingPosition;
057        this.listeners = new ArrayList<EventListener>();
058        this.listenerLock = new Object();
059    }
060
061    /**
062     * Adds a listener that will be notified when an event is received.
063     * @param listener the listener to add.
064     */
065    public void addListener(EventListener listener) {
066        synchronized (this.listenerLock) {
067            this.listeners.add(listener);
068        }
069    }
070
071    /**
072     * Indicates whether or not this EventStream has been started.
073     * @return true if this EventStream has been started; otherwise false.
074     */
075    public boolean isStarted() {
076        return this.started;
077    }
078
079    /**
080     * Stops this EventStream and disconnects from the API.
081     * @throws IllegalStateException if the EventStream is already stopped.
082     */
083    public void stop() {
084        if (!this.started) {
085            throw new IllegalStateException("Cannot stop the EventStream because it isn't started.");
086        }
087
088        this.started = false;
089        this.pollerThread.interrupt();
090    }
091
092    /**
093     * Starts this EventStream and begins long polling the API.
094     * @throws IllegalStateException if the EventStream is already started.
095     */
096    public void start() {
097        if (this.started) {
098            throw new IllegalStateException("Cannot start the EventStream because it isn't stopped.");
099        }
100
101        final long initialPosition;
102
103        if (this.startingPosition == STREAM_POSITION_NOW) {
104            BoxAPIRequest request = new BoxAPIRequest(this.api, EVENT_URL.build(this.api.getBaseURL(), "now"), "GET");
105            BoxJSONResponse response = (BoxJSONResponse) request.send();
106            JsonObject jsonObject = JsonObject.readFrom(response.getJSON());
107            initialPosition = jsonObject.get("next_stream_position").asLong();
108        } else {
109            initialPosition = this.startingPosition;
110        }
111
112        this.poller = new Poller(initialPosition);
113
114        this.pollerThread = new Thread(this.poller);
115        this.pollerThread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
116            public void uncaughtException(Thread t, Throwable e) {
117                EventStream.this.notifyException(e);
118            }
119        });
120        this.pollerThread.start();
121
122        this.started = true;
123    }
124
125    /**
126     * Indicates whether or not an event ID is a duplicate.
127     *
128     * <p>This method can be overridden by a subclass in order to provide custom de-duping logic.</p>
129     *
130     * @param  eventID the event ID.
131     * @return         true if the event is a duplicate; otherwise false.
132     */
133    protected boolean isDuplicate(String eventID) {
134        if (this.receivedEvents == null) {
135            this.receivedEvents = new LRUCache<String>();
136        }
137
138        return !this.receivedEvents.add(eventID);
139    }
140
141    private void notifyNextPosition(long position) {
142        synchronized (this.listenerLock) {
143            for (EventListener listener : this.listeners) {
144                listener.onNextPosition(position);
145            }
146        }
147    }
148
149    private void notifyEvent(BoxEvent event) {
150        synchronized (this.listenerLock) {
151            boolean isDuplicate = this.isDuplicate(event.getID());
152            if (!isDuplicate) {
153                for (EventListener listener : this.listeners) {
154                    listener.onEvent(event);
155                }
156            }
157        }
158    }
159
160    private void notifyException(Throwable e) {
161        if (e instanceof InterruptedException && !this.started) {
162            return;
163        }
164
165        this.stop();
166        synchronized (this.listenerLock) {
167            for (EventListener listener : this.listeners) {
168                if (listener.onException(e)) {
169                    return;
170                }
171            }
172        }
173    }
174
175    private class Poller implements Runnable {
176        private final long initialPosition;
177
178        private RealtimeServerConnection server;
179
180        public Poller(long initialPosition) {
181            this.initialPosition = initialPosition;
182            this.server = new RealtimeServerConnection(EventStream.this.api);
183        }
184
185        @Override
186        public void run() {
187            long position = this.initialPosition;
188            while (!Thread.interrupted()) {
189                if (this.server.getRemainingRetries() == 0) {
190                    this.server = new RealtimeServerConnection(EventStream.this.api);
191                }
192
193                if (this.server.waitForChange(position)) {
194                    if (Thread.interrupted()) {
195                        return;
196                    }
197
198                    BoxAPIRequest request = new BoxAPIRequest(EventStream.this.api,
199                        EVENT_URL.build(EventStream.this.api.getBaseURL(), position), "GET");
200                    BoxJSONResponse response = (BoxJSONResponse) request.send();
201                    JsonObject jsonObject = JsonObject.readFrom(response.getJSON());
202                    JsonArray entriesArray = jsonObject.get("entries").asArray();
203                    for (JsonValue entry : entriesArray) {
204                        BoxEvent event = new BoxEvent(EventStream.this.api, entry.asObject());
205                        EventStream.this.notifyEvent(event);
206                    }
207                    position = jsonObject.get("next_stream_position").asLong();
208                    EventStream.this.notifyNextPosition(position);
209                }
210            }
211        }
212    }
213}