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:co.cask.cdap.client.rest.RestClientTest.java

@Test
public void testForbiddenResponseCodeAnalysis() {

    StatusLine statusLine = new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_FORBIDDEN,
            "Forbidden");
    when(response.getStatusLine()).thenReturn(statusLine);
    TestUtils.verifyResponse(HttpStatus.SC_FORBIDDEN, response);
    verify(response).getStatusLine();/*from w w w . j av a  2s.  c  om*/
}

From source file:org.piraso.client.net.HttpPirasoEntryReaderTest.java

@Test
public void testStartOnSuccess() throws Exception {
    String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
            + "<piraso id=\"1\" watched-address=\"127.0.0.1\">\n"
            + "<entry class-name=\"org.piraso.api.entry.MessageEntry\" date=\"1319349832439\" id=\"1\">{\"message\":\"message\",\"elapseTime\":null}</entry>\n"
            + "</piraso>";

    Preferences preferences = new Preferences();

    StatusLine line = new BasicStatusLine(new ProtocolVersion("http", 1, 0), HttpStatus.SC_OK, "");
    doReturn(line).when(response).getStatusLine();

    doReturn(new ByteArrayInputStream(xml.getBytes())).when(entity).getContent();
    doReturn(XML_CONTENT_TYPE).when(contentTypeHeader).getValue();

    reader.getStartHandler().setPreferences(preferences);
    reader.getStartHandler().setWatchedAddr("127.0.0.1");

    final List<Entry> entries = new ArrayList<Entry>();

    reader.getStartHandler().addListener(new EntryReadAdapter() {
        @Override//from   w w  w  .j av a2s  . c  o  m
        public void readEntry(EntryReadEvent evt) {
            entries.add(evt.getEntry());
        }
    });

    reader.start();

    assertNotNull(reader.getStartHandler().getWatchedAddr());
    assertNotNull(reader.getStartHandler().getId());
    assertTrue(reader.isComplete());

    assertEquals(1, CollectionUtils.size(entries));
    assertTrue(UrlEncodedFormEntity.class.isInstance(capturedPost.getEntity()));
    verify(client).execute(Matchers.<HttpHost>any(), Matchers.<HttpRequest>any(), Matchers.<HttpContext>any());

    reader.stop();

    // still once since already complete
    verify(client).execute(Matchers.<HttpHost>any(), Matchers.<HttpRequest>any(), Matchers.<HttpContext>any());
}

From source file:org.kymjs.kjframe.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>();
    //just marker by chenlin
    map.putAll(request.getHeaders());/* w w  w .  ja v a  2s  .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);
    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;
}

From source file:com.telefonica.iot.cygnus.backends.http.HttpBackendTest.java

/**
 * [HttpBackend.createJsonResponse] -------- A JsonResponse object is
 * created if the response content-type header is 'application/json' and the
 * response contains a location header./*from  w  ww  .  ja  va2 s .  c  om*/
 */
@Test
public void testCreateJsonResponseEverythingOK() {
    System.out.println(getTestTraceHead("[HttpBackend.createJsonResponse]")
            + "-------- A JsonResponse object is created if the response content-type header is "
            + "'application/json' and the response contains a location header");
    HttpResponseFactory factory = new DefaultHttpResponseFactory();
    HttpResponse response = factory
            .newHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, null), null);
    String responseStr = "{\"somefield1\":\"somevalue1\",\"somefield2\":\"somevalue2\","
            + "\"somefield3\":\"somevalue3\"}";

    try {
        response.setEntity(new StringEntity(responseStr));
    } catch (UnsupportedEncodingException e) {
        System.out.println(getTestTraceHead("[HttpBackend.createJsonResponse]")
                + "- FAIL - There was some problem when creating the HttpResponse object");
        throw new AssertionError(e.getMessage());
    } // try catch

    response.addHeader("Content-Type", "application/json");
    response.addHeader("Location", "http://someurl.org");
    HttpBackend httpBackend = new HttpBackendImpl(host, port, false, false, null, null, null, null, maxConns,
            maxConnsPerRoute);

    try {
        JsonResponse jsonRes = httpBackend.createJsonResponse(response);

        try {
            assertTrue(jsonRes.getJsonObject() != null);
            System.out.println(getTestTraceHead("[HttpBackend.createJsonResponse]")
                    + "-  OK  - The JsonResponse object has a Json apyload");
        } catch (AssertionError e) {
            System.out.println(getTestTraceHead("[HttpBackend.createJsonResponse]")
                    + "- FAIL - The JsonResponse object has not a Json payload");
            throw e;
        } // try catch

        try {
            assertTrue(jsonRes.getLocationHeader() != null);
            System.out.println(getTestTraceHead("[HttpBackend.createJsonResponse]")
                    + "-  OK  - The JsonResponse object has a Location header");
        } catch (AssertionError e) {
            System.out.println(getTestTraceHead("[HttpBackend.createJsonResponse]")
                    + "- FAIL - The JsonResponse object has not a Location header");
            throw e;
        } // try catch
    } catch (Exception e) {
        System.out.println(getTestTraceHead("[HttpBackend.createJsonResponse]")
                + "- FAIL - There was some problem when creating the JsonResponse object");
        throw new AssertionError(e.getMessage());
    } // try catch
}

From source file:org.sentilo.platform.server.test.parser.AdminParserTest.java

