001package com.box.sdk;
002
003import java.io.IOException;
004import java.io.InputStreamReader;
005import java.net.HttpURLConnection;
006
007/**
008 * Used to read HTTP responses containing JSON from the Box API.
009 *
010 * <p>This request type extends BoxAPIResponse to provide additional functionality for handling JSON strings. It reads
011 * the response body into a string and allows the JSON in the response to be logged.</p>
012 */
013public class BoxJSONResponse extends BoxAPIResponse {
014    private static final int BUFFER_SIZE = 8192;
015
016    private String json;
017
018    /**
019     * Constructs a BoxJSONResponse without an associated HttpURLConnection.
020     */
021    public BoxJSONResponse() {
022        super();
023    }
024
025    /**
026     * Constructs a BoxJSONResponse using an HttpURLConnection.
027     * @param  connection a connection that has already sent a request to the API.
028     */
029    public BoxJSONResponse(HttpURLConnection connection) {
030        super(connection);
031    }
032
033    /**
034     * Gets the body of the response as a JSON string. When this method is called, the response's body will be read and
035     * the response will be disconnected, meaning that the stream returned by {@link #getBody} can no longer be used.
036     * @return the body of the response as a JSON string.
037     */
038    public String getJSON() {
039        if (this.json != null) {
040            return this.json;
041        }
042
043        InputStreamReader reader = new InputStreamReader(this.getBody(), StandardCharsets.UTF_8);
044        StringBuilder builder = new StringBuilder();
045        char[] buffer = new char[BUFFER_SIZE];
046
047        try {
048            int read = reader.read(buffer, 0, BUFFER_SIZE);
049            while (read != -1) {
050                builder.append(buffer, 0, read);
051                read = reader.read(buffer, 0, BUFFER_SIZE);
052            }
053
054            this.disconnect();
055            reader.close();
056        } catch (IOException e) {
057            throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e);
058        }
059        this.json = builder.toString();
060        return this.json;
061    }
062
063    @Override
064    protected String bodyToString() {
065        String bodyString = super.bodyToString();
066        if (bodyString == null) {
067            return this.getJSON();
068        } else {
069            return bodyString;
070        }
071    }
072}