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:sonata.kernel.vimadaptor.wrapper.openstack.javastackclient.JavaStackCore.java

public synchronized HttpResponse listComputeLimits() throws IOException {
    HttpGet getLimits = null;/*ww  w .  j  a  v a2  s  .co m*/
    HttpResponse response = null;

    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpResponseFactory factory = new DefaultHttpResponseFactory();

    if (isAuthenticated) {
        StringBuilder buildUrl = new StringBuilder();
        buildUrl.append("http://");
        buildUrl.append(endpoint);
        buildUrl.append(":");
        buildUrl.append(Constants.COMPUTE_PORT.toString());
        buildUrl.append(String.format("/%s/%s/limits", Constants.COMPUTE_VERSION.toString(), this.tenant_id));

        getLimits = new HttpGet(buildUrl.toString());
        getLimits.addHeader(Constants.AUTHTOKEN_HEADER.toString(), this.token_id);

        response = httpClient.execute(getLimits);
        int status_code = response.getStatusLine().getStatusCode();
        return (status_code == 200) ? response
                : factory.newHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, status_code,
                        "List Limits Failed with Status: " + status_code), null);
    }
    return response;
}

From source file:sonata.kernel.vimadaptor.wrapper.openstack.javastackclient.JavaStackCore.java

public synchronized HttpResponse listComputeFlavors() throws IOException {
    HttpGet getFlavors = null;//ww  w  . j av  a  2s .co  m
    HttpResponse response = null;

    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpResponseFactory factory = new DefaultHttpResponseFactory();

    if (isAuthenticated) {
        StringBuilder buildUrl = new StringBuilder();
        buildUrl.append("http://");
        buildUrl.append(endpoint);
        buildUrl.append(":");
        buildUrl.append(Constants.COMPUTE_PORT.toString());
        buildUrl.append(
                String.format("/%s/%s/flavors/detail", Constants.COMPUTE_VERSION.toString(), this.tenant_id));

        getFlavors = new HttpGet(buildUrl.toString());
        getFlavors.addHeader(Constants.AUTHTOKEN_HEADER.toString(), this.token_id);

        response = httpClient.execute(getFlavors);
        int status_code = response.getStatusLine().getStatusCode();
        return (status_code == 200) ? response
                : factory.newHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, status_code,
                        "List Flavors  Failed with Status: " + status_code), null);
    }
    return response;
}

From source file:com.socialize.test.integration.services.b.TwitterUtilsTest.java

protected void do_test_post() throws Exception {
    String entityKeyRandom = "foobar" + Math.random();
    Entity entity = Entity.newInstance(entityKeyRandom, "foobar");

    final CountDownLatch latch = new CountDownLatch(1);

    final String token = TestUtils.getDummyTwitterToken(getContext());
    final String secret = TestUtils.getDummyTwitterSecret(getContext());

    // Stub in the TwitterAuthProvider
    TwitterAuthProvider mockTwitterAuthProvider = new TwitterAuthProvider() {
        @Override//from  ww w  . j  a  v  a 2 s.  c o m
        public void authenticate(Context context, TwitterAuthProviderInfo info, AuthProviderListener listener) {
            AuthProviderResponse response = new AuthProviderResponse();
            response.setToken(token);
            response.setSecret(secret);
            listener.onAuthSuccess(response);
        }
    };

    final HttpResponse mockResponse = new BasicHttpResponse(
            new BasicStatusLine(new ProtocolVersion("https", 1, 0), 200, ""));
    final String responseData = "{foo:bar}";

    // Stub in the http provider factory for the tweet
    HttpRequestProvider mockProvider = new HttpRequestProvider() {

        @Override
        public void post(HttpPost request, HttpRequestListener listener) {
            listener.onSuccess(mockResponse, responseData);
        }

        @Override
        public void get(HttpGet request, HttpRequestListener listener) {
            listener.onSuccess(mockResponse, responseData);
        }
    };

    SocializeIOC.registerStub("twitterProvider", mockTwitterAuthProvider);
    SocializeIOC.registerStub("httpRequestProvider", mockProvider);

    TwitterUtils.tweetEntity(TestUtils.getActivity(this), entity, "AndroidSDK Test",
            new SocialNetworkShareListener() {

                @Override
                public void onNetworkError(Activity context, SocialNetwork network, Exception error) {
                    error.printStackTrace();
                    latch.countDown();
                }

                @Override
                public boolean onBeforePost(Activity parent, SocialNetwork socialNetwork, PostData postData) {
                    addResult(3, "onBeforePost");

                    return false;
                }

                @Override
                public void onAfterPost(Activity parent, SocialNetwork socialNetwork, JSONObject response) {
                    addResult(1, "onAfterPost");
                    latch.countDown();
                }

                @Override
                public void onCancel() {
                }
            });

    assertTrue(latch.await(20, TimeUnit.SECONDS));

    final CountDownLatch latch2 = new CountDownLatch(1);

    // Make sure we have a share object
    ShareUtils.getSharesByUser(getContext(), UserUtils.getCurrentUser(getContext()), 0, 100,
            new ShareListListener() {
                @Override
                public void onList(ListResult<Share> entities) {
                    addResult(2, entities);
                    latch2.countDown();
                }

                @Override
                public void onError(SocializeException error) {
                    error.printStackTrace();
                    latch2.countDown();
                }
            });

    assertTrue(latch2.await(20, TimeUnit.SECONDS));

    SocializeIOC.unregisterStub("twitterProvider");

    String onAfterPost = getResult(1);
    ListResult<Share> shares = getResult(2);
    String onBeforePost = getResult(3);

    assertNotNull(onAfterPost);
    assertNotNull(shares);
    assertNotNull(onBeforePost);

    // Find the share
    assertTrue(shares.size() > 0);

    List<Share> items = shares.getItems();
    Share match = null;
    for (Share share : items) {
        if (share.getEntity().getKey().equals(entityKeyRandom)) {
            match = share;
            break;
        }
    }

    assertNotNull(match);
}