@Test
public void parseStatsWriteResponse() throws Exception {
    final Events events = new Events(new Long(10), new Long(3), new Long(4), new Long(3));
    final Performance performance = new Performance(new Float(54.84), new Float(14.65), new Float(784.84));
    final Statistics stats = new Statistics(events, performance);

    final SentiloResponse response = SentiloResponse
            .build(new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_0, 200, "")));
    parser.writeStatsResponse(sentiloRequest, response, stats);

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ((ByteArrayEntity) response.getHttpResponse().getEntity()).writeTo(baos);
    final String expected = "{\"events\":{\"total\":10,\"observations\":4,\"alarms\":3,\"orders\":3},\"performance\":{\"instantAvg\":54.84,\"dailyAvg\":14.65,\"maxAvg\":784.84}}";
    assertEquals(expected, baos.toString());
}

From source file:lh.api.showcase.server.util.HttpQueryUtilsTest.java

@Test(expected = HttpErrorResponseException.class)
public void shouldRetryToRefreshToken()
        throws ClientProtocolException, IOException, HttpErrorResponseException {

    Mockito.when(responseMock.getStatusLine())
            .thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "Unauthorized"));
    Mockito.when(entityMock.getContent()).thenAnswer(new Answer<InputStream>() {
        @Override//from ww w  .j a  va 2s .c  o m
        public InputStream answer(InvocationOnMock invocation) throws Throwable {
            return this.getClass().getResource("/empty_response.txt").openStream();
        }
    });
    Mockito.when(apiAuthMock.updateAccessToken()).thenReturn(true);

    int maxRetried = 3;
    try {
        HttpQueryUtils.executeQuery(uri, apiAuthMock, null, new HttpClientFactoryTestImpl(), maxRetried);

    } finally {
        Mockito.verify(apiAuthMock, Mockito.times(maxRetried)).updateAccessToken();
        Mockito.verify(httpClientMock, Mockito.times(maxRetried + 1)).execute((HttpGet) Mockito.any());
    }
}

From source file:com.joyent.manta.client.multipart.ServerSideMultipartManagerTest.java

public void canInitiateUploadFailure503() throws IOException {
    final StatusLine statusLine = new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_SERVICE_UNAVAILABLE,
            "UNAVAILABLE");

    final String jsonResponse = "{ \"code\":\"InternalError\", \"message\":\"Unit test message.\"}";

    String path = "/test/stor/object";

    boolean caught = false;
    try {/*w  w  w  .j ava  2 s .c o  m*/
        initiateUploadWithAllParams(path, statusLine, jsonResponse);
    } catch (MantaMultipartException e) {
        if (e.getMessage().startsWith("Unable to create multipart upload")) {
            caught = true;
        } else {
            throw e;
        }
    }

    Assert.assertTrue(caught, "Expected exception was not caught");
}

From source file:com.gooddata.http.client.GoodDataHttpClientTest.java

private HttpResponse createResponse(int status, String body, String reasonPhrase) {
    HttpResponse response = new BasicHttpResponse(
            new BasicStatusLine(new ProtocolVersion("https", 1, 1), status, reasonPhrase));
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(new ByteArrayInputStream(body.getBytes()));
    response.setEntity(entity);/*from  w ww . jav  a2s . c o  m*/
    return response;
}

From source file:org.apache.nifi.processors.aws.wag.TestInvokeAmazonGatewayApiMock.java

@Test
public void testGetApiSimple() throws Exception {

    HttpResponse resp = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK"));
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(new ByteArrayInputStream("test payload".getBytes()));
    resp.setEntity(entity);/*from w  ww . j  ava 2s  .com*/
    Mockito.doReturn(resp).when(mockSdkClient).execute(any(HttpUriRequest.class), any(HttpContext.class));

    // execute
    runner.assertValid();
    runner.run(1);

    // check
    Mockito.verify(mockSdkClient, times(1)).execute(argThat(new RequestMatcher<HttpUriRequest>(x -> {
        return x.getMethod().equals("GET") && x.getFirstHeader("x-api-key").getValue().equals("abcd")
                && x.getFirstHeader("Authorization").getValue().startsWith("AWS4")
                && x.getURI().toString().equals("https://foobar.execute-api.us-east-1.amazonaws.com/TEST");
    })), any(HttpContext.class));

    runner.assertTransferCount(InvokeAWSGatewayApi.REL_SUCCESS_REQ, 0);
    runner.assertTransferCount(InvokeAWSGatewayApi.REL_RESPONSE, 1);
    runner.assertTransferCount(InvokeAWSGatewayApi.REL_RETRY, 0);
    runner.assertTransferCount(InvokeAWSGatewayApi.REL_NO_RETRY, 0);
    runner.assertTransferCount(InvokeAWSGatewayApi.REL_FAILURE, 0);

    final List<MockFlowFile> flowFiles = runner.getFlowFilesForRelationship(InvokeAWSGatewayApi.REL_RESPONSE);
    final MockFlowFile ff0 = flowFiles.get(0);

    ff0.assertAttributeEquals(InvokeAWSGatewayApi.STATUS_CODE, "200");
    ff0.assertContentEquals("test payload");
    ff0.assertAttributeExists(InvokeAWSGatewayApi.TRANSACTION_ID);
    ff0.assertAttributeEquals(InvokeAWSGatewayApi.RESOURCE_NAME_ATTR, "/TEST");
}

From source file:com.example.allen.frameworkexample.volley.OkHttp3Stack.java

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

    OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
    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));
    }//from w  w  w. ja v a2 s  . c o 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;
}