001package com.box.sdk;
002
003import java.util.ArrayList;
004import java.util.HashMap;
005import java.util.List;
006import java.util.Map;
007
008import com.eclipsesource.json.JsonObject;
009
010
011
012/**
013 * Thrown to indicate than an error occured while returning with a response from the Box API.
014 */
015public class BoxAPIResponseException extends BoxAPIException {
016
017    private String message;
018    private BoxAPIResponse responseObj;
019
020    /**
021     * Constructs a BoxAPIException that contains detailed message for underlying exception.
022     *
023     * @param message     a message explaining why the error occurred.
024     * @param responseObj a response object from the server.
025     */
026    public BoxAPIResponseException(String message, BoxAPIResponse responseObj) {
027        super(message, responseObj.getResponseCode(), responseObj.bodyToString());
028        String requestId = "";
029        String apiMessage = "";
030        JsonObject responseJSON = null;
031        this.responseObj = responseObj;
032
033        Map<String, List<String>> responseHeaders = new HashMap<String, List<String>>();
034        for (String headerKey : responseObj.getHeaders().keySet()) {
035            List<String> headerValues = new ArrayList<String>();
036            headerValues.add(responseObj.getHeaderField(headerKey));
037            responseHeaders.put(headerKey, headerValues);
038        }
039
040        this.setHeaders(responseHeaders);
041
042        if (responseObj.bodyToString() != null && !responseObj.bodyToString().equals("")) {
043            responseJSON = JsonObject.readFrom(responseObj.bodyToString());
044
045            if (responseObj.bodyToString() != null && responseJSON.get("request_id") != null) {
046                requestId = " | " + responseJSON.get("request_id").asString();
047            }
048
049            if (responseObj.bodyToString() != null && responseJSON.get("code") != null) {
050                apiMessage += " " + responseJSON.get("code").asString();
051            }
052
053            if (responseObj.bodyToString() != null && responseJSON.get("message") != null) {
054                apiMessage += " - " + responseJSON.get("message").asString();
055            }
056
057            this.setMessage(message + " [" + responseObj.getResponseCode() + requestId + "]" + apiMessage);
058
059        } else {
060            this.setMessage(message + " [" + responseObj.getResponseCode() + "]");
061        }
062    }
063
064    /**
065     * The message to return for the API exception.
066     * @param message the constructed for the API exception.
067     */
068    protected void setMessage(String message) {
069        this.message = message;
070    }
071
072    /**
073     *
074     * @return The constructed message for the API exception.
075     */
076    public String getMessage() {
077        return this.message;
078    }
079}