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:at.deder.ybr.test.server.SimpleHttpServerTest.java

@Test
public void testGetPackageTopLevel() throws ProtocolViolationException, IOException {

    // given/*w  ww .  jav  a  2s  .com*/
    ServerManifest dummyManifest = MockUtils.getMockManifest();

    given(mockHttpClient.execute(Matchers.any(HttpGet.class))).willReturn(mockHttpResponse);
    given(mockHttpResponse.getEntity()).willReturn(mockHttpEntity);
    given(mockHttpResponse.getStatusLine())
            .willReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"));
    given(mockHttpEntity.getContent())
            .willReturn(new ByteArrayInputStream(dummyManifest.toString().getBytes("utf-8")));
    SimpleHttpServer instance = new SimpleHttpServer("none");
    instance.setHttpClient(mockHttpClient);

    // when
    RepositoryEntry result = instance.getPackage("com");

    // then
    RepositoryEntry root = dummyManifest.getRepository();
    RepositoryEntry expResult = root.getChildByName("com");
    then(result).isEqualTo(expResult);
}

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

@Test(expected = IOException.class)
public void httpGetRemoteUrlThrowsIOExceptionWhenHttpStatusIsAnotherError() throws IOException {
    when(mockHttpClient.execute(any(HttpUriRequest.class)))
            .thenReturn(new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1),
                    HttpStatus.SC_INTERNAL_SERVER_ERROR, "INTERNAL ERROR")));

    httpClientDownloader.download(mockPluginRequest, A_REMOTE_RESOURCE_URL.toString(), mockAccount,
            mockPluginConfig);//from  ww  w  .  ja  v a  2  s  . c o m
}

From source file:com.circle.android.api.OkHttp3Stack.java

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

    OkHttpClient.Builder clientBuilder = mClient.newBuilder();
    int timeoutMs = request.getTimeoutMs();

    clientBuilder.connectTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    clientBuilder.readTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    clientBuilder.writeTimeout(timeoutMs, TimeUnit.MILLISECONDS);

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

    Map<String, String> headers = request.getHeaders();
    for (final String name : headers.keySet()) {
        okHttpRequestBuilder.addHeader(name, headers.get(name));
    }/* w  w  w  .j  ava  2s.  co m*/
    for (final String name : additionalHeaders.keySet()) {
        okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name));
    }

    setConnectionParametersForRequest(okHttpRequestBuilder, request);

    OkHttpClient client = clientBuilder.build();
    okhttp3.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.launchkey.sdk.transport.v1.ApacheHttpClientTransportPingTest.java

@Test
public void testResponseStatusCodeOf300ThrowsExpectedException() throws Exception {
    expectedException.expect(CommunicationErrorException.class);
    expectedException.expectMessage("Expected Message");

    when(response.getStatusLine())//from  ww  w.ja  v a  2s.  c  o m
            .thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 300, "Expected Message"));
    transport.ping(new PingRequest());
}

From source file:com.volley.air.toolbox.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws AuthFailureError, IOException {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<>();
    map.putAll(request.getHeaders());/*from w  ww.j a  v  a  2 s . c  o  m*/
    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);

    if (!TextUtils.isEmpty(mUserAgent)) {
        connection.setRequestProperty(HEADER_USER_AGENT, mUserAgent);
    }

    for (Entry<String, String> entry : map.entrySet()) {
        connection.addRequestProperty(entry.getKey(), entry.getValue());
    }
    if (request instanceof MultiPartRequest) {
        setConnectionParametersForMultipartRequest(connection, request);
    } else {
        setConnectionParametersForRequest(connection, request);
    }

    // Initialize HttpResponse with data from the HttpURLConnection.
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = connection.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, 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) {
            Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            response.addHeader(h);
        }
    }
    return response;
}

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

/**
 * Mocks the synchronous request execution like if it was executed by Elasticsearch.
 *//* w ww.j  av  a  2 s  . co m*/
private Response mockPerformRequest(Request request) throws IOException {
    assertThat(request.getOptions().getHeaders(), hasSize(1));
    Header httpHeader = request.getOptions().getHeaders().get(0);
    final Response mockResponse = mock(Response.class);
    when(mockResponse.getHost()).thenReturn(new HttpHost("localhost", 9200));

    ProtocolVersion protocol = new ProtocolVersion("HTTP", 1, 1);
    when(mockResponse.getStatusLine()).thenReturn(new BasicStatusLine(protocol, 200, "OK"));

    MainResponse response = new MainResponse(httpHeader.getValue(), Version.CURRENT, ClusterName.DEFAULT, "_na",
            Build.CURRENT);
    BytesRef bytesRef = XContentHelper.toXContent(response, XContentType.JSON, false).toBytesRef();
    when(mockResponse.getEntity())
            .thenReturn(new ByteArrayEntity(bytesRef.bytes, ContentType.APPLICATION_JSON));

    RequestLine requestLine = new BasicRequestLine(HttpGet.METHOD_NAME, ENDPOINT, protocol);
    when(mockResponse.getRequestLine()).thenReturn(requestLine);

    return mockResponse;
}

