Example usage for org.apache.http.message BasicStatusLine BasicStatusLine

List of usage examples for org.apache.http.message BasicStatusLine BasicStatusLine

Introduction

In this page you can find the example usage for org.apache.http.message BasicStatusLine BasicStatusLine.

Prototype

public BasicStatusLine(ProtocolVersion protocolVersion, int i, String str) 

Source Link

Usage

From source file:library.util.OkHttpStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {

    OkHttpClient client = mClient.clone();
    int timeoutMs = request.getTimeoutMs();
    client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS);

    Builder okHttpRequestBuilder = new Builder();
    okHttpRequestBuilder.url(request.getUrl());

    Map<String, String> headers = request.getHeaders();
    for (final String name : headers.keySet()) {
        okHttpRequestBuilder.addHeader(name, headers.get(name));
    }//from w  ww. j a  v  a2  s .  com
    for (final String name : additionalHeaders.keySet()) {
        okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name));
    }

    setConnectionParametersForRequest(okHttpRequestBuilder, request);

    com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build();
    Call okHttpCall = client.newCall(okHttpRequest);
    Response okHttpResponse = okHttpCall.execute();

    StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()),
            okHttpResponse.code(), okHttpResponse.message());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromOkHttpResponse(okHttpResponse));

    Headers responseHeaders = okHttpResponse.headers();
    for (int i = 0, len = responseHeaders.size(); i < len; i++) {
        final String name = responseHeaders.name(i), value = responseHeaders.value(i);
        if (name != null) {
            response.addHeader(new BasicHeader(name, value));
        }
    }

    return response;
}

From source file:com.snda.mymarket.providers.downloads.HurlStack.java

@Override
public HttpResponse performRequest(HttpUriRequest request) throws IOException {
    String url = request.getURI().toString();

    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }/*ww w  .j a  v  a  2 s .c o m*/
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    client = openConnection(parsedUrl, request);
    for (Header headerName : request.getAllHeaders()) {
        client.addRequestProperty(headerName.getName(), headerName.getValue());
    }
    client.setRequestMethod("GET");
    // Initialize HttpResponse with data from the HttpURLConnection.
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = client.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could not be retrieved.
        // Signal to the caller that something was wrong with the connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion, client.getResponseCode(),
            client.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(client));
    for (Entry<String, List<String>> header : client.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            response.addHeader(h);
        }
    }
    return response;
}

From source file:org.apache.camel.component.hipchat.HipchatComponentConsumerTest.java

@Test
public void sendInOnly() throws Exception {
    result.expectedMessageCount(1);/*from   w  ww.  j  av  a  2s . c om*/
    String expectedResponse = "{\n" + "  \"items\" : [\n" + "    {\n"
            + "      \"date\" : \"2015-01-19T22:07:11.030740+00:00\",\n" + "      \"from\" : {\n"
            + "        \"id\" : 1647095,\n" + "        \"links\" : {\n"
            + "          \"self\" : \"https://api.hipchat.com/v2/user/1647095\"\n" + "        },\n"
            + "        \"mention_name\" : \"notifier\",\n" + "        \"name\" : \"Message Notifier\"\n"
            + "      },\n" + "      \"id\" : \"6567c6f7-7c1b-43cf-bed0-792b1d092919\",\n"
            + "      \"mentions\" : [ ],\n" + "      \"message\" : \"Unit test Alert\",\n"
            + "      \"type\" : \"message\"\n" + "    }\n" + "  ],\n" + "  \"links\" : {\n"
            + "    \"self\" : \"https://api.hipchat.com/v2/user/%40ShreyasPurohit/history/latest\"\n" + "  },\n"
            + "  \"maxResults\" : 1,\n" + "  \"startIndex\" : 0\n" + "}";
    HttpEntity mockHttpEntity = mock(HttpEntity.class);
    when(mockHttpEntity.getContent())
            .thenReturn(new ByteArrayInputStream(expectedResponse.getBytes(StandardCharsets.UTF_8)));
    when(closeableHttpResponse.getEntity()).thenReturn(mockHttpEntity);
    when(closeableHttpResponse.getStatusLine())
            .thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, ""));

    assertMockEndpointsSatisfied();

    assertCommonResultExchange(result.getExchanges().get(0));
}

