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