From source file:com.androidex.volley.toolbox.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws AuthFailureError, IOException {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());/* w w w  . j  a v  a 2 s. com*/
    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);

    if (!TextUtils.isEmpty(mUserAgent)) {
        connection.setRequestProperty(HEADER_USER_AGENT, mUserAgent);
    }

    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    if (request instanceof MultiPartRequest) {
        setConnectionParametersForMultipartRequest(connection, request);
    } else {
        setConnectionParametersForRequest(connection, request);
    }

    // Initialize HttpResponse with data from the HttpURLConnection.
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = connection.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, 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) {
            Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            response.addHeader(h);
        }
    }
    return response;
}

From source file:de.micromata.genome.tpsb.soapui.DelegateToSoapUiTestBuilderHttpClientRequestTransport.java

private HttpResponse execute(SubmitContext submitContext, ExtendedHttpMethod method, HttpContext httpContext,
        Map<String, String> httpRequestParameter) throws Exception {
    boolean passtoremote = false;
    if (passtoremote == true) {
        return HttpClientSupport.execute(method, httpContext);

    }// w  w w . j a v  a  2s.c  o  m
    byte[] reqData = null;
    if (method.getRequestEntity() != null && method.getRequestEntity().getContent() != null) {
        reqData = filterRequestData(IOUtils.toByteArray(method.getRequestEntity().getContent()));
    }
    Header[] soaphaedera = method.getHeaders("SOAPAction");
    String soapAction = "";
    if (soaphaedera != null && soaphaedera.length > 0) {
        soapAction = method.getHeaders("SOAPAction")[0].getValue();
    }
    String uri = method.getURI().toString();
    //    testBuilder.initWithUri(uri);
    testBuilder//
            .createNewPostRequestIntern(submitContext) //
            .initWithUri(uri).setRequestMethod(method.getMethod()).setRequestData(reqData);
    if (StringUtils.isNotBlank(soapAction) == true) {
        testBuilder.addRequestHeader("SOAPAction", soapAction);
    }
    Header[] allHeaders = method.getAllHeaders();
    for (Header h : allHeaders) {
        testBuilder.addRequestHeader(h.getName(), h.getValue());
    }
    httpRequestParameter.forEach((k, v) -> testBuilder.getHttpRequest().addRequestParameter(k, v));
    MockHttpServletResponse httpr = testBuilder.executeServletRequest() //
            .getHttpResponse();

    byte[] respData = filterResponseData(httpr.getOutputBytes());
    //    String outp = httpr.getOutputString();
    BasicStatusLine statusLine = new BasicStatusLine(new ProtocolVersion("http", 1, 1), httpr.getStatus(),
            null);
    BasicHttpResponse httpResponse = new BasicHttpResponse(statusLine);
    httpResponse.setEntity(new ByteArrayEntity(respData));
    httpResponse = filterBasicHttpResponse(httpResponse);
    //        WsdlSinglePartHttpResponse wsdls = new WsdlSinglePartHttpResponse();
    method.setHttpResponse(httpResponse);
    try {
        method.setURI(new URI("http://localhost/dummy"));
    } catch (URISyntaxException ex) {
        throw new RuntimeException(ex);
    }
    return httpResponse;
}

From source file:org.sentilo.common.test.rest.RESTClientImplTest.java

@Test
public void deleteWithBody() throws Exception {
    final String path = "/data";
    final String body = "body";
    final String responseContent = "Lorem ipsum";
    final StatusLine statusLine = new BasicStatusLine(HttpVersion.HTTP_1_0, HttpStatus.SC_OK, "");

    when(httpClient.execute(notNull(HttpPut.class))).thenReturn(httpResponse);
    when(httpResponse.getStatusLine()).thenReturn(statusLine);
    when(httpResponse.getEntity()).thenReturn(new StringEntity(responseContent));

    final String result = restClient.delete(path, body, null);

    verify(httpClient).execute(any(HttpPut.class));
    Assert.assertEquals(responseContent, result);
}

From source file:com.ksc.http.timers.ClientExecutionAndRequestTimerTestUtils.java

private static HttpResponseProxy createHttpResponseProxy(HttpEntity entity) {
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    BasicStatusLine statusLine = new BasicStatusLine(protocolVersion, 200, "mock response");
    BasicHttpResponse response = new BasicHttpResponse(statusLine);
    response.setEntity(entity);//from  w w  w .ja  v  a  2 s  .co m
    return new HttpResponseProxy(response);
}