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