org.opentestsystem.shared.trapi.exception.TrApiResponseErrorHandler.java Source code

Java tutorial

Introduction

Here is the source code for org.opentestsystem.shared.trapi.exception.TrApiResponseErrorHandler.java

Source

/*******************************************************************************
 * Educational Online Test Delivery System 
 * Copyright (c) 2014 American Institutes for Research
 *   
 * Distributed under the AIR Open Source License, Version 1.0 
 * See accompanying file AIR-License-1_0.txt or at
 * http://www.smarterapp.org/documents/American_Institutes_for_Research_Open_Source_Software_License.pdf
 ******************************************************************************/
package org.opentestsystem.shared.trapi.exception;

import java.io.IOException;

import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.ResponseErrorHandler;

import AIR.Common.Json.JsonHelper;

/**
 * @author jmambo
 *
 */
public class TrApiResponseErrorHandler implements ResponseErrorHandler {

    private ResponseErrorHandler errorHandler = new DefaultResponseErrorHandler();

    public boolean hasError(ClientHttpResponse response) throws IOException {
        return errorHandler.hasError(response);
    }

    public void handleError(ClientHttpResponse response) throws IOException {
        String responseString = IOUtils.toString(response.getBody());
        try {
            ResponseMessage message = JsonHelper.deserialize(responseString, ResponseMessage.class);
            responseString = message.getMessages();
        } catch (Exception ex) {
            //not all response are of message type hence use original string
        }
        String statusCode = response.getStatusCode().name();
        if (response.getStatusCode() == HttpStatus.NOT_IMPLEMENTED) {
            if (TrApiErrorCode.LOCAL_OK.getCode().equals(responseString)) {
                statusCode = responseString;
            }
        }
        TrApiException exception = new TrApiException(statusCode, responseString);
        throw exception;
    }

}