From source file:com.nexmo.client.voice.endpoints.AbstractMethodTest.java

@Before
public void setUp() throws Exception {
    mockWrapper = mock(HttpWrapper.class);
    mockAuthMethods = mock(AuthCollection.class);
    mockAuthMethod = mock(AuthMethod.class);
    mockHttpClient = mock(HttpClient.class);
    when(mockAuthMethods.getAcceptableAuthMethod(any(Set.class))).thenReturn(mockAuthMethod);

    when(mockWrapper.getHttpClient()).thenReturn(mockHttpClient);
    when(mockHttpClient.execute(any(HttpUriRequest.class))).thenReturn(
            new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("1.1", 1, 1), 200, "OK")));
    when(mockWrapper.getAuthCollection()).thenReturn(mockAuthMethods);
}

From source file:org.elasticsearch.client.FailureTrackingResponseListenerTests.java

private static Response mockResponse() {
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    RequestLine requestLine = new BasicRequestLine("GET", "/", protocolVersion);
    StatusLine statusLine = new BasicStatusLine(protocolVersion, 200, "OK");
    HttpResponse httpResponse = new BasicHttpResponse(statusLine);
    return new Response(requestLine, new HttpHost("localhost", 9200), httpResponse);
}

From source file:nl.waisda.services.EuropeanaImportServiceTest.java

