org.opentestsystem.shared.trapi.TrClient.java Source code

Java tutorial

Introduction

Here is the source code for org.opentestsystem.shared.trapi.TrClient.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;

import java.net.URI;
import java.net.URISyntaxException;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.StringUtils;
import org.opentestsystem.shared.trapi.exception.TrApiErrorCode;
import org.opentestsystem.shared.trapi.exception.TrApiException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import AIR.Common.Json.JsonHelper;

/**
 * @author jmambo
 *
 */
public class TrClient implements ITrClient {

    private static final Logger _logger = LoggerFactory.getLogger(TrClient.class);

    @Value("${TestRegistrationApplicationUrl}")
    private String _testRegistrationApplicationUrl;

    private boolean _isLocal;

    @Autowired
    private ITrRestApiClient _trRestApiClient;

    @PostConstruct
    private void init() {
        if (StringUtils.isBlank(_testRegistrationApplicationUrl)) {
            _logger.warn("TrClient: TestRegistrationApplicationUrl is not provided");
        }
        if (!_testRegistrationApplicationUrl.endsWith("/")) {
            _testRegistrationApplicationUrl += "/";
        }
        setLocal();
    }

    @Override
    public String getPackage(String url) {
        return getForObject(url, TrApiContentType.XML);
    }

    @Override
    public String getForObject(String url) {
        return getForObject(url, TrApiContentType.JSON);
    }

    @Override
    public <T> T getForObject(String url, Class<T> responseType) {
        return getForObject(url, TrApiContentType.JSON, responseType);
    }

    @Override
    public String getForObject(String url, TrApiContentType contentType) {
        return getForObject(url, contentType, String.class);
    }

    @Override
    public <T> T getForObject(String url, TrApiContentType contentType, Class<T> responseType) {
        ResponseEntity<T> entity = exchange(url, null, contentType, HttpMethod.GET, responseType);
        return entity.getBody();
    }

    @Override
    public <T> T postForObject(String url, Object request, Class<T> responseType) {
        try {
            ResponseEntity<T> entity = exchange(url, JsonHelper.serialize(request), TrApiContentType.JSON,
                    HttpMethod.POST, responseType);
            return entity.getBody();
        } catch (TrApiException e) {
            throw e;
        } catch (Exception e) {
            throw new TrApiException(e);
        }
    }

    @Override
    public void put(String url, Object request) {
        try {
            exchange(url, JsonHelper.serialize(request), TrApiContentType.JSON, HttpMethod.PUT);
        } catch (TrApiException e) {
            throw e;
        } catch (Exception e) {
            throw new TrApiException(e);
        }
    }

    @Override
    public ResponseEntity<String> exchange(String url, String requestBody, TrApiContentType contentType,
            HttpMethod httpMethod) {
        return exchange(url, requestBody, contentType, httpMethod, String.class);
    }

    @Override
    public <T> ResponseEntity<T> exchange(String url, String requestBody, TrApiContentType contentType,
            HttpMethod httpMethod, Class<T> responseType) {
        long startTime = System.currentTimeMillis();
        HttpEntity<String> entity = null;
        HttpHeaders httpHeaders = getHttpHeaders(contentType);
        if (requestBody == null) {
            entity = new HttpEntity<String>(httpHeaders);
        } else {
            entity = new HttpEntity<String>(requestBody, httpHeaders);
        }
        try {
            if (_logger.isDebugEnabled()) {
                _logger.debug("TrClient before call TR URL: {}", _testRegistrationApplicationUrl + url);
            }
            ResponseEntity<T> response = _trRestApiClient.exchange(_testRegistrationApplicationUrl + url.trim(),
                    httpMethod, entity, responseType);
            if (_logger.isDebugEnabled()) {
                _logger.debug("TrClient TR URL: {}; Execution Time: {} ms; Response: {}",
                        _testRegistrationApplicationUrl + url.trim(), (System.currentTimeMillis() - startTime),
                        response.getBody());
            }
            if (response.getStatusCode() == HttpStatus.OK) {
                return response;
            } else {
                throw new TrApiException(
                        "TrClient.exchange Error: URL " + url + "; StatusCode: " + response.getStatusCode());
            }
        } catch (TrApiException e) {
            _logger.warn("Exception calling tr rest api - Error Message : {}; Wait Time : {} seconds",
                    e.getMessage(), ((System.currentTimeMillis() - startTime) / 1000));
            if (_isLocal && TrApiErrorCode.LOCAL_OK.getCode().equals(e.getErrorCode())) {
                e.setErrorExempted(true);
            }
            throw e;
        } catch (Exception e) {
            throw new TrApiException(e);
        }
    }

    private HttpHeaders getHttpHeaders(TrApiContentType contentType) {
        HttpHeaders headers = new HttpHeaders();
        if (contentType.equals(TrApiContentType.XML)) {
            headers.setContentType(MediaType.APPLICATION_XML);
        } else if (contentType.equals(TrApiContentType.JSON)) {
            headers.setContentType(MediaType.APPLICATION_JSON);
        } else {
            throw new IllegalArgumentException("Supported content type is xml or json");
        }
        return headers;
    }

    private void setLocal() {
        URI uri;
        try {
            uri = new URI(_testRegistrationApplicationUrl);
            _isLocal = "localhost".equals(uri.getHost());
        } catch (URISyntaxException e) {
            _logger.warn(e.getMessage());
            _isLocal = false;
        }
    }

}