Search in sources :

Example 1 with HttpHeaders

use of org.apache.http.HttpHeaders in project irontest by zheng-wang.

the class IronTestUtils method invokeHTTPAPI.

/**
 * This method trusts all SSL certificates exposed by the API.
 *
 * @param url
 * @param username
 * @param password
 * @param httpMethod
 * @param httpHeaders
 * @param httpBody
 * @return
 * @throws Exception
 */
public static HTTPAPIResponse invokeHTTPAPI(String url, String username, String password, HTTPMethod httpMethod, List<HTTPHeader> httpHeaders, String httpBody) throws Exception {
    UrlValidator urlValidator = new UrlValidator(new String[] { "http", "https" }, UrlValidator.ALLOW_LOCAL_URLS);
    if (!urlValidator.isValid(url)) {
        throw new RuntimeException("Invalid URL");
    }
    // to allow special characters like whitespace in query parameters
    String safeUrl = UrlEscapers.urlFragmentEscaper().escape(url);
    // create HTTP request object and set body if applicable
    HttpUriRequest httpRequest;
    switch(httpMethod) {
        case GET:
            httpRequest = new HttpGet(safeUrl);
            break;
        case POST:
            HttpPost httpPost = new HttpPost(safeUrl);
            // StringEntity doesn't accept null string (exception is thrown)
            httpPost.setEntity(httpBody == null ? null : new StringEntity(httpBody, "UTF-8"));
            httpRequest = httpPost;
            break;
        case PUT:
            HttpPut httpPut = new HttpPut(safeUrl);
            // StringEntity doesn't accept null string (exception is thrown)
            httpPut.setEntity(httpBody == null ? null : new StringEntity(httpBody, "UTF-8"));
            httpRequest = httpPut;
            break;
        case DELETE:
            httpRequest = new HttpDelete(safeUrl);
            break;
        default:
            throw new IllegalArgumentException("Unrecognized HTTP method " + httpMethod);
    }
    // set request HTTP headers
    for (HTTPHeader httpHeader : httpHeaders) {
        httpRequest.setHeader(httpHeader.getName(), httpHeader.getValue());
    }
    // set HTTP basic auth
    if (!"".equals(StringUtils.trimToEmpty(username))) {
        String auth = username + ":" + password;
        String encodedAuth = Base64.encodeBase64String(auth.getBytes());
        String authHeader = "Basic " + encodedAuth;
        httpRequest.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
    }
    final HTTPAPIResponse apiResponse = new HTTPAPIResponse();
    final AtomicReference<Date> responseReceivedTime = new AtomicReference<>();
    ResponseHandler<Void> responseHandler = httpResponse -> {
        responseReceivedTime.set(new Date());
        apiResponse.setStatusCode(httpResponse.getStatusLine().getStatusCode());
        apiResponse.getHttpHeaders().add(new HTTPHeader("*Status-Line*", httpResponse.getStatusLine().toString()));
        Header[] headers = httpResponse.getAllHeaders();
        for (Header header : headers) {
            apiResponse.getHttpHeaders().add(new HTTPHeader(header.getName(), header.getValue()));
        }
        HttpEntity entity = httpResponse.getEntity();
        apiResponse.setHttpBody(entity != null ? EntityUtils.toString(entity) : null);
        return null;
    };
    // build HTTP Client instance, trusting all SSL certificates, using system HTTP proxy if needed and exists
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial((TrustStrategy) (chain, authType) -> true).build();
    HostnameVerifier allowAllHosts = new NoopHostnameVerifier();
    SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext, allowAllHosts);
    HttpClientBuilder httpClientBuilder = HttpClients.custom().setSSLSocketFactory(connectionFactory);
    InetAddress urlHost = InetAddress.getByName(new URL(url).getHost());
    if (!(urlHost.isLoopbackAddress() || urlHost.isSiteLocalAddress())) {
        // only use system proxy for external address
        Proxy systemHTTPProxy = getSystemHTTPProxy();
        if (systemHTTPProxy != null) {
            InetSocketAddress addr = (InetSocketAddress) systemHTTPProxy.address();
            httpClientBuilder.setProxy(new HttpHost(addr.getHostName(), addr.getPort()));
        }
    }
    HttpClient httpClient = httpClientBuilder.build();
    // invoke the API
    Date invocationStartTime = new Date();
    try {
        httpClient.execute(httpRequest, responseHandler);
    } catch (ClientProtocolException e) {
        throw new RuntimeException(e.getCause().getMessage(), e);
    }
    long responseTime = responseReceivedTime.get().getTime() - invocationStartTime.getTime();
    apiResponse.setResponseTime(responseTime);
    return apiResponse;
}
Also used : SSLContext(javax.net.ssl.SSLContext) Metadata.metadata(com.github.tomakehurst.wiremock.common.Metadata.metadata) XPathExpressionException(javax.xml.xpath.XPathExpressionException) DefaultArtifactVersion(org.apache.maven.artifact.versioning.DefaultArtifactVersion) io.irontest.models.mixin(io.irontest.models.mixin) StringUtils(org.apache.commons.lang3.StringUtils) Header(org.apache.http.Header) Base64(org.apache.commons.codec.binary.Base64) EntityUtils(org.apache.http.util.EntityUtils) WireMockServer(com.github.tomakehurst.wiremock.WireMockServer) io.irontest.models(io.irontest.models) java.net(java.net) Document(org.w3c.dom.Document) ResultSet(java.sql.ResultSet) org.apache.http.client.methods(org.apache.http.client.methods) HTTPAPIResponse(io.irontest.core.teststep.HTTPAPIResponse) NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) HostnameVerifier(javax.net.ssl.HostnameVerifier) WIREMOCK_STUB_METADATA_ATTR_NAME_IRON_TEST_ID(io.irontest.IronTestConstants.WIREMOCK_STUB_METADATA_ATTR_NAME_IRON_TEST_ID) PlainTextStubNotMatchedRenderer(com.github.tomakehurst.wiremock.verification.notmatched.PlainTextStubNotMatchedRenderer) HttpHeaders(org.apache.http.HttpHeaders) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) LoggedRequest(com.github.tomakehurst.wiremock.verification.LoggedRequest) UrlEscapers(com.google.common.net.UrlEscapers) HttpEntity(org.apache.http.HttpEntity) StringEntity(org.apache.http.entity.StringEntity) WIREMOCK_STUB_METADATA_ATTR_NAME_IRON_TEST_NUMBER(io.irontest.IronTestConstants.WIREMOCK_STUB_METADATA_ATTR_NAME_IRON_TEST_NUMBER) UrlValidator(org.apache.commons.validator.routines.UrlValidator) HTTPHeader(io.irontest.models.teststep.HTTPHeader) LoggedResponse(com.github.tomakehurst.wiremock.http.LoggedResponse) MQRFH2Folder(io.irontest.models.teststep.MQRFH2Folder) HttpClients(org.apache.http.impl.client.HttpClients) ResultSetMetaData(java.sql.ResultSetMetaData) ClientProtocolException(org.apache.http.client.ClientProtocolException) java.util(java.util) SQLStatementType(io.irontest.db.SQLStatementType) TransformerException(javax.xml.transform.TransformerException) ANTLRStringStream(org.antlr.runtime.ANTLRStringStream) AtomicReference(java.util.concurrent.atomic.AtomicReference) Encoding(com.github.tomakehurst.wiremock.common.Encoding) SQLException(java.sql.SQLException) HttpClient(org.apache.http.client.HttpClient) ResponseDefinition(com.github.tomakehurst.wiremock.http.ResponseDefinition) StubMapping(com.github.tomakehurst.wiremock.stubbing.StubMapping) Jdbi(org.jdbi.v3.core.Jdbi) JsonParser(com.fasterxml.jackson.core.JsonParser) TrustStrategy(org.apache.http.conn.ssl.TrustStrategy) ServeEvent(com.github.tomakehurst.wiremock.stubbing.ServeEvent) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) SqlScriptParser(org.jdbi.v3.core.internal.SqlScriptParser) IOException(java.io.IOException) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) com.github.tomakehurst.wiremock.matching(com.github.tomakehurst.wiremock.matching) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) ResponseHandler(org.apache.http.client.ResponseHandler) HttpHost(org.apache.http.HttpHost) TrustStrategy(org.apache.http.conn.ssl.TrustStrategy) HTTPAPIResponse(io.irontest.core.teststep.HTTPAPIResponse) HttpEntity(org.apache.http.HttpEntity) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ClientProtocolException(org.apache.http.client.ClientProtocolException) StringEntity(org.apache.http.entity.StringEntity) HttpHost(org.apache.http.HttpHost) UrlValidator(org.apache.commons.validator.routines.UrlValidator) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) AtomicReference(java.util.concurrent.atomic.AtomicReference) SSLContext(javax.net.ssl.SSLContext) NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) HostnameVerifier(javax.net.ssl.HostnameVerifier) Header(org.apache.http.Header) HTTPHeader(io.irontest.models.teststep.HTTPHeader) HttpClient(org.apache.http.client.HttpClient) HTTPHeader(io.irontest.models.teststep.HTTPHeader)