private HttpResponse mockDetailHttpResponse(String videoUrl, String webresourceVideoUrl)
        throws UnsupportedEncodingException {
    BasicHttpResponse response = new BasicHttpResponse(new BasicStatusLine(new HttpVersion(100, 1), 200, null));
    response.setEntity(new StringEntity(
            "{\"apikey\":\"XxxsEZoWj\",\"action\":\"record.json\",\"success\":true,\"statsDuration\":50,\"requestNumber\":3752,"
                    + "\"object\":{\"type\":\"VIDEO\",\"year\":[\"1919\"],"
                    + "\"title\":[\"Opening Staten Generaal 20-9-1921\"],"
                    + "\"about\":\"/2021601/6D84A6DB3976320008D516D00F5399132A5E8EE9\","
                    + "\"proxies\":[{\"about\":\"/proxy/provider/2021601/6D84A6DB3976320008D516D00F5399132A5E8EE9\","
                    + "\"dcCreator\":{\"def\":[\"Nederlands Instituut voor Beeld en Geluid (beheerder)\",\"Netherlands Institute for Sound and Vison (curator)\"]},"
                    + "\"dcDate\":{\"def\":[\"1919-01-01\"]},\"dcDescription\":{\"def\":[]},\"dcLanguage\":{\"def\":[\"nl\"]},"
                    + "\"dcPublisher\":{\"def\":[\"Nederlands Instituut voor Beeld en Geluid\",\"http://www.openbeelden.nl/users/beeldengeluid\"]},"
                    + "\"dcSource\":{\"def\":[\"ONTHULLINGSTA-HRE00007FDA\"]},"
                    + "\"dcSubject\":{\"def\":[\"standbeelden\",\"volkscultuur\",\"steden\",\"zwemmen\",\"trams\",\"onthullingen\",\"wedstrijden\",\"optochten\",\"menigte\",\"hotels\",\"musici\",\"roeiboten\",\"kransleggingen\"]},"
                    + "\"dcTitle\":{\"def\":[\"Opening Staten Generaal 20-9-1921\"]},"
                    + "\"dcType\":{\"def\":[\"Moving Image\"]},"
                    + "\"dctermsAlternative\":{\"def\":[\"\",\"\"]},"
                    + "\"dctermsExtent\":{\"def\":[\"PT10M57S\"]},"
                    + "\"proxyIn\":[\"/aggregation/provider/2021601/6D84A6DB3976320008D516D00F5399132A5E8EE9\"],"
                    + "\"proxyFor\":\"/item/2021601/6D84A6DB3976320008D516D00F5399132A5E8EE9\","
                    + "\"edmType\":\"VIDEO\",\"europeanaProxy\":false},"
                    + "{\"about\":\"/proxy/europeana/2021601/6D84A6DB3976320008D516D00F5399132A5E8EE9\","
                    + "\"edmHasMet\":{\"def\":[\"http://semium.org/time/19xx_1_third\",\"http://semium.org/time/1919\"]},"
                    + "\"proxyIn\":[\"/aggregation/europeana/2021601/6D84A6DB3976320008D516D00F5399132A5E8EE9\"],"
                    + "\"proxyFor\":\"/item/2021601/6D84A6DB3976320008D516D00F5399132A5E8EE9\","
                    + "\"year\":{\"def\":[\"1919\"]}," + "\"europeanaProxy\":true}],"
                    + "\"aggregations\":[{\"about\":\"/aggregation/provider/2021601/6D84A6DB3976320008D516D00F5399132A5E8EE9\","
                    + "\"edmDataProvider\":{\"def\":[\"Open Beelden\"]},"
                    + (videoUrl != null ? "\"edmIsShownBy\":\"" + videoUrl + "\"," : "")
                    + "\"edmIsShownAt\":\"http://preview.europeana.eu/api/728/redirect.json?shownAt=http%3A%2F%2Fwww.openbeelden.nl%2Fmedia%2F3969%3Fbt%3Deuropeanaapi&provider=Nationale+Aggregator&id=http://www.europeana.eu/resolve/record/2021601/6D84A6DB3976320008D516D00F5399132A5E8EE9&profile=full\","
                    + "\"edmObject\":\"http://www.openbeelden.nl/images/66690/Vlissingen_%285_28%29.png\","
                    + "\"edmProvider\":{\"def\":[\"Nationale Aggregator\"]},"
                    + "\"edmRights\":{\"def\":[\"http://creativecommons.org/licenses/by-sa/3.0/nl/\"]},"
                    + "\"webResources\":[{\"about\":\"http://www.openbeelden.nl/media/3969\"},"
                    + (webresourceVideoUrl != null ? "{\"about\":\"" + webresourceVideoUrl + "\"}," : "")
                    + "{\"about\":\"http://www.openbeelden.nl/images/66690/Vlissingen_%285_28%29.png\"}]}],"
                    + "\"timespans\":[{\"about\":\"http://semium.org/time/19xx_1_third\","
                    + "\"prefLabel\":{\"en\":[\"early 20th century\"],\"ru\":[\"\"]}},"
                    + "{\"about\":\"http://semium.org/time/1919\"," + "\"prefLabel\":{\"def\":[\"1919\"]},"
                    + "\"isPartOf\":{\"en\":[\"http://semium.org/time/19xx_1_third\"]}}],"
                    + "\"europeanaCompleteness\":10,"
                    + "\"providedCHOs\":[{\"about\":\"/item/2021601/6D84A6DB3976320008D516D00F5399132A5E8EE9\"}],\"europeanaAggregation\":{\"about\":\"/aggregation/europeana/2021601/6D84A6DB3976320008D516D00F5399132A5E8EE9\","
                    + "\"edmLandingPage\":\"http://www.europeana.eu/portal/record/2021601/6D84A6DB3976320008D516D00F5399132A5E8EE9\","
                    + "\"edmCountry\":{\"def\":[\"netherlands\"]}," + "\"edmLanguage\":{\"def\":[\"nl\"]}},"
                    + "\"europeanaCollectionName\":[\"2021601_Ag_NL_DNA_Open_Beelden\"]}}"));

    return response;
}

