001package com.box.sdk; 002 003import java.io.IOException; 004import java.io.InputStream; 005import java.io.InputStreamReader; 006import java.net.HttpURLConnection; 007import java.util.ArrayList; 008import java.util.List; 009import java.util.Map; 010import java.util.logging.Level; 011import java.util.logging.Logger; 012import java.util.zip.GZIPInputStream; 013 014/** 015 * Used to read HTTP responses from the Box API. 016 * 017 * <p>All responses from the REST API are read using this class or one of its subclasses. This class wraps {@link 018 * HttpURLConnection} in order to provide a simpler interface that can automatically handle various conditions specific 019 * to Box's API. When a response is contructed, it will throw a {@link BoxAPIException} if the response from the API 020 * was an error. Therefore every BoxAPIResponse instance is guaranteed to represent a successful response.</p> 021 * 022 * <p>This class usually isn't instantiated directly, but is instead returned after calling {@link BoxAPIRequest#send}. 023 * </p> 024 */ 025public class BoxAPIResponse { 026 private static final Logger LOGGER = Logger.getLogger(BoxAPIResponse.class.getName()); 027 private static final int BUFFER_SIZE = 8192; 028 029 private final HttpURLConnection connection; 030 031 private int responseCode; 032 private String bodyString; 033 034 /** 035 * The raw InputStream is the stream returned directly from HttpURLConnection.getInputStream(). We need to keep 036 * track of this stream in case we need to access it after wrapping it inside another stream. 037 */ 038 private InputStream rawInputStream; 039 040 /** 041 * The regular InputStream is the stream that will be returned by getBody(). This stream might be a GZIPInputStream 042 * or a ProgressInputStream (or both) that wrap the raw InputStream. 043 */ 044 private InputStream inputStream; 045 046 /** 047 * Constructs an empty BoxAPIResponse without an associated HttpURLConnection. 048 */ 049 public BoxAPIResponse() { 050 this.connection = null; 051 } 052 053 /** 054 * Constructs a BoxAPIResponse using an HttpURLConnection. 055 * @param connection a connection that has already sent a request to the API. 056 */ 057 public BoxAPIResponse(HttpURLConnection connection) { 058 this.connection = connection; 059 this.inputStream = null; 060 061 try { 062 this.responseCode = this.connection.getResponseCode(); 063 } catch (IOException e) { 064 throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e); 065 } 066 067 if (!isSuccess(this.responseCode)) { 068 this.logResponse(); 069 throw new BoxAPIException("The API returned an error code: " + this.responseCode, this.responseCode, 070 this.bodyToString()); 071 } 072 073 this.logResponse(); 074 } 075 076 /** 077 * Gets the response code returned by the API. 078 * @return the response code returned by the API. 079 */ 080 public int getResponseCode() { 081 return this.responseCode; 082 } 083 084 /** 085 * Gets the length of this response's body as indicated by the "Content-Length" header. 086 * @return the length of the response's body. 087 */ 088 public long getContentLength() { 089 return this.connection.getContentLength(); 090 } 091 092 /** 093 * Gets an InputStream for reading this response's body. 094 * @return an InputStream for reading the response's body. 095 */ 096 public InputStream getBody() { 097 return this.getBody(null); 098 } 099 100 /** 101 * Gets an InputStream for reading this response's body which will report its read progress to a ProgressListener. 102 * @param listener a listener for monitoring the read progress of the body. 103 * @return an InputStream for reading the response's body. 104 */ 105 public InputStream getBody(ProgressListener listener) { 106 if (this.inputStream == null) { 107 String contentEncoding = this.connection.getContentEncoding(); 108 try { 109 if (this.rawInputStream == null) { 110 this.rawInputStream = this.connection.getInputStream(); 111 } 112 113 if (listener == null) { 114 this.inputStream = this.rawInputStream; 115 } else { 116 this.inputStream = new ProgressInputStream(this.rawInputStream, listener, 117 this.getContentLength()); 118 } 119 120 if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) { 121 this.inputStream = new GZIPInputStream(this.inputStream); 122 } 123 } catch (IOException e) { 124 throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e); 125 } 126 } 127 128 return this.inputStream; 129 } 130 131 /** 132 * Disconnects this response from the server and frees up any network resources. The body of this response can no 133 * longer be read after it has been disconnected. 134 */ 135 public void disconnect() { 136 if (this.connection == null) { 137 return; 138 } 139 140 try { 141 if (this.rawInputStream == null) { 142 this.rawInputStream = this.connection.getInputStream(); 143 } 144 145 // We need to manually read from the raw input stream in case there are any remaining bytes. There's a bug 146 // where a wrapping GZIPInputStream may not read to the end of a chunked response, causing Java to not 147 // return the connection to the connection pool. 148 byte[] buffer = new byte[BUFFER_SIZE]; 149 int n = this.rawInputStream.read(buffer); 150 while (n != -1) { 151 n = this.rawInputStream.read(buffer); 152 } 153 this.rawInputStream.close(); 154 155 if (this.inputStream != null) { 156 this.inputStream.close(); 157 } 158 } catch (IOException e) { 159 throw new BoxAPIException("Couldn't finish closing the connection to the Box API due to a network error or " 160 + "because the stream was already closed.", e); 161 } 162 } 163 164 @Override 165 public String toString() { 166 String lineSeparator = System.getProperty("line.separator"); 167 Map<String, List<String>> headers = this.connection.getHeaderFields(); 168 StringBuilder builder = new StringBuilder(); 169 builder.append("Response"); 170 builder.append(lineSeparator); 171 builder.append(this.connection.getRequestMethod()); 172 builder.append(' '); 173 builder.append(this.connection.getURL().toString()); 174 builder.append(lineSeparator); 175 builder.append(headers.get(null).get(0)); 176 builder.append(lineSeparator); 177 178 for (Map.Entry<String, List<String>> entry : headers.entrySet()) { 179 String key = entry.getKey(); 180 if (key == null) { 181 continue; 182 } 183 184 List<String> nonEmptyValues = new ArrayList<String>(); 185 for (String value : entry.getValue()) { 186 if (value != null && value.trim().length() != 0) { 187 nonEmptyValues.add(value); 188 } 189 } 190 191 if (nonEmptyValues.size() == 0) { 192 continue; 193 } 194 195 builder.append(key); 196 builder.append(": "); 197 for (String value : nonEmptyValues) { 198 builder.append(value); 199 builder.append(", "); 200 } 201 202 builder.delete(builder.length() - 2, builder.length()); 203 builder.append(lineSeparator); 204 } 205 206 String bodyString = this.bodyToString(); 207 if (bodyString != null && bodyString != "") { 208 builder.append(lineSeparator); 209 builder.append(bodyString); 210 } 211 212 return builder.toString().trim(); 213 } 214 215 /** 216 * Returns a string representation of this response's body. This method is used when logging this response's body. 217 * By default, it returns an empty string (to avoid accidentally logging binary data) unless the response contained 218 * an error message. 219 * @return a string representation of this response's body. 220 */ 221 protected String bodyToString() { 222 if (this.bodyString == null && !isSuccess(this.responseCode)) { 223 this.bodyString = readErrorStream(this.getErrorStream()); 224 } 225 226 return this.bodyString; 227 } 228 229 /** 230 * Returns the response error stream, handling the case when it contains gzipped data. 231 * @return gzip decoded (if needed) error stream or null 232 */ 233 private InputStream getErrorStream() { 234 InputStream errorStream = this.connection.getErrorStream(); 235 if (errorStream != null) { 236 final String contentEncoding = this.connection.getContentEncoding(); 237 if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) { 238 try { 239 errorStream = new GZIPInputStream(errorStream); 240 } catch (IOException e) { 241 // just return the error stream as is 242 } 243 } 244 } 245 246 return errorStream; 247 } 248 249 private void logResponse() { 250 if (LOGGER.isLoggable(Level.FINE)) { 251 LOGGER.log(Level.FINE, this.toString()); 252 } 253 } 254 255 private static boolean isSuccess(int responseCode) { 256 return responseCode >= 200 && responseCode < 300; 257 } 258 259 private static String readErrorStream(InputStream stream) { 260 if (stream == null) { 261 return null; 262 } 263 264 InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8); 265 StringBuilder builder = new StringBuilder(); 266 char[] buffer = new char[BUFFER_SIZE]; 267 268 try { 269 int read = reader.read(buffer, 0, BUFFER_SIZE); 270 while (read != -1) { 271 builder.append(buffer, 0, read); 272 read = reader.read(buffer, 0, BUFFER_SIZE); 273 } 274 275 reader.close(); 276 } catch (IOException e) { 277 return null; 278 } 279 280 return builder.toString(); 281 } 282}