Aggregations

JsonParser (com.fasterxml.jackson.core.JsonParser)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 WireMockServer (com.github.tomakehurst.wiremock.WireMockServer)1 Encoding (com.github.tomakehurst.wiremock.common.Encoding)1 Metadata.metadata (com.github.tomakehurst.wiremock.common.Metadata.metadata)1 LoggedResponse (com.github.tomakehurst.wiremock.http.LoggedResponse)1 ResponseDefinition (com.github.tomakehurst.wiremock.http.ResponseDefinition)1 com.github.tomakehurst.wiremock.matching (com.github.tomakehurst.wiremock.matching)1 ServeEvent (com.github.tomakehurst.wiremock.stubbing.ServeEvent)1 StubMapping (com.github.tomakehurst.wiremock.stubbing.StubMapping)1 LoggedRequest (com.github.tomakehurst.wiremock.verification.LoggedRequest)1 PlainTextStubNotMatchedRenderer (com.github.tomakehurst.wiremock.verification.notmatched.PlainTextStubNotMatchedRenderer)1 UrlEscapers (com.google.common.net.UrlEscapers)1 WIREMOCK_STUB_METADATA_ATTR_NAME_IRON_TEST_ID (io.irontest.IronTestConstants.WIREMOCK_STUB_METADATA_ATTR_NAME_IRON_TEST_ID)1 WIREMOCK_STUB_METADATA_ATTR_NAME_IRON_TEST_NUMBER (io.irontest.IronTestConstants.WIREMOCK_STUB_METADATA_ATTR_NAME_IRON_TEST_NUMBER)1 HTTPAPIResponse (io.irontest.core.teststep.HTTPAPIResponse)1 SQLStatementType (io.irontest.db.SQLStatementType)1 io.irontest.models (io.irontest.models)1 io.irontest.models.mixin (io.irontest.models.mixin)1 HTTPHeader (io.irontest.models.teststep.HTTPHeader)1