From source file:org.esigate.http.HttpClientRequestExecutorTest.java

/**
 * Test that we don't have a NullpointerException when forcing the caching (ttl).
 * /*from   ww w .  j  ava 2  s . c  o m*/
 * @throws Exception
 */
public void testForcedTtlWith304ResponseCode() throws Exception {
    properties = new Properties();
    properties.put(Parameters.REMOTE_URL_BASE.getName(), "http://localhost:8080");
    properties.put(Parameters.TTL.getName(), "1000");
    createHttpClientRequestExecutor();
    DriverRequest originalRequest = TestUtils.createDriverRequest(driver);
    originalRequest.getOriginalRequest().addHeader("If-Modified-Since", "Fri, 15 Jun 2012 21:06:25 GMT");
    OutgoingRequest request = httpClientRequestExecutor.createOutgoingRequest(originalRequest,
            "http://localhost:8080", false);
    HttpResponse response = new BasicHttpResponse(
            new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_NOT_MODIFIED, "Not Modified"));
    mockConnectionManager.setResponse(response);
    HttpResponse result = httpClientRequestExecutor.execute(request);
    if (result.getEntity() != null) {
        result.getEntity().writeTo(new NullOutputStream());
        // We should have had a NullpointerException
    }
}

From source file:org.esigate.http.HttpClientRequestExecutorTest.java

/**
 * Test that we don't have a NullpointerException when forcing the caching (ttl).
 * /*w ww  .j a v a 2 s  .  c o m*/
 * @throws Exception
 */
public void testForcedTtlWith301ResponseCode() throws Exception {
    properties = new Properties();
    properties.put(Parameters.REMOTE_URL_BASE.getName(), "http://localhost:8080");
    properties.put(Parameters.TTL.getName(), "1000");
    createHttpClientRequestExecutor();
    DriverRequest originalRequest = TestUtils.createDriverRequest(driver);
    OutgoingRequest request = httpClientRequestExecutor.createOutgoingRequest(originalRequest,
            "http://localhost:8080", true);
    HttpResponse response = new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1),
            HttpStatus.SC_MOVED_PERMANENTLY, "Moved permanently"));
    response.addHeader("Location", "http://www.foo.com");
    mockConnectionManager.setResponse(response);
    HttpResponse result = httpClientRequestExecutor.execute(request);
    if (result.getEntity() != null) {
        result.getEntity().writeTo(new NullOutputStream());
        // We should have had a NullpointerException
    }
}

From source file:org.esigate.http.HttpClientRequestExecutorTest.java

/**
 * Test that we don't have a NullpointerException when forcing the caching (ttl).
 * //w  w  w  . j  a  v  a  2s .co  m
 * @throws Exception
 */
public void testForcedTtlWith302ResponseCode() throws Exception {
    properties = new Properties();
    properties.put(Parameters.REMOTE_URL_BASE.getName(), "http://localhost:8080");
    properties.put(Parameters.TTL.getName(), "1000");
    createHttpClientRequestExecutor();
    DriverRequest originalRequest = TestUtils.createDriverRequest(driver);
    OutgoingRequest request = httpClientRequestExecutor.createOutgoingRequest(originalRequest,
            "http://localhost:8080", true);
    HttpResponse response = new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1),
            HttpStatus.SC_MOVED_TEMPORARILY, "Moved temporarily"));
    response.addHeader("Location", "http://www.foo.com");
    mockConnectionManager.setResponse(response);
    HttpResponse result = httpClientRequestExecutor.execute(request);
    if (result.getEntity() != null) {
        result.getEntity().writeTo(new NullOutputStream());
        // We should have had a NullpointerException
    }
}

