001package com.box.sdkgen.managers.events;
002
003import static com.box.sdkgen.internal.utils.UtilsManager.convertToString;
004import static com.box.sdkgen.internal.utils.UtilsManager.entryOf;
005import static com.box.sdkgen.internal.utils.UtilsManager.mapOf;
006import static com.box.sdkgen.internal.utils.UtilsManager.mergeMaps;
007import static com.box.sdkgen.internal.utils.UtilsManager.prepareParams;
008
009import com.box.sdkgen.box.eventstream.EventStream;
010import com.box.sdkgen.networking.auth.Authentication;
011import com.box.sdkgen.networking.fetchoptions.FetchOptions;
012import com.box.sdkgen.networking.fetchoptions.ResponseFormat;
013import com.box.sdkgen.networking.fetchresponse.FetchResponse;
014import com.box.sdkgen.networking.network.NetworkSession;
015import com.box.sdkgen.schemas.events.Events;
016import com.box.sdkgen.schemas.realtimeservers.RealtimeServers;
017import com.box.sdkgen.serialization.json.JsonManager;
018import java.util.Map;
019
020public class EventsManager {
021
022  public Authentication auth;
023
024  public NetworkSession networkSession;
025
026  public EventsManager() {
027    this.networkSession = new NetworkSession();
028  }
029
030  protected EventsManager(Builder builder) {
031    this.auth = builder.auth;
032    this.networkSession = builder.networkSession;
033  }
034
035  /**
036   * Returns a list of real-time servers that can be used for long-polling updates to the [event
037   * stream](https://developer.box.com/reference/get-events).
038   *
039   * <p>Long polling is the concept where a HTTP request is kept open until the server sends a
040   * response, then repeating the process over and over to receive updated responses.
041   *
042   * <p>Long polling the event stream can only be used for user events, not for enterprise events.
043   *
044   * <p>To use long polling, first use this endpoint to retrieve a list of long poll URLs. Next,
045   * make a long poll request to any of the provided URLs.
046   *
047   * <p>When an event occurs in monitored account a response with the value `new_change` will be
048   * sent. The response contains no other details as it only serves as a prompt to take further
049   * action such as sending a request to the [events
050   * endpoint](https://developer.box.com/reference/get-events) with the last known
051   * `stream_position`.
052   *
053   * <p>After the server sends this response it closes the connection. You must now repeat the long
054   * poll process to begin listening for events again.
055   *
056   * <p>If no events occur for a while and the connection times out you will receive a response with
057   * the value `reconnect`. When you receive this response you’ll make another call to this endpoint
058   * to restart the process.
059   *
060   * <p>If you receive no events in `retry_timeout` seconds then you will need to make another
061   * request to the real-time server (one of the URLs in the response for this endpoint). This might
062   * be necessary due to network errors.
063   *
064   * <p>Finally, if you receive a `max_retries` error when making a request to the real-time server,
065   * you should start over by making a call to this endpoint first.
066   */
067  public RealtimeServers getEventsWithLongPolling() {
068    return getEventsWithLongPolling(new GetEventsWithLongPollingHeaders());
069  }
070
071  /**
072   * Returns a list of real-time servers that can be used for long-polling updates to the [event
073   * stream](https://developer.box.com/reference/get-events).
074   *
075   * <p>Long polling is the concept where a HTTP request is kept open until the server sends a
076   * response, then repeating the process over and over to receive updated responses.
077   *
078   * <p>Long polling the event stream can only be used for user events, not for enterprise events.
079   *
080   * <p>To use long polling, first use this endpoint to retrieve a list of long poll URLs. Next,
081   * make a long poll request to any of the provided URLs.
082   *
083   * <p>When an event occurs in monitored account a response with the value `new_change` will be
084   * sent. The response contains no other details as it only serves as a prompt to take further
085   * action such as sending a request to the [events
086   * endpoint](https://developer.box.com/reference/get-events) with the last known
087   * `stream_position`.
088   *
089   * <p>After the server sends this response it closes the connection. You must now repeat the long
090   * poll process to begin listening for events again.
091   *
092   * <p>If no events occur for a while and the connection times out you will receive a response with
093   * the value `reconnect`. When you receive this response you’ll make another call to this endpoint
094   * to restart the process.
095   *
096   * <p>If you receive no events in `retry_timeout` seconds then you will need to make another
097   * request to the real-time server (one of the URLs in the response for this endpoint). This might
098   * be necessary due to network errors.
099   *
100   * <p>Finally, if you receive a `max_retries` error when making a request to the real-time server,
101   * you should start over by making a call to this endpoint first.
102   *
103   * @param headers Headers of getEventsWithLongPolling method
104   */
105  public RealtimeServers getEventsWithLongPolling(GetEventsWithLongPollingHeaders headers) {
106    Map<String, String> headersMap = prepareParams(mergeMaps(mapOf(), headers.getExtraHeaders()));
107    FetchResponse response =
108        this.networkSession
109            .getNetworkClient()
110            .fetch(
111                new FetchOptions.Builder(
112                        String.join(
113                            "", this.networkSession.getBaseUrls().getBaseUrl(), "/2.0/events"),
114                        "OPTIONS")
115                    .headers(headersMap)
116                    .responseFormat(ResponseFormat.JSON)
117                    .auth(this.auth)
118                    .networkSession(this.networkSession)
119                    .build());
120    return JsonManager.deserialize(response.getData(), RealtimeServers.class);
121  }
122
123  /**
124   * Returns up to a year of past events for a given user or for the entire enterprise.
125   *
126   * <p>By default this returns events for the authenticated user. To retrieve events for the entire
127   * enterprise, set the `stream_type` to `admin_logs_streaming` for live monitoring of new events,
128   * or `admin_logs` for querying across historical events. The user making the API call will need
129   * to have admin privileges, and the application will need to have the scope `manage enterprise
130   * properties` checked.
131   */
132  public Events getEvents() {
133    return getEvents(new GetEventsQueryParams(), new GetEventsHeaders());
134  }
135
136  /**
137   * Returns up to a year of past events for a given user or for the entire enterprise.
138   *
139   * <p>By default this returns events for the authenticated user. To retrieve events for the entire
140   * enterprise, set the `stream_type` to `admin_logs_streaming` for live monitoring of new events,
141   * or `admin_logs` for querying across historical events. The user making the API call will need
142   * to have admin privileges, and the application will need to have the scope `manage enterprise
143   * properties` checked.
144   *
145   * @param queryParams Query parameters of getEvents method
146   */
147  public Events getEvents(GetEventsQueryParams queryParams) {
148    return getEvents(queryParams, new GetEventsHeaders());
149  }
150
151  /**
152   * Returns up to a year of past events for a given user or for the entire enterprise.
153   *
154   * <p>By default this returns events for the authenticated user. To retrieve events for the entire
155   * enterprise, set the `stream_type` to `admin_logs_streaming` for live monitoring of new events,
156   * or `admin_logs` for querying across historical events. The user making the API call will need
157   * to have admin privileges, and the application will need to have the scope `manage enterprise
158   * properties` checked.
159   *
160   * @param headers Headers of getEvents method
161   */
162  public Events getEvents(GetEventsHeaders headers) {
163    return getEvents(new GetEventsQueryParams(), headers);
164  }
165
166  /**
167   * Returns up to a year of past events for a given user or for the entire enterprise.
168   *
169   * <p>By default this returns events for the authenticated user. To retrieve events for the entire
170   * enterprise, set the `stream_type` to `admin_logs_streaming` for live monitoring of new events,
171   * or `admin_logs` for querying across historical events. The user making the API call will need
172   * to have admin privileges, and the application will need to have the scope `manage enterprise
173   * properties` checked.
174   *
175   * @param queryParams Query parameters of getEvents method
176   * @param headers Headers of getEvents method
177   */
178  public Events getEvents(GetEventsQueryParams queryParams, GetEventsHeaders headers) {
179    Map<String, String> queryParamsMap =
180        prepareParams(
181            mapOf(
182                entryOf("stream_type", convertToString(queryParams.getStreamType())),
183                entryOf("stream_position", convertToString(queryParams.getStreamPosition())),
184                entryOf("limit", convertToString(queryParams.getLimit())),
185                entryOf("event_type", convertToString(queryParams.getEventType())),
186                entryOf("created_after", convertToString(queryParams.getCreatedAfter())),
187                entryOf("created_before", convertToString(queryParams.getCreatedBefore()))));
188    Map<String, String> headersMap = prepareParams(mergeMaps(mapOf(), headers.getExtraHeaders()));
189    FetchResponse response =
190        this.networkSession
191            .getNetworkClient()
192            .fetch(
193                new FetchOptions.Builder(
194                        String.join(
195                            "", this.networkSession.getBaseUrls().getBaseUrl(), "/2.0/events"),
196                        "GET")
197                    .params(queryParamsMap)
198                    .headers(headersMap)
199                    .responseFormat(ResponseFormat.JSON)
200                    .auth(this.auth)
201                    .networkSession(this.networkSession)
202                    .build());
203    return JsonManager.deserialize(response.getData(), Events.class);
204  }
205
206  /** Get an event stream for the Box API */
207  public EventStream getEventStream() {
208    return getEventStream(new GetEventStreamQueryParams(), new GetEventStreamHeaders());
209  }
210
211  /**
212   * Get an event stream for the Box API
213   *
214   * @param queryParams Query parameters of getEvents method
215   */
216  public EventStream getEventStream(GetEventStreamQueryParams queryParams) {
217    return getEventStream(queryParams, new GetEventStreamHeaders());
218  }
219
220  /**
221   * Get an event stream for the Box API
222   *
223   * @param headers Headers of getEvents method
224   */
225  public EventStream getEventStream(GetEventStreamHeaders headers) {
226    return getEventStream(new GetEventStreamQueryParams(), headers);
227  }
228
229  /**
230   * Get an event stream for the Box API
231   *
232   * @param queryParams Query parameters of getEvents method
233   * @param headers Headers of getEvents method
234   */
235  public EventStream getEventStream(
236      GetEventStreamQueryParams queryParams, GetEventStreamHeaders headers) {
237    return new EventStream.Builder(this, queryParams).headersInput(headers).build();
238  }
239
240  public Authentication getAuth() {
241    return auth;
242  }
243
244  public NetworkSession getNetworkSession() {
245    return networkSession;
246  }
247
248  public static class Builder {
249
250    protected Authentication auth;
251
252    protected NetworkSession networkSession;
253
254    public Builder() {}
255
256    public Builder auth(Authentication auth) {
257      this.auth = auth;
258      return this;
259    }
260
261    public Builder networkSession(NetworkSession networkSession) {
262      this.networkSession = networkSession;
263      return this;
264    }
265
266    public EventsManager build() {
267      if (this.networkSession == null) {
268        this.networkSession = new NetworkSession();
269      }
270      return new EventsManager(this);
271    }
272  }
273}