org.opentestsystem.shared.test.interactioncontext.FastInteractionResponse.java Source code

Java tutorial

Introduction

Here is the source code for org.opentestsystem.shared.test.interactioncontext.FastInteractionResponse.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.test.interactioncontext;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.opentestsystem.shared.test.api.InteractionResponse;
import org.opentestsystem.shared.test.api.PageDriver;
import org.opentestsystem.shared.test.pagedriver.FastPageDriver;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class FastInteractionResponse implements InteractionResponse<FastInteractionResponse> {

    private final byte[] _bytes;
    private String _body;
    private Document _bodyXML;
    private final Map<String, List<String>> _responseHeaders;
    private String _httpVersion;
    private int _status;
    private String _statusMessage;
    private final URL _requestUrl;
    private final FastInteractionContext _interactionContext;
    private final long _t_timeout;
    private final long _timeout;

    FastInteractionResponse(FastInteractionContext interactionContext, InputStream is, HttpURLConnection connection,
            long timeout, long t_timeout) throws IOException {

        _interactionContext = interactionContext;
        _timeout = timeout;
        _t_timeout = t_timeout;

        // Get the response
        _requestUrl = connection.getURL();
        _bytes = IOUtils.toByteArray(is);
        _responseHeaders = connection.getHeaderFields();
        connection.getContentType();
        String message = connection.getResponseMessage();
        if (message != null) {
            String[] messageParts = StringUtils.split(message, null, 3);
            if (messageParts.length > 0) {
                _httpVersion = messageParts[0];
            }

            if (messageParts.length > 1) {
                try {
                    _status = Integer.valueOf(messageParts[1]);
                } catch (Exception e) {
                    // Do nothing: an invalid HTTP status code!!
                }
            }
            if (messageParts.length > 2) {
                _statusMessage = messageParts[2];
            }
        }
    }

    @Override
    public FastInteractionContext getInteractionContext() {
        return _interactionContext;
    }

    @Override
    public <T extends PageDriver<FastInteractionResponse>> T expecting(Class<T> pageType) throws Throwable {
        return expecting(pageType, true);
    }

    @Override
    public <T extends PageDriver<FastInteractionResponse>> T expecting(Class<T> pageType, boolean ensureLoaded)
            throws Throwable {
        final T pageDriverFactory = pageType.getDeclaredConstructor().newInstance();
        @SuppressWarnings("unchecked")
        final T pageDriver = (T) pageDriverFactory.init(this, ensureLoaded);
        if (ensureLoaded) {
            pageDriver.assertExpectedPage();
        }
        _interactionContext.setCurrentPage((FastPageDriver) pageDriver);
        return pageDriver;
    }

    @Override
    public long getTimeout() {
        return _timeout;
    }

    @Override
    public long getTimeoutTime() {
        return _t_timeout;
    }

    @Override
    public boolean isTimedOut() {
        return System.currentTimeMillis() > _t_timeout;
    }

    public Map<String, List<String>> getResponseHeaders() {
        return _responseHeaders;
    }

    public byte[] getResponseBody() {
        return _bytes;
    }

    public String getResponseBodyAsString() {
        if (_body == null && _bytes != null) {
            try {
                _body = new String(_bytes, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                // Return null--cannot be converted to String
            }
        }
        return _body;
    }

    public Document getResponseAsDOM() throws SAXException, IOException, ParserConfigurationException {
        if (_bodyXML == null && _bytes != null && _bytes.length > 0) {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();

            InputSource is = new InputSource(new ByteArrayInputStream(_bytes));
            _bodyXML = builder.parse(is);
        }
        return _bodyXML;
    }

    public URL getRequestUrl() {
        return _requestUrl;
    }

    public String getHttpVersion() {
        return _httpVersion;
    }

    public int getStatus() {
        return _status;
    }

    public String getStatusMessage() {
        return _statusMessage;
    }

    public String getContentType() {
        List<String> headerList = getResponseHeaders().get("Content-Type");
        if (headerList.size() >= 1) {
            return headerList.get(0);
        }
        return "";
    }

    @SuppressWarnings("unchecked")
    public Map<String, Object> getResponseBodyAsJson() {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.readValue(_bytes, Map.class);
        } catch (JsonParseException e) {
            throw new AssertionError("Content is not valid JSON", e);
        } catch (JsonMappingException e) {
            throw new AssertionError("Content is not valid JSON", e);
        } catch (IOException e) {
            throw new AssertionError("Content is not valid JSON", e);
        }
    }
}