From source file:org.esigate.http.HttpClientRequestExecutorTest.java

/**
 * Test Expires response header with ttl forced.
 * //  www  .j ava  2s .  c om
 * @throws Exception
 */
public void testExpiresResponseHeaderWithForcedTtl() throws Exception {
    properties = new Properties();
    properties.put(Parameters.REMOTE_URL_BASE, "http://localhost:8080");
    properties.put(Parameters.TTL, "1");
    properties.put(Parameters.X_CACHE_HEADER, "true");
    properties.put(Parameters.HEURISTIC_CACHING_ENABLED, "false");
    createHttpClientRequestExecutor();
    DriverRequest originalRequest = TestUtils.createDriverRequest(driver);

    OutgoingRequest request = httpClientRequestExecutor.createOutgoingRequest(originalRequest,
            "http://localhost:8080", false);

    HttpResponse response = new BasicHttpResponse(
            new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_OK, "OK"));
    response.addHeader("Date", "Mon, 10 Dec 2012 19:37:52 GMT");
    response.addHeader("Last-Modified", "Mon, 10 Dec 2012 19:35:27 GMT");
    response.addHeader("Expires", "Mon, 10 Dec 2012 20:35:27 GMT");
    response.addHeader("Cache-Control", "private, no-cache, must-revalidate, proxy-revalidate");
    response.setEntity(new StringEntity("test"));
    mockConnectionManager.setResponse(response);

    // First call to load the cache
    HttpResponse result = httpClientRequestExecutor.execute(request);
    assertNotNull(result.getFirstHeader("Expires"));
    assertNotNull(result.getFirstHeader("Cache-control"));
    assertEquals("public, max-age=1", (result.getFirstHeader("Cache-control").getValue()));

    // Same test with the cache entry
    // Change the response to check that the cache is used
    response = new BasicHttpResponse(
            new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_NOT_MODIFIED, "Not modified"));
    response.addHeader("Date", "Mon, 10 Dec 2012 19:37:52 GMT");
    response.addHeader("Expires", "Mon, 10 Dec 2012 20:35:27 GMT");
    response.addHeader("Cache-Control", "private, no-cache, must-revalidate, proxy-revalidate");
    mockConnectionManager.setResponse(response);

    result = httpClientRequestExecutor.execute(request);
    // Check that the cache has been used
    assertTrue(result.getFirstHeader("X-cache").getValue(),
            result.getFirstHeader("X-cache").getValue().startsWith("HIT"));
    assertNotNull(result.getFirstHeader("Expires"));
    assertNotNull(result.getFirstHeader("Cache-control"));
    assertEquals("public, max-age=1", (result.getFirstHeader("Cache-control").getValue()));

    // Wait for a revalidation to occur
    Thread.sleep(ONE_SECOND);

    result = httpClientRequestExecutor.execute(request);
    // Check that the revalidation occurred
    assertNotNull(result.getFirstHeader("Expires"));
    assertNotNull(result.getFirstHeader("Cache-control"));
    assertEquals("public, max-age=1", (result.getFirstHeader("Cache-control").getValue()));
    assertTrue(result.getFirstHeader("X-cache").getValue(),
            result.getFirstHeader("X-cache").getValue().startsWith("VALIDATED"));
}

From source file:org.esigate.http.HttpClientRequestExecutorTest.java

/**
 * Test that we do not return a 304 to a non-conditional request when ttl forced.
 * /*from w w  w  . j  a v a 2  s .co  m*/
 * @throws Exception
 */
