001package com.box.sdk;
002
003import com.box.sdk.http.HttpHeaders;
004import com.box.sdk.http.HttpMethod;
005import com.eclipsesource.json.Json;
006import com.eclipsesource.json.JsonObject;
007import java.io.ByteArrayInputStream;
008import java.io.IOException;
009import java.io.InputStream;
010import java.io.OutputStream;
011import java.net.HttpURLConnection;
012import java.net.MalformedURLException;
013import java.net.ProtocolException;
014import java.net.URL;
015import java.security.KeyManagementException;
016import java.security.NoSuchAlgorithmException;
017import java.util.ArrayList;
018import java.util.List;
019import java.util.Map;
020import java.util.Objects;
021import javax.net.ssl.HttpsURLConnection;
022import javax.net.ssl.SSLContext;
023import javax.net.ssl.SSLParameters;
024import javax.net.ssl.SSLSocketFactory;
025
026
027/**
028 * Used to make HTTP requests to the Box API.
029 *
030 * <p>All requests to the REST API are sent using this class or one of its subclasses. This class wraps {@link
031 * HttpURLConnection} in order to provide a simpler interface that can automatically handle various conditions specific
032 * to Box's API. Requests will be authenticated using a {@link BoxAPIConnection} (if one is provided), so it isn't
033 * necessary to add authorization headers. Requests can also be sent more than once, unlike with HttpURLConnection. If
034 * an error occurs while sending a request, it will be automatically retried (with a back off delay) up to the maximum
035 * number of times set in the BoxAPIConnection.</p>
036 *
037 * <p>Specifying a body for a BoxAPIRequest is done differently than it is with HttpURLConnection. Instead of writing to
038 * an OutputStream, the request is provided an {@link InputStream} which will be read when the {@link #send} method is
039 * called. This makes it easy to retry requests since the stream can automatically reset and reread with each attempt.
040 * If the stream cannot be reset, then a new stream will need to be provided before each call to send. There is also a
041 * convenience method for specifying the body as a String, which simply wraps the String with an InputStream.</p>
042 */
043public class BoxAPIRequest {
044    private static final BoxLogger LOGGER = BoxLogger.defaultLogger();
045    private static final int MAX_REDIRECTS = 3;
046    private static final String ERROR_CREATING_REQUEST_BODY = "Error creating request body";
047    private static SSLSocketFactory sslSocketFactory;
048
049    static {
050        // Setup the SSL context manually to force newer TLS version on legacy Java environments
051        // This is necessary because Java 7 uses TLSv1.0 by default, but the Box API will need
052        // to deprecate this protocol in the future.  To prevent clients from breaking, we must
053        // ensure that they are using TLSv1.1 or greater!
054        SSLContext sc = null;
055        try {
056            sc = SSLContext.getDefault();
057            SSLParameters params = sc.getDefaultSSLParameters();
058            boolean supportsNewTLS = false;
059            for (String protocol : params.getProtocols()) {
060                if (protocol.compareTo("TLSv1") > 0) {
061                    supportsNewTLS = true;
062                    break;
063                }
064            }
065            if (!supportsNewTLS) {
066                // Try to upgrade to a higher TLS version
067                sc = null;
068                sc = SSLContext.getInstance("TLSv1.1");
069                sc.init(null, null, new java.security.SecureRandom());
070                sc = SSLContext.getInstance("TLSv1.2");
071                sc.init(null, null, new java.security.SecureRandom());
072            }
073        } catch (NoSuchAlgorithmException ex) {
074            if (sc == null) {
075                LOGGER.error("Unable to set up SSL context for HTTPS! "
076                    + "This may result in the inability  to connect to the Box API.");
077            }
078            if (sc != null && sc.getProtocol().equals("TLSv1")) {
079                // Could not find a good version of TLS
080                LOGGER.error("Using deprecated TLSv1 protocol, which will be deprecated by the Box API! "
081                    + "Upgrade to a newer version of Java as soon as possible.");
082            }
083        } catch (KeyManagementException ex) {
084            LOGGER.error(
085                "Exception when initializing SSL Context!  This may result in the inabilty to connect to the Box API"
086            );
087            sc = null;
088        }
089
090        if (sc != null) {
091            sslSocketFactory = sc.getSocketFactory();
092        }
093
094    }
095
096    private final BoxAPIConnection api;
097    private final List<RequestHeader> headers;
098    private final String method;
099    private URL url;
100    private BackoffCounter backoffCounter;
101    private int connectTimeout;
102    private int readTimeout;
103    private InputStream body;
104    private long bodyLength;
105    private Map<String, List<String>> requestProperties;
106    private int numRedirects;
107    private boolean followRedirects = true;
108    private boolean shouldAuthenticate;
109
110    /**
111     * Constructs an unauthenticated BoxAPIRequest.
112     *
113     * @param url    the URL of the request.
114     * @param method the HTTP method of the request.
115     */
116    public BoxAPIRequest(URL url, String method) {
117        this(null, url, method);
118    }
119
120    /**
121     * Constructs an authenticated BoxAPIRequest using a provided BoxAPIConnection.
122     *
123     * @param api    an API connection for authenticating the request.
124     * @param url    the URL of the request.
125     * @param method the HTTP method of the request.
126     */
127    public BoxAPIRequest(BoxAPIConnection api, URL url, String method) {
128        this.api = api;
129        this.url = url;
130        this.method = method;
131        this.headers = new ArrayList<>();
132        if (api != null) {
133            Map<String, String> customHeaders = api.getHeaders();
134            if (customHeaders != null) {
135                for (String header : customHeaders.keySet()) {
136                    this.addHeader(header, customHeaders.get(header));
137                }
138            }
139            this.headers.add(new RequestHeader("X-Box-UA", api.getBoxUAHeader()));
140        }
141        this.backoffCounter = new BackoffCounter(new Time());
142        this.shouldAuthenticate = true;
143        if (api != null) {
144            this.connectTimeout = api.getConnectTimeout();
145            this.readTimeout = api.getReadTimeout();
146        } else {
147            this.connectTimeout = BoxGlobalSettings.getConnectTimeout();
148            this.readTimeout = BoxGlobalSettings.getReadTimeout();
149        }
150
151        this.addHeader("Accept-Encoding", "gzip");
152        this.addHeader("Accept-Charset", "utf-8");
153
154    }
155
156    /**
157     * Constructs an authenticated BoxAPIRequest using a provided BoxAPIConnection.
158     *
159     * @param api    an API connection for authenticating the request.
160     * @param url    the URL of the request.
161     * @param method the HTTP method of the request.
162     */
163    public BoxAPIRequest(BoxAPIConnection api, URL url, HttpMethod method) {
164        this(api, url, method.name());
165    }
166
167    /**
168     * Constructs an request, using URL and HttpMethod.
169     *
170     * @param url    the URL of the request.
171     * @param method the HTTP method of the request.
172     */
173    public BoxAPIRequest(URL url, HttpMethod method) {
174        this(url, method.name());
175    }
176
177    /**
178     * @param apiException BoxAPIException thrown
179     * @return true if the request is one that should be retried, otherwise false
180     */
181    public static boolean isRequestRetryable(BoxAPIException apiException) {
182        // Only requests that failed to send should be retried
183        return (Objects.equals(apiException.getMessage(), ERROR_CREATING_REQUEST_BODY));
184    }
185
186    /**
187     * @param responseCode HTTP error code of the response
188     * @param apiException BoxAPIException thrown
189     * @return true if the response is one that should be retried, otherwise false
190     */
191    public static boolean isResponseRetryable(int responseCode, BoxAPIException apiException) {
192        String response = apiException.getResponse();
193        String message = apiException.getMessage();
194        String errorCode = "";
195
196        try {
197            JsonObject responseBody = Json.parse(response).asObject();
198            if (responseBody.get("code") != null) {
199                errorCode = responseBody.get("code").toString();
200            }
201        } catch (Exception e) {
202        }
203
204        Boolean isClockSkewError = responseCode == 400
205            && errorCode.contains("invalid_grant")
206            && message.contains("exp");
207
208        return (isClockSkewError
209            || responseCode >= 500
210            || responseCode == 429);
211    }
212
213    private static boolean isResponseRedirect(int responseCode) {
214        return (responseCode == 301 || responseCode == 302);
215    }
216
217    /**
218     * Adds an HTTP header to this request.
219     *
220     * @param key   the header key.
221     * @param value the header value.
222     */
223    public void addHeader(String key, String value) {
224        if (key.equals("As-User")) {
225            for (int i = 0; i < this.headers.size(); i++) {
226                if (this.headers.get(i).getKey().equals("As-User")) {
227                    this.headers.remove(i);
228                }
229            }
230        }
231        if (key.equals("X-Box-UA")) {
232            throw new IllegalArgumentException("Altering the X-Box-UA header is not permitted");
233        }
234        this.headers.add(new RequestHeader(key, value));
235    }
236
237    /**
238     * Gets the connect timeout for the request.
239     *
240     * @return the request connection timeout.
241     */
242    public int getConnectTimeout() {
243        return this.connectTimeout;
244    }
245
246    /**
247     * Sets a Connect timeout for this request in milliseconds.
248     *
249     * @param timeout the timeout in milliseconds.
250     */
251    public void setConnectTimeout(int timeout) {
252        this.connectTimeout = timeout;
253    }
254
255    /**
256     * Gets the read timeout for the request.
257     *
258     * @return the request's read timeout.
259     */
260    public int getReadTimeout() {
261        return this.readTimeout;
262    }
263
264    /**
265     * Sets a read timeout for this request in milliseconds.
266     *
267     * @param timeout the timeout in milliseconds.
268     */
269    public void setReadTimeout(int timeout) {
270        this.readTimeout = timeout;
271    }
272
273    /**
274     * Sets whether or not to follow redirects (i.e. Location header)
275     *
276     * @param followRedirects true to follow, false to not follow
277     */
278    public void setFollowRedirects(boolean followRedirects) {
279        this.followRedirects = followRedirects;
280    }
281
282    /**
283     * Gets the stream containing contents of this request's body.
284     *
285     * <p>Note that any bytes that read from the returned stream won't be sent unless the stream is reset back to its
286     * initial position.</p>
287     *
288     * @return an InputStream containing the contents of this request's body.
289     */
290    public InputStream getBody() {
291        return this.body;
292    }
293
294    /**
295     * Sets the request body to the contents of an InputStream.
296     *
297     * <p>The stream must support the {@link InputStream#reset} method if auto-retry is used or if the request needs to
298     * be resent. Otherwise, the body must be manually set before each call to {@link #send}.</p>
299     *
300     * @param stream an InputStream containing the contents of the body.
301     */
302    public void setBody(InputStream stream) {
303        this.body = stream;
304    }
305
306    /**
307     * Sets the request body to the contents of a String.
308     *
309     * <p>If the contents of the body are large, then it may be more efficient to use an {@link InputStream} instead of
310     * a String. Using a String requires that the entire body be in memory before sending the request.</p>
311     *
312     * @param body a String containing the contents of the body.
313     */
314    public void setBody(String body) {
315        byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
316        this.bodyLength = bytes.length;
317        this.body = new ByteArrayInputStream(bytes);
318    }
319
320    /**
321     * Sets the request body to the contents of an InputStream.
322     *
323     * <p>Providing the length of the InputStream allows for the progress of the request to be monitored when calling
324     * {@link #send(ProgressListener)}.</p>
325     *
326     * <p> See {@link #setBody(InputStream)} for more information on setting the body of the request.</p>
327     *
328     * @param stream an InputStream containing the contents of the body.
329     * @param length the expected length of the stream.
330     */
331    public void setBody(InputStream stream, long length) {
332        this.bodyLength = length;
333        this.body = stream;
334    }
335
336    /**
337     * Gets the URL from the request.
338     *
339     * @return a URL containing the URL of the request.
340     */
341    public URL getUrl() {
342        return this.url;
343    }
344
345    /**
346     * Gets the http method from the request.
347     *
348     * @return http method
349     */
350    public String getMethod() {
351        return this.method;
352    }
353
354    /**
355     * Get headers as list of RequestHeader objects.
356     *
357     * @return headers as list of RequestHeader objects
358     */
359    protected List<RequestHeader> getHeaders() {
360        return this.headers;
361    }
362
363    /**
364     * Sends this request and returns a BoxAPIResponse containing the server's response.
365     *
366     * <p>The type of the returned BoxAPIResponse will be based on the content type returned by the server, allowing it
367     * to be cast to a more specific type. For example, if it's known that the API call will return a JSON response,
368     * then it can be cast to a {@link BoxJSONResponse} like so:</p>
369     *
370     * <pre>BoxJSONResponse response = (BoxJSONResponse) request.sendWithoutRetry();</pre>
371     *
372     * @return a {@link BoxAPIResponse} containing the server's response.
373     * @throws BoxAPIException if the server returns an error code or if a network error occurs.
374     */
375    public BoxAPIResponse sendWithoutRetry() {
376        return this.trySend(null);
377    }
378
379    /**
380     * Sends this request and returns a BoxAPIResponse containing the server's response.
381     *
382     * <p>The type of the returned BoxAPIResponse will be based on the content type returned by the server, allowing it
383     * to be cast to a more specific type. For example, if it's known that the API call will return a JSON response,
384     * then it can be cast to a {@link BoxJSONResponse} like so:</p>
385     *
386     * <pre>BoxJSONResponse response = (BoxJSONResponse) request.send();</pre>
387     *
388     * <p>If the server returns an error code or if a network error occurs, then the request will be automatically
389     * retried. If the maximum number of retries is reached and an error still occurs, then a {@link BoxAPIException}
390     * will be thrown.</p>
391     *
392     * <p> See {@link #send} for more information on sending requests.</p>
393     *
394     * @return a {@link BoxAPIResponse} containing the server's response.
395     * @throws BoxAPIException if the server returns an error code or if a network error occurs.
396     */
397    public BoxAPIResponse send() {
398        return this.send(null);
399    }
400
401    /**
402     * Sends this request while monitoring its progress and returns a BoxAPIResponse containing the server's response.
403     *
404     * <p>The type of the returned BoxAPIResponse will be based on the content type returned by the server, allowing it
405     * to be cast to a more specific type. For example, if it's known that the API call will return a JSON response,
406     * then it can be cast to a {@link BoxJSONResponse} like so:</p>
407     *
408     * <p>If the server returns an error code or if a network error occurs, then the request will be automatically
409     * retried. If the maximum number of retries is reached and an error still occurs, then a {@link BoxAPIException}
410     * will be thrown.</p>
411     *
412     * <p>A ProgressListener is generally only useful when the size of the request is known beforehand. If the size is
413     * unknown, then the ProgressListener will be updated for each byte sent, but the total number of bytes will be
414     * reported as 0.</p>
415     *
416     * <p> See {@link #send} for more information on sending requests.</p>
417     *
418     * @param listener a listener for monitoring the progress of the request.
419     * @return a {@link BoxAPIResponse} containing the server's response.
420     * @throws BoxAPIException if the server returns an error code or if a network error occurs.
421     */
422    public BoxAPIResponse send(ProgressListener listener) {
423        if (this.api == null) {
424            this.backoffCounter.reset(BoxGlobalSettings.getMaxRetryAttempts() + 1);
425        } else {
426            this.backoffCounter.reset(this.api.getMaxRetryAttempts() + 1);
427        }
428
429        while (this.backoffCounter.getAttemptsRemaining() > 0) {
430            try {
431                return this.trySend(listener);
432            } catch (BoxAPIException apiException) {
433                if (!this.backoffCounter.decrement()
434                    || (!isRequestRetryable(apiException)
435                    && !isResponseRetryable(apiException.getResponseCode(), apiException))) {
436                    throw apiException;
437                }
438
439                LOGGER.warn(
440                    String.format("Retrying request due to transient error status=%d body=%s",
441                        apiException.getResponseCode(),
442                        apiException.getResponse())
443                );
444
445                try {
446                    this.resetBody();
447                } catch (IOException ioException) {
448                    throw apiException;
449                }
450
451                try {
452                    List<String> retryAfterHeader = apiException.getHeaders().get("Retry-After");
453                    if (retryAfterHeader == null) {
454                        this.backoffCounter.waitBackoff();
455                    } else {
456                        int retryAfterDelay = Integer.parseInt(retryAfterHeader.get(0));
457                        this.backoffCounter.waitBackoff(retryAfterDelay);
458                    }
459                } catch (InterruptedException interruptedException) {
460                    Thread.currentThread().interrupt();
461                    throw apiException;
462                }
463            }
464        }
465
466        throw new RuntimeException();
467    }
468
469    /**
470     * Sends a request to upload a file part and returns a BoxFileUploadSessionPart containing information
471     * about the upload part. This method is separate from send() because it has custom retry logic.
472     *
473     * <p>If the server returns an error code or if a network error occurs, then the request will be automatically
474     * retried. If the maximum number of retries is reached and an error still occurs, then a {@link BoxAPIException}
475     * will be thrown.</p>
476     *
477     * @param session The BoxFileUploadSession uploading the part
478     * @param offset  Offset of the part being uploaded
479     * @return A {@link BoxFileUploadSessionPart} part that has been uploaded.
480     * @throws BoxAPIException if the server returns an error code or if a network error occurs.
481     */
482    BoxFileUploadSessionPart sendForUploadPart(BoxFileUploadSession session, long offset) {
483        if (this.api == null) {
484            this.backoffCounter.reset(BoxGlobalSettings.getMaxRetryAttempts() + 1);
485        } else {
486            this.backoffCounter.reset(this.api.getMaxRetryAttempts() + 1);
487        }
488
489        while (this.backoffCounter.getAttemptsRemaining() > 0) {
490            try {
491                BoxJSONResponse response = (BoxJSONResponse) this.trySend(null);
492                JsonObject jsonObject = Json.parse(response.getJSON()).asObject();
493                return new BoxFileUploadSessionPart((JsonObject) jsonObject.get("part"));
494            } catch (BoxAPIException apiException) {
495                if (!this.backoffCounter.decrement()
496                    || (!isRequestRetryable(apiException)
497                    && !isResponseRetryable(apiException.getResponseCode(), apiException))) {
498                    throw apiException;
499                }
500                if (apiException.getResponseCode() == 500) {
501                    try {
502                        Iterable<BoxFileUploadSessionPart> parts = session.listParts();
503                        for (BoxFileUploadSessionPart part : parts) {
504                            if (part.getOffset() == offset) {
505                                return part;
506                            }
507                        }
508                    } catch (BoxAPIException e) {
509                    }
510                }
511                LOGGER.warn(String.format(
512                    "Retrying request due to transient error status=%d body=%s",
513                    apiException.getResponseCode(),
514                    apiException.getResponse()
515                ));
516
517                try {
518                    this.resetBody();
519                } catch (IOException ioException) {
520                    throw apiException;
521                }
522
523                try {
524                    this.backoffCounter.waitBackoff();
525                } catch (InterruptedException interruptedException) {
526                    Thread.currentThread().interrupt();
527                    throw apiException;
528                }
529            }
530        }
531
532        throw new RuntimeException();
533    }
534
535    /**
536     * Returns a String containing the URL, HTTP method, headers and body of this request.
537     *
538     * @return a String containing information about this request.
539     */
540    @Override
541    public String toString() {
542        String lineSeparator = System.getProperty("line.separator");
543        StringBuilder builder = new StringBuilder();
544        builder.append("Request");
545        builder.append(lineSeparator);
546        builder.append(this.method);
547        builder.append(' ');
548        builder.append(this.url.toString());
549        builder.append(lineSeparator);
550
551        if (this.requestProperties != null) {
552
553            for (Map.Entry<String, List<String>> entry : this.requestProperties.entrySet()) {
554                List<String> nonEmptyValues = new ArrayList<>();
555                for (String value : entry.getValue()) {
556                    if (value != null && value.trim().length() != 0) {
557                        nonEmptyValues.add(value);
558                    }
559                }
560
561                if (nonEmptyValues.size() == 0) {
562                    continue;
563                }
564
565                builder.append(entry.getKey());
566                builder.append(": ");
567                for (String value : nonEmptyValues) {
568                    builder.append(value);
569                    builder.append(", ");
570                }
571
572                builder.delete(builder.length() - 2, builder.length());
573                builder.append(lineSeparator);
574            }
575        }
576
577        String bodyString = this.bodyToString();
578        if (bodyString != null) {
579            builder.append(lineSeparator);
580            builder.append(bodyString);
581        }
582
583        return builder.toString().trim();
584    }
585
586    /**
587     * Returns a String representation of this request's body used in {@link #toString}. This method returns
588     * null by default.
589     *
590     * <p>A subclass may want override this method if the body can be converted to a String for logging or debugging
591     * purposes.</p>
592     *
593     * @return a String representation of this request's body.
594     */
595    protected String bodyToString() {
596        return null;
597    }
598
599    /**
600     * Writes the body of this request to an HttpURLConnection.
601     *
602     * <p>Subclasses overriding this method must remember to close the connection's OutputStream after writing.</p>
603     *
604     * @param connection the connection to which the body should be written.
605     * @param listener   an optional listener for monitoring the write progress.
606     * @throws BoxAPIException if an error occurs while writing to the connection.
607     */
608    protected void writeBody(HttpURLConnection connection, ProgressListener listener) {
609        if (this.body == null) {
610            return;
611        }
612
613        connection.setDoOutput(true);
614        try {
615            OutputStream output = connection.getOutputStream();
616            if (listener != null) {
617                output = new ProgressOutputStream(output, listener, this.bodyLength);
618            }
619            int b = this.body.read();
620            while (b != -1) {
621                output.write(b);
622                b = this.body.read();
623            }
624            output.close();
625        } catch (IOException e) {
626            throw new BoxAPIException(ERROR_CREATING_REQUEST_BODY, e);
627        }
628    }
629
630    /**
631     * Resets the InputStream containing this request's body.
632     *
633     * <p>This method will be called before each attempt to resend the request, giving subclasses an opportunity to
634     * reset any streams that need to be read when sending the body.</p>
635     *
636     * @throws IOException if the stream cannot be reset.
637     */
638    protected void resetBody() throws IOException {
639        if (this.body != null) {
640            this.body.reset();
641        }
642    }
643
644    void setBackoffCounter(BackoffCounter counter) {
645        this.backoffCounter = counter;
646    }
647
648    private BoxAPIResponse trySend(ProgressListener listener) {
649        if (this.api != null) {
650            RequestInterceptor interceptor = this.api.getRequestInterceptor();
651            if (interceptor != null) {
652                BoxAPIResponse response = interceptor.onRequest(this);
653                if (response != null) {
654                    return response;
655                }
656            }
657        }
658
659        HttpURLConnection connection = this.createConnection();
660
661        if (connection instanceof HttpsURLConnection) {
662            HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
663
664            if (sslSocketFactory != null) {
665                httpsConnection.setSSLSocketFactory(sslSocketFactory);
666            }
667        }
668
669        if (this.bodyLength > 0) {
670            connection.setFixedLengthStreamingMode((int) this.bodyLength);
671            connection.setDoOutput(true);
672        }
673
674        if (this.api != null) {
675            if (this.shouldAuthenticate) {
676                connection.addRequestProperty(HttpHeaders.AUTHORIZATION, "Bearer " + this.api.lockAccessToken());
677            }
678            connection.setRequestProperty("User-Agent", this.api.getUserAgent());
679            if (this.api.getProxy() != null) {
680                if (this.api.getProxyUsername() != null && this.api.getProxyPassword() != null) {
681                    String usernameAndPassword = this.api.getProxyUsername() + ":" + this.api.getProxyPassword();
682                    String encoded = Base64.encode(usernameAndPassword.getBytes());
683                    connection.addRequestProperty("Proxy-Authorization", "Basic " + encoded);
684                }
685            }
686
687            if (this.api instanceof SharedLinkAPIConnection) {
688                SharedLinkAPIConnection sharedItemAPI = (SharedLinkAPIConnection) this.api;
689                String sharedLink = sharedItemAPI.getSharedLink();
690                String boxAPIValue = "shared_link=" + sharedLink;
691                String sharedLinkPassword = sharedItemAPI.getSharedLinkPassword();
692                if (sharedLinkPassword != null) {
693                    boxAPIValue += "&shared_link_password=" + sharedLinkPassword;
694                }
695                connection.addRequestProperty("BoxApi", boxAPIValue);
696            }
697        }
698
699        this.requestProperties = connection.getRequestProperties();
700
701        int responseCode;
702        try {
703            this.writeBody(connection, listener);
704
705            // Ensure that we're connected in case writeBody() didn't write anything.
706            try {
707                connection.connect();
708            } catch (IOException e) {
709                throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e);
710            }
711
712            this.logRequest();
713
714            // We need to manually handle redirects by creating a new HttpURLConnection so that connection pooling
715            // happens correctly. There seems to be a bug in Oracle's Java implementation where automatically handled
716            // redirects will not keep the connection alive.
717            try {
718                responseCode = connection.getResponseCode();
719            } catch (IOException e) {
720                throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e);
721            }
722        } finally {
723            if (this.api != null && this.shouldAuthenticate) {
724                this.api.unlockAccessToken();
725            }
726        }
727
728        if (isResponseRedirect(responseCode)) {
729            return this.handleRedirect(connection, listener);
730        }
731
732        String contentType = connection.getContentType();
733        BoxAPIResponse response;
734        if (contentType == null) {
735            response = new BoxAPIResponse(connection);
736        } else if (contentType.contains("application/json")) {
737            response = new BoxJSONResponse(connection);
738        } else {
739            response = new BoxAPIResponse(connection);
740        }
741
742        return response;
743    }
744
745    private BoxAPIResponse handleRedirect(HttpURLConnection connection, ProgressListener listener) {
746        if (this.numRedirects >= MAX_REDIRECTS) {
747            throw new BoxAPIException("The Box API responded with too many redirects.");
748        }
749        this.numRedirects++;
750
751        // Even though the redirect response won't have a body, we need to read the InputStream so that Java will put
752        // the connection back in the connection pool.
753        try {
754            InputStream stream = connection.getInputStream();
755            byte[] buffer = new byte[8192];
756            int n = stream.read(buffer);
757            while (n != -1) {
758                n = stream.read(buffer);
759            }
760            stream.close();
761        } catch (IOException e) {
762            throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e);
763        }
764
765        String redirect = connection.getHeaderField("Location");
766        try {
767            this.url = new URL(redirect);
768        } catch (MalformedURLException e) {
769            throw new BoxAPIException("The Box API responded with an invalid redirect.", e);
770        }
771
772        if (this.followRedirects) {
773            return this.trySend(listener);
774        } else {
775            BoxRedirectResponse redirectResponse = new BoxRedirectResponse();
776            redirectResponse.setRedirectURL(this.url);
777            return redirectResponse;
778        }
779    }
780
781    private void logRequest() {
782        if (LOGGER.isDebugEnabled()) {
783            LOGGER.debug(this.toString());
784        }
785    }
786
787    private HttpURLConnection createConnection() {
788        HttpURLConnection connection;
789
790        try {
791            if (this.api == null || this.api.getProxy() == null) {
792                connection = (HttpURLConnection) this.url.openConnection();
793            } else {
794                connection = (HttpURLConnection) this.url.openConnection(this.api.getProxy());
795            }
796        } catch (IOException e) {
797            throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e);
798        }
799
800        try {
801            connection.setRequestMethod(this.method);
802        } catch (ProtocolException e) {
803            throw new BoxAPIException("Couldn't connect to the Box API because the request's method was invalid.", e);
804        }
805
806        connection.setConnectTimeout(this.connectTimeout);
807        connection.setReadTimeout(this.readTimeout);
808
809        // Don't allow HttpURLConnection to automatically redirect because it messes up the connection pool. See the
810        // trySend(ProgressListener) method for how we handle redirects.
811        connection.setInstanceFollowRedirects(false);
812
813        for (RequestHeader header : this.headers) {
814            connection.addRequestProperty(header.getKey(), header.getValue());
815        }
816
817        return connection;
818    }
819
820    void shouldAuthenticate(boolean shouldAuthenticate) {
821        this.shouldAuthenticate = shouldAuthenticate;
822    }
823
824    /**
825     * Class for mapping a request header and value.
826     */
827    public final class RequestHeader {
828        private final String key;
829        private final String value;
830
831        /**
832         * Construct a request header from header key and value.
833         *
834         * @param key   header name
835         * @param value header value
836         */
837        public RequestHeader(String key, String value) {
838            this.key = key;
839            this.value = value;
840        }
841
842        /**
843         * Get header key.
844         *
845         * @return http header name
846         */
847        public String getKey() {
848            return this.key;
849        }
850
851        /**
852         * Get header value.
853         *
854         * @return http header value
855         */
856        public String getValue() {
857            return this.value;
858        }
859    }
860}