From source file:mobi.jenkinsci.server.core.services.HttpClientURLDownloaderTest.java

@Test
public void httpGetRemoteUrlReturnsRawBinaryNode() throws IOException {
    when(mockHttpClient.execute(any(HttpUriRequest.class))).thenReturn(new BasicHttpResponse(
            new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_OK, "OK")));

    final RawBinaryNode responseNode = httpClientDownloader.download(mockPluginRequest,
            A_REMOTE_RESOURCE_URL.toString(), mockAccount, mockPluginConfig);

    verify(mockHttpClient).execute(httpUriRequestCaptor.capture());
    final HttpRequestBase requestValue = httpUriRequestCaptor.getValue();
    assertThat(requestValue, hasProperty("URI", equalTo(A_REMOTE_RESOURCE_URL)));
    assertThat(responseNode, notNullValue(RawBinaryNode.class));
}

From source file:org.elasticsearch.client.HeapBufferedAsyncResponseConsumerTests.java

private static void bufferLimitTest(HeapBufferedAsyncResponseConsumer consumer, int bufferLimit)
        throws Exception {
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    StatusLine statusLine = new BasicStatusLine(protocolVersion, 200, "OK");
    consumer.onResponseReceived(new BasicHttpResponse(statusLine));

    final AtomicReference<Long> contentLength = new AtomicReference<>();
    HttpEntity entity = new StringEntity("", ContentType.APPLICATION_JSON) {
        @Override//from w ww.  j a va  2 s.  c  om
        public long getContentLength() {
            return contentLength.get();
        }
    };
    contentLength.set(randomLong(bufferLimit));
    consumer.onEntityEnclosed(entity, ContentType.APPLICATION_JSON);

    contentLength.set(randomLongBetween(bufferLimit + 1, MAX_TEST_BUFFER_SIZE));
    try {
        consumer.onEntityEnclosed(entity, ContentType.APPLICATION_JSON);
    } catch (ContentTooLongException e) {
        assertEquals("entity content is too long [" + entity.getContentLength()
                + "] for the configured buffer limit [" + bufferLimit + "]", e.getMessage());
    }
}

From source file:com.emc.vipr.ribbon.test.ViPRDataServicesServerListTest.java

@Test
public void testXmlParse() throws Exception {
    String rawXml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"
            + "        <ListDataNode xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">\n"
            + "            <DataNodes> 10.247.102.239</DataNodes>\n"
            + "            <DataNodes>10.247.102.240</DataNodes>\n"
            + "            <DataNodes>10.247.102.241 </DataNodes>\n"
            + "            <VersionInfo>vipr-2.0.0.0.r2b3e482</VersionInfo>\n" + "        </ListDataNode>";

    HttpResponse testResponse = new BasicHttpResponse(
            new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK"));
    testResponse.setEntity(new StringEntity(rawXml, ContentType.APPLICATION_XML));

    ParserTester tester = new ParserTester();
    List<String> hosts = tester.testParse(testResponse);

    Assert.assertEquals("wrong number of hosts", 3, hosts.size());
    Assert.assertEquals("wrong 1st host", "10.247.102.239", hosts.get(0));
    Assert.assertEquals("wrong 2nd host", "10.247.102.240", hosts.get(1));
    Assert.assertEquals("wrong 3rd host", "10.247.102.241", hosts.get(2));
}

From source file:org.myframe.http.HttpConnectStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());/*www .ja va 2  s . c om*/
    map.putAll(additionalHeaders);

    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);
    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    setConnectionParametersForRequest(connection, request);

    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(),
            connection.getResponseMessage());

    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            String value = "";
            for (String v : header.getValue()) {
                value += (v + "; ");
            }
            Header h = new BasicHeader(header.getKey(), value);
            response.addHeader(h);
        }
    }
    return response;
}