public void testDoNotReturn304ForNonConditionalRequestWhenTtlSet() throws Exception {
    properties = new Properties();
    properties.put(Parameters.REMOTE_URL_BASE, "http://localhost:8080");
    properties.put(Parameters.TTL, "1");
    properties.put(Parameters.X_CACHE_HEADER, "true");
    createHttpClientRequestExecutor();

    DriverRequest originalRequest = TestUtils.createDriverRequest(driver);
    OutgoingRequest request1 = httpClientRequestExecutor.createOutgoingRequest(originalRequest,
            "http://localhost:8080", false);
    request1.addHeader("If-None-Match", "etag");

    HttpResponse response = new BasicHttpResponse(
            new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_NOT_MODIFIED, "Not modified"));
    response.addHeader("Date", "Mon, 10 Dec 2012 19:37:52 GMT");
    response.addHeader("Etag", "etag");
    response.addHeader("Cache-Control", "max-age=0");
    mockConnectionManager.setResponse(response);

    // First request returns a 304
    HttpResponse result1 = httpClientRequestExecutor.execute(request1);
    assertEquals(HttpStatus.SC_NOT_MODIFIED, result1.getStatusLine().getStatusCode());
    assertTrue(result1.getFirstHeader("X-cache").getValue(),
            result1.getFirstHeader("X-cache").getValue().startsWith("MISS"));
    assertNull(result1.getEntity());

    // Second request should use the cache and return a
    // 304 again
    HttpResponse result2 = httpClientRequestExecutor.execute(request1);
    assertEquals(HttpStatus.SC_NOT_MODIFIED, result1.getStatusLine().getStatusCode());
    assertTrue(result2.getFirstHeader("X-cache").getValue(),
            result2.getFirstHeader("X-cache").getValue().startsWith("HIT"));
    assertNull(result2.getEntity());

    HttpResponse response2 = new BasicHttpResponse(
            new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_OK, "Ok"));
    response2.addHeader("Date", "Mon, 10 Dec 2012 19:37:52 GMT");
    response2.addHeader("Etag", "etag");
    response2.addHeader("Cache-Control", "max-age=0");
    response2.setEntity(new StringEntity("test"));
    mockConnectionManager.setResponse(response2);

    // Third request not conditional ! Should call backend server as we
    // don't have the entity in the cache.
    OutgoingRequest request2 = httpClientRequestExecutor.createOutgoingRequest(originalRequest,
            "http://localhost:8080", false);
    HttpResponse result3 = httpClientRequestExecutor.execute(request2);
    assertEquals(HttpStatus.SC_OK, result3.getStatusLine().getStatusCode());
    assertTrue(result3.getFirstHeader("X-cache").getValue(),
            !result3.getFirstHeader("X-cache").getValue().startsWith("HIT"));
    assertNotNull(result3.getEntity());
}

From source file:org.apache.camel.component.olingo2.api.impl.Olingo2AppImpl.java

private Olingo2BatchResponse parseResponse(Edm edm, Map<String, String> contentIdLocationMap,
        Olingo2BatchRequest request, BatchSingleResponse response)
        throws EntityProviderException, ODataApplicationException {

    // validate HTTP status
    final int statusCode = Integer.parseInt(response.getStatusCode());
    final String statusInfo = response.getStatusInfo();

    final BasicHttpResponse httpResponse = new BasicHttpResponse(
            new BasicStatusLine(HttpVersion.HTTP_1_1, statusCode, statusInfo));
    final Map<String, String> headers = response.getHeaders();
    for (Map.Entry<String, String> entry : headers.entrySet()) {
        httpResponse.setHeader(entry.getKey(), entry.getValue());
    }/*  www  .ja  v  a 2  s  .  c om*/

    ByteArrayInputStream content = null;
    try {
        if (response.getBody() != null) {
            final ContentType partContentType = receiveWithCharsetParameter(
                    ContentType.parse(headers.get(HttpHeaders.CONTENT_TYPE)), Consts.UTF_8);
            final String charset = partContentType.getCharset().toString();

            final String body = response.getBody();
            content = body != null ? new ByteArrayInputStream(body.getBytes(charset)) : null;

            httpResponse.setEntity(new StringEntity(body, charset));
        }

        AbstractFutureCallback.checkStatus(httpResponse);
    } catch (ODataApplicationException e) {
        return new Olingo2BatchResponse(statusCode, statusInfo, response.getContentId(), response.getHeaders(),
                e);
    } catch (UnsupportedEncodingException e) {
        return new Olingo2BatchResponse(statusCode, statusInfo, response.getContentId(), response.getHeaders(),
                e);
    }

    // resolve resource path and query params and parse batch part uri
    final String resourcePath = request.getResourcePath();
    final String resolvedResourcePath;
    if (resourcePath.startsWith("$") && !(METADATA.equals(resourcePath) || BATCH.equals(resourcePath))) {
        resolvedResourcePath = findLocation(resourcePath, contentIdLocationMap);
    } else {
        final String resourceLocation = response.getHeader(HttpHeaders.LOCATION);
        resolvedResourcePath = resourceLocation != null ? resourceLocation.substring(serviceUri.length())
                : resourcePath;
    }
    final Map<String, String> resolvedQueryParams = request instanceof Olingo2BatchQueryRequest
            ? ((Olingo2BatchQueryRequest) request).getQueryParams()
            : null;
    final UriInfoWithType uriInfo = parseUri(edm, resolvedResourcePath, resolvedQueryParams);

    // resolve response content
    final Object resolvedContent = content != null ? readContent(uriInfo, content) : null;

    return new Olingo2BatchResponse(statusCode, statusInfo, response.getContentId(), response.getHeaders(),
            resolvedContent);
}