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