001package com.box.sdk;
002
003import java.io.ByteArrayInputStream;
004import java.io.IOException;
005import java.io.InputStream;
006import java.io.OutputStream;
007import java.net.HttpURLConnection;
008import java.net.MalformedURLException;
009import java.net.ProtocolException;
010import java.net.URL;
011import java.util.ArrayList;
012import java.util.List;
013import java.util.Map;
014import java.util.logging.Level;
015import java.util.logging.Logger;
016
017import com.box.sdk.http.HttpMethod;
018
019/**
020 * Used to make HTTP requests to the Box API.
021 *
022 * <p>All requests to the REST API are sent using this class or one of its subclasses. This class wraps {@link
023 * HttpURLConnection} in order to provide a simpler interface that can automatically handle various conditions specific
024 * to Box's API. Requests will be authenticated using a {@link BoxAPIConnection} (if one is provided), so it isn't
025 * necessary to add authorization headers. Requests can also be sent more than once, unlike with HttpURLConnection. If
026 * an error occurs while sending a request, it will be automatically retried (with a back off delay) up to the maximum
027 * number of times set in the BoxAPIConnection.</p>
028 *
029 * <p>Specifying a body for a BoxAPIRequest is done differently than it is with HttpURLConnection. Instead of writing to
030 * an OutputStream, the request is provided an {@link InputStream} which will be read when the {@link #send} method is
031 * called. This makes it easy to retry requests since the stream can automatically reset and reread with each attempt.
032 * If the stream cannot be reset, then a new stream will need to be provided before each call to send. There is also a
033 * convenience method for specifying the body as a String, which simply wraps the String with an InputStream.</p>
034 */
035public class BoxAPIRequest {
036    private static final Logger LOGGER = Logger.getLogger(BoxAPIRequest.class.getName());
037    private static final int BUFFER_SIZE = 8192;
038    private static final int MAX_REDIRECTS = 3;
039
040    private final BoxAPIConnection api;
041    private final List<RequestHeader> headers;
042    private final String method;
043
044    private URL url;
045    private BackoffCounter backoffCounter;
046    private int timeout;
047    private InputStream body;
048    private long bodyLength;
049    private Map<String, List<String>> requestProperties;
050    private int numRedirects;
051    private boolean followRedirects = true;
052    private boolean shouldAuthenticate;
053
054    /**
055     * Constructs an unauthenticated BoxAPIRequest.
056     * @param  url    the URL of the request.
057     * @param  method the HTTP method of the request.
058     */
059    public BoxAPIRequest(URL url, String method) {
060        this(null, url, method);
061    }
062
063    /**
064     * Constructs an authenticated BoxAPIRequest using a provided BoxAPIConnection.
065     * @param  api    an API connection for authenticating the request.
066     * @param  url    the URL of the request.
067     * @param  method the HTTP method of the request.
068     */
069    public BoxAPIRequest(BoxAPIConnection api, URL url, String method) {
070        this.api = api;
071        this.url = url;
072        this.method = method;
073        this.headers = new ArrayList<RequestHeader>();
074        this.backoffCounter = new BackoffCounter(new Time());
075        this.shouldAuthenticate = true;
076
077        this.addHeader("Accept-Encoding", "gzip");
078        this.addHeader("Accept-Charset", "utf-8");
079    }
080
081    /**
082     * Constructs an authenticated BoxAPIRequest using a provided BoxAPIConnection.
083     * @param  api    an API connection for authenticating the request.
084     * @param  uploadPartEndpoint the URL of the request.
085     * @param  method the HTTP method of the request.
086     */
087    public BoxAPIRequest(BoxAPIConnection api, URL uploadPartEndpoint, HttpMethod method) {
088        this(api, uploadPartEndpoint, method.name());
089    }
090
091    /**
092     * Adds an HTTP header to this request.
093     * @param key   the header key.
094     * @param value the header value.
095     */
096    public void addHeader(String key, String value) {
097        this.headers.add(new RequestHeader(key, value));
098    }
099
100    /**
101     * Sets a timeout for this request in milliseconds.
102     * @param timeout the timeout in milliseconds.
103     */
104    public void setTimeout(int timeout) {
105        this.timeout = timeout;
106    }
107
108    /**
109     * Sets whether or not to follow redirects (i.e. Location header)
110     * @param followRedirects true to follow, false to not follow
111     */
112    public void setFollowRedirects(boolean followRedirects) {
113        this.followRedirects = followRedirects;
114    }
115
116    /**
117     * Gets the stream containing contents of this request's body.
118     *
119     * <p>Note that any bytes that read from the returned stream won't be sent unless the stream is reset back to its
120     * initial position.</p>
121     *
122     * @return an InputStream containing the contents of this request's body.
123     */
124    public InputStream getBody() {
125        return this.body;
126    }
127
128    /**
129     * Sets the request body to the contents of an InputStream.
130     *
131     * <p>The stream must support the {@link InputStream#reset} method if auto-retry is used or if the request needs to
132     * be resent. Otherwise, the body must be manually set before each call to {@link #send}.</p>
133     *
134     * @param stream an InputStream containing the contents of the body.
135     */
136    public void setBody(InputStream stream) {
137        this.body = stream;
138    }
139
140    /**
141     * Sets the request body to the contents of an InputStream.
142     *
143     * <p>Providing the length of the InputStream allows for the progress of the request to be monitored when calling
144     * {@link #send(ProgressListener)}.</p>
145     *
146     * <p> See {@link #setBody(InputStream)} for more information on setting the body of the request.</p>
147     *
148     * @param stream an InputStream containing the contents of the body.
149     * @param length the expected length of the stream.
150     */
151    public void setBody(InputStream stream, long length) {
152        this.bodyLength = length;
153        this.body = stream;
154    }
155
156    /**
157     * Sets the request body to the contents of a String.
158     *
159     * <p>If the contents of the body are large, then it may be more efficient to use an {@link InputStream} instead of
160     * a String. Using a String requires that the entire body be in memory before sending the request.</p>
161     *
162     * @param body a String containing the contents of the body.
163     */
164    public void setBody(String body) {
165        byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
166        this.bodyLength = bytes.length;
167        this.body = new ByteArrayInputStream(bytes);
168    }
169
170    /**
171     * Gets the URL from the request.
172     *
173     * @return a URL containing the URL of the request.
174     */
175    public URL getUrl() {
176        return this.url;
177    }
178
179    /**
180     * Sends this request and returns a BoxAPIResponse containing the server's response.
181     *
182     * <p>The type of the returned BoxAPIResponse will be based on the content type returned by the server, allowing it
183     * to be cast to a more specific type. For example, if it's known that the API call will return a JSON response,
184     * then it can be cast to a {@link BoxJSONResponse} like so:</p>
185     *
186     * <pre>BoxJSONResponse response = (BoxJSONResponse) request.send();</pre>
187     *
188     * <p>If the server returns an error code or if a network error occurs, then the request will be automatically
189     * retried. If the maximum number of retries is reached and an error still occurs, then a {@link BoxAPIException}
190     * will be thrown.</p>
191     *
192     * @throws BoxAPIException if the server returns an error code or if a network error occurs.
193     * @return a {@link BoxAPIResponse} containing the server's response.
194     */
195    public BoxAPIResponse send() {
196        return this.send(null);
197    }
198
199    /**
200     * Sends this request while monitoring its progress and returns a BoxAPIResponse containing the server's response.
201     *
202     * <p>A ProgressListener is generally only useful when the size of the request is known beforehand. If the size is
203     * unknown, then the ProgressListener will be updated for each byte sent, but the total number of bytes will be
204     * reported as 0.</p>
205     *
206     * <p> See {@link #send} for more information on sending requests.</p>
207     *
208     * @param  listener a listener for monitoring the progress of the request.
209     * @throws BoxAPIException if the server returns an error code or if a network error occurs.
210     * @return a {@link BoxAPIResponse} containing the server's response.
211     */
212    public BoxAPIResponse send(ProgressListener listener) {
213        if (this.api == null) {
214            this.backoffCounter.reset(BoxAPIConnection.DEFAULT_MAX_ATTEMPTS);
215        } else {
216            this.backoffCounter.reset(this.api.getMaxRequestAttempts());
217        }
218
219        while (this.backoffCounter.getAttemptsRemaining() > 0) {
220            try {
221                return this.trySend(listener);
222            } catch (BoxAPIException apiException) {
223                if (!this.backoffCounter.decrement() || !isResponseRetryable(apiException.getResponseCode())) {
224                    throw apiException;
225                }
226
227                try {
228                    this.resetBody();
229                } catch (IOException ioException) {
230                    throw apiException;
231                }
232
233                try {
234                    this.backoffCounter.waitBackoff();
235                } catch (InterruptedException interruptedException) {
236                    Thread.currentThread().interrupt();
237                    throw apiException;
238                }
239            }
240        }
241
242        throw new RuntimeException();
243    }
244
245    /**
246     * Returns a String containing the URL, HTTP method, headers and body of this request.
247     * @return a String containing information about this request.
248     */
249    @Override
250    public String toString() {
251        String lineSeparator = System.getProperty("line.separator");
252        StringBuilder builder = new StringBuilder();
253        builder.append("Request");
254        builder.append(lineSeparator);
255        builder.append(this.method);
256        builder.append(' ');
257        builder.append(this.url.toString());
258        builder.append(lineSeparator);
259
260        for (Map.Entry<String, List<String>> entry : this.requestProperties.entrySet()) {
261            List<String> nonEmptyValues = new ArrayList<String>();
262            for (String value : entry.getValue()) {
263                if (value != null && value.trim().length() != 0) {
264                    nonEmptyValues.add(value);
265                }
266            }
267
268            if (nonEmptyValues.size() == 0) {
269                continue;
270            }
271
272            builder.append(entry.getKey());
273            builder.append(": ");
274            for (String value : nonEmptyValues) {
275                builder.append(value);
276                builder.append(", ");
277            }
278
279            builder.delete(builder.length() - 2, builder.length());
280            builder.append(lineSeparator);
281        }
282
283        String bodyString = this.bodyToString();
284        if (bodyString != null) {
285            builder.append(lineSeparator);
286            builder.append(bodyString);
287        }
288
289        return builder.toString().trim();
290    }
291
292    /**
293     * Returns a String representation of this request's body used in {@link #toString}. This method returns
294     * null by default.
295     *
296     * <p>A subclass may want override this method if the body can be converted to a String for logging or debugging
297     * purposes.</p>
298     *
299     * @return a String representation of this request's body.
300     */
301    protected String bodyToString() {
302        return null;
303    }
304
305    /**
306     * Writes the body of this request to an HttpURLConnection.
307     *
308     * <p>Subclasses overriding this method must remember to close the connection's OutputStream after writing.</p>
309     *
310     * @param connection the connection to which the body should be written.
311     * @param listener   an optional listener for monitoring the write progress.
312     * @throws BoxAPIException if an error occurs while writing to the connection.
313     */
314    protected void writeBody(HttpURLConnection connection, ProgressListener listener) {
315        if (this.body == null) {
316            return;
317        }
318
319        connection.setDoOutput(true);
320        try {
321            OutputStream output = connection.getOutputStream();
322            if (listener != null) {
323                output = new ProgressOutputStream(output, listener, this.bodyLength);
324            }
325            int b = this.body.read();
326            while (b != -1) {
327                output.write(b);
328                b = this.body.read();
329            }
330            output.close();
331        } catch (IOException e) {
332            throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e);
333        }
334    }
335
336    /**
337     * Resets the InputStream containing this request's body.
338     *
339     * <p>This method will be called before each attempt to resend the request, giving subclasses an opportunity to
340     * reset any streams that need to be read when sending the body.</p>
341     *
342     * @throws IOException if the stream cannot be reset.
343     */
344    protected void resetBody() throws IOException {
345        if (this.body != null) {
346            this.body.reset();
347        }
348    }
349
350    void setBackoffCounter(BackoffCounter counter) {
351        this.backoffCounter = counter;
352    }
353
354    private BoxAPIResponse trySend(ProgressListener listener) {
355        if (this.api != null) {
356            RequestInterceptor interceptor = this.api.getRequestInterceptor();
357            if (interceptor != null) {
358                BoxAPIResponse response = interceptor.onRequest(this);
359                if (response != null) {
360                    return response;
361                }
362            }
363        }
364
365        HttpURLConnection connection = this.createConnection();
366
367        if (this.bodyLength > 0) {
368            connection.setFixedLengthStreamingMode((int) this.bodyLength);
369            connection.setDoOutput(true);
370        }
371
372        if (this.api != null) {
373            if (this.shouldAuthenticate) {
374                connection.addRequestProperty("Authorization", "Bearer " + this.api.lockAccessToken());
375            }
376            connection.setRequestProperty("User-Agent", this.api.getUserAgent());
377            if (this.api.getProxy() != null) {
378                if (this.api.getProxyUsername() != null && this.api.getProxyPassword() != null) {
379                    String usernameAndPassword = this.api.getProxyUsername() + ":" + this.api.getProxyPassword();
380                    String encoded = new String(Base64.encode(usernameAndPassword.getBytes()));
381                    connection.addRequestProperty("Proxy-Authorization", "Basic " + encoded);
382                }
383            }
384
385            if (this.api instanceof SharedLinkAPIConnection) {
386                SharedLinkAPIConnection sharedItemAPI = (SharedLinkAPIConnection) this.api;
387                String sharedLink = sharedItemAPI.getSharedLink();
388                String boxAPIValue = "shared_link=" + sharedLink;
389                String sharedLinkPassword = sharedItemAPI.getSharedLinkPassword();
390                if (sharedLinkPassword != null) {
391                    boxAPIValue += "&shared_link_password=" + sharedLinkPassword;
392                }
393                connection.addRequestProperty("BoxApi", boxAPIValue);
394            }
395        }
396
397        this.requestProperties = connection.getRequestProperties();
398
399        int responseCode;
400        try {
401            this.writeBody(connection, listener);
402
403            // Ensure that we're connected in case writeBody() didn't write anything.
404            try {
405                connection.connect();
406            } catch (IOException e) {
407                throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e);
408            }
409
410            this.logRequest(connection);
411
412            // We need to manually handle redirects by creating a new HttpURLConnection so that connection pooling
413            // happens correctly. There seems to be a bug in Oracle's Java implementation where automatically handled
414            // redirects will not keep the connection alive.
415            try {
416                responseCode = connection.getResponseCode();
417            } catch (IOException e) {
418                throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e);
419            }
420        } finally {
421            if (this.api != null && this.shouldAuthenticate) {
422                this.api.unlockAccessToken();
423            }
424        }
425
426        if (isResponseRedirect(responseCode)) {
427            return this.handleRedirect(connection, listener);
428        }
429
430        String contentType = connection.getContentType();
431        BoxAPIResponse response;
432        if (contentType == null) {
433            response = new BoxAPIResponse(connection);
434        } else if (contentType.contains("application/json")) {
435            response = new BoxJSONResponse(connection);
436        } else {
437            response = new BoxAPIResponse(connection);
438        }
439
440        return response;
441    }
442
443    private BoxAPIResponse handleRedirect(HttpURLConnection connection, ProgressListener listener) {
444        if (this.numRedirects >= MAX_REDIRECTS) {
445            throw new BoxAPIException("The Box API responded with too many redirects.");
446        }
447        this.numRedirects++;
448
449        // Even though the redirect response won't have a body, we need to read the InputStream so that Java will put
450        // the connection back in the connection pool.
451        try {
452            InputStream stream = connection.getInputStream();
453            byte[] buffer = new byte[8192];
454            int n = stream.read(buffer);
455            while (n != -1) {
456                n = stream.read(buffer);
457            }
458            stream.close();
459        } catch (IOException e) {
460            throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e);
461        }
462
463        String redirect = connection.getHeaderField("Location");
464        try {
465            this.url = new URL(redirect);
466        } catch (MalformedURLException e) {
467            throw new BoxAPIException("The Box API responded with an invalid redirect.", e);
468        }
469
470        if (this.followRedirects) {
471            return this.trySend(listener);
472        } else {
473            BoxRedirectResponse redirectResponse = new BoxRedirectResponse();
474            redirectResponse.setRedirectURL(this.url);
475            return redirectResponse;
476        }
477    }
478
479    private void logRequest(HttpURLConnection connection) {
480        if (LOGGER.isLoggable(Level.FINE)) {
481            LOGGER.log(Level.FINE, this.toString());
482        }
483    }
484
485    private HttpURLConnection createConnection() {
486        HttpURLConnection connection = null;
487
488        try {
489            if (this.api == null || this.api.getProxy() == null) {
490                connection = (HttpURLConnection) this.url.openConnection();
491            } else {
492                connection = (HttpURLConnection) this.url.openConnection(this.api.getProxy());
493            }
494        } catch (IOException e) {
495            throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e);
496        }
497
498        try {
499            connection.setRequestMethod(this.method);
500        } catch (ProtocolException e) {
501            throw new BoxAPIException("Couldn't connect to the Box API because the request's method was invalid.", e);
502        }
503
504        connection.setConnectTimeout(this.timeout);
505        connection.setReadTimeout(this.timeout);
506
507        // Don't allow HttpURLConnection to automatically redirect because it messes up the connection pool. See the
508        // trySend(ProgressListener) method for how we handle redirects.
509        connection.setInstanceFollowRedirects(false);
510
511        for (RequestHeader header : this.headers) {
512            connection.addRequestProperty(header.getKey(), header.getValue());
513        }
514
515        return connection;
516    }
517
518    void shouldAuthenticate(boolean shouldAuthenticate) {
519        this.shouldAuthenticate = shouldAuthenticate;
520    }
521
522    private static boolean isResponseRetryable(int responseCode) {
523        return (responseCode >= 500 || responseCode == 429);
524    }
525
526    private static boolean isResponseRedirect(int responseCode) {
527        return (responseCode == 301 || responseCode == 302);
528    }
529
530    private final class RequestHeader {
531        private final String key;
532        private final String value;
533
534        public RequestHeader(String key, String value) {
535            this.key = key;
536            this.value = value;
537        }
538
539        public String getKey() {
540            return this.key;
541        }
542
543        public String getValue() {
544            return this.value;
545        }
546    }
547}