Search in sources :

Example 1 with HttpResponseHeaders

use of com.ning.http.client.HttpResponseHeaders in project connect-java-library by urbanairship.

the class StreamConnectionResponseHandlerTest method testBodyReceivedBeforeBodyConsumeLatchReleasedHandlerClosesProperly.

@Test
public void testBodyReceivedBeforeBodyConsumeLatchReleasedHandlerClosesProperly() throws Exception {
    int code = HttpURLConnection.HTTP_PAYMENT_REQUIRED;
    String message = RandomStringUtils.randomAlphabetic(20);
    HttpResponseStatus status = mock(HttpResponseStatus.class);
    when(status.getStatusCode()).thenReturn(code);
    when(status.getStatusText()).thenReturn(message);
    HttpResponseHeaders headers = mock(HttpResponseHeaders.class);
    when(headers.getHeaders()).thenReturn(new FluentCaseInsensitiveStringsMap(Collections.<String, Collection<String>>emptyMap()));
    handler.onStatusReceived(status);
    handler.onHeadersReceived(headers);
    final CountDownLatch bodyReceivedThreadStarted = new CountDownLatch(1);
    final CountDownLatch bodyReceivedThreadExit = new CountDownLatch(1);
    final HttpResponseBodyPart part = mock(HttpResponseBodyPart.class);
    ExecutorService bodyReceivedThread = Executors.newSingleThreadExecutor();
    Runnable bodyReceivedRunnable = new Runnable() {

        @Override
        public void run() {
            try {
                bodyReceivedThreadStarted.countDown();
                handler.onBodyPartReceived(part);
                bodyReceivedThreadExit.countDown();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    try {
        bodyReceivedThread.submit(bodyReceivedRunnable);
        assertTrue(bodyReceivedThreadStarted.await(10, TimeUnit.SECONDS));
        // Wait just an exta little bit to try to guarantee the body received call gets made...
        Thread.sleep(2000L);
        handler.stop();
        assertTrue(bodyReceivedThreadExit.await(10, TimeUnit.SECONDS));
    } finally {
        bodyReceivedThread.shutdownNow();
    }
}
Also used : HttpResponseHeaders(com.ning.http.client.HttpResponseHeaders) HttpResponseStatus(com.ning.http.client.HttpResponseStatus) FluentCaseInsensitiveStringsMap(com.ning.http.client.FluentCaseInsensitiveStringsMap) ExecutorService(java.util.concurrent.ExecutorService) Collection(java.util.Collection) CountDownLatch(java.util.concurrent.CountDownLatch) HttpResponseBodyPart(com.ning.http.client.HttpResponseBodyPart) TimeoutException(java.util.concurrent.TimeoutException) Test(org.junit.Test)

Example 2 with HttpResponseHeaders

use of com.ning.http.client.HttpResponseHeaders in project connect-java-library by urbanairship.

the class StreamConnectionResponseHandlerTest method testConnectFlow.

@Test
public void testConnectFlow() throws Exception {
    int code = HttpURLConnection.HTTP_OK;
    String message = RandomStringUtils.randomAlphabetic(20);
    HttpResponseStatus status = mock(HttpResponseStatus.class);
    when(status.getStatusCode()).thenReturn(code);
    when(status.getStatusText()).thenReturn(message);
    AsyncHandler.STATE state = handler.onStatusReceived(status);
    assertEquals(AsyncHandler.STATE.CONTINUE, state);
    HttpResponseHeaders headers = mock(HttpResponseHeaders.class);
    Map<String, Collection<String>> headerMap = ImmutableMap.of(RandomStringUtils.randomAlphanumeric(5), ImmutableList.of(RandomStringUtils.randomAlphabetic(10)), RandomStringUtils.randomAlphanumeric(5), (Collection<String>) ImmutableList.of(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(5)));
    when(headers.getHeaders()).thenReturn(new FluentCaseInsensitiveStringsMap(headerMap));
    state = handler.onHeadersReceived(headers);
    assertEquals(AsyncHandler.STATE.CONTINUE, state);
    ArgumentCaptor<StatusAndHeaders> captor = ArgumentCaptor.forClass(StatusAndHeaders.class);
    verify(connectCallback).connected(captor.capture());
    StatusAndHeaders received = captor.getValue();
    assertEquals(code, received.getStatusCode());
    assertEquals(message, received.getStatusMessage());
    assertEquals(headerMap, received.getHeaders());
}
Also used : AsyncHandler(com.ning.http.client.AsyncHandler) HttpResponseHeaders(com.ning.http.client.HttpResponseHeaders) HttpResponseStatus(com.ning.http.client.HttpResponseStatus) FluentCaseInsensitiveStringsMap(com.ning.http.client.FluentCaseInsensitiveStringsMap) Collection(java.util.Collection) Test(org.junit.Test)

Example 3 with HttpResponseHeaders

use of com.ning.http.client.HttpResponseHeaders in project jersey by jersey.

the class GrizzlyConnector method apply.

@Override
public Future<?> apply(final ClientRequest request, final AsyncConnectorCallback callback) {
    final Request connectorRequest = translate(request);
    final Map<String, String> clientHeadersSnapshot = writeOutBoundHeaders(request.getHeaders(), connectorRequest);
    final ByteBufferInputStream entityStream = new ByteBufferInputStream();
    final AtomicBoolean callbackInvoked = new AtomicBoolean(false);
    Throwable failure;
    try {
        return grizzlyClient.executeRequest(connectorRequest, new AsyncHandler<Void>() {

            private volatile HttpResponseStatus status = null;

            @Override
            public STATE onStatusReceived(final HttpResponseStatus responseStatus) throws Exception {
                status = responseStatus;
                return STATE.CONTINUE;
            }

            @Override
            public STATE onHeadersReceived(HttpResponseHeaders headers) throws Exception {
                if (!callbackInvoked.compareAndSet(false, true)) {
                    return STATE.ABORT;
                }
                HeaderUtils.checkHeaderChanges(clientHeadersSnapshot, request.getHeaders(), GrizzlyConnector.this.getClass().getName());
                // hand-off to grizzly's application thread pool for response processing
                processResponse(new Runnable() {

                    @Override
                    public void run() {
                        callback.response(translate(request, status, headers, entityStream));
                    }
                });
                return STATE.CONTINUE;
            }

            @Override
            public STATE onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception {
                entityStream.put(bodyPart.getBodyByteBuffer());
                return STATE.CONTINUE;
            }

            @Override
            public Void onCompleted() throws Exception {
                entityStream.closeQueue();
                return null;
            }

            @Override
            public void onThrowable(Throwable t) {
                entityStream.closeQueue(t);
                if (callbackInvoked.compareAndSet(false, true)) {
                    t = t instanceof IOException ? new ProcessingException(t.getMessage(), t) : t;
                    callback.failure(t);
                }
            }
        });
    } catch (Throwable t) {
        failure = t;
    }
    if (callbackInvoked.compareAndSet(false, true)) {
        callback.failure(failure);
    }
    CompletableFuture<Object> future = new CompletableFuture<>();
    future.completeExceptionally(failure);
    return future;
}
Also used : HttpResponseHeaders(com.ning.http.client.HttpResponseHeaders) HttpResponseStatus(com.ning.http.client.HttpResponseStatus) Request(com.ning.http.client.Request) ClientRequest(org.glassfish.jersey.client.ClientRequest) ByteBufferInputStream(org.glassfish.jersey.internal.util.collection.ByteBufferInputStream) IOException(java.io.IOException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) ProcessingException(javax.ws.rs.ProcessingException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) HttpResponseBodyPart(com.ning.http.client.HttpResponseBodyPart) ProcessingException(javax.ws.rs.ProcessingException)

Example 4 with HttpResponseHeaders

use of com.ning.http.client.HttpResponseHeaders in project jersey by jersey.

the class GrizzlyConnector method apply.

/**
     * Sends the {@link javax.ws.rs.core.Request} via Grizzly transport and returns the {@link javax.ws.rs.core.Response}.
     *
     * @param request Jersey client request to be sent.
     * @return received response.
     */
@Override
public ClientResponse apply(final ClientRequest request) {
    final Request connectorRequest = translate(request);
    final Map<String, String> clientHeadersSnapshot = writeOutBoundHeaders(request.getHeaders(), connectorRequest);
    final CompletableFuture<ClientResponse> responseFuture = new CompletableFuture<>();
    final ByteBufferInputStream entityStream = new ByteBufferInputStream();
    final AtomicBoolean futureSet = new AtomicBoolean(false);
    try {
        grizzlyClient.executeRequest(connectorRequest, new AsyncHandler<Void>() {

            private volatile HttpResponseStatus status = null;

            @Override
            public STATE onStatusReceived(final HttpResponseStatus responseStatus) throws Exception {
                status = responseStatus;
                return STATE.CONTINUE;
            }

            @Override
            public STATE onHeadersReceived(HttpResponseHeaders headers) throws Exception {
                if (!futureSet.compareAndSet(false, true)) {
                    return STATE.ABORT;
                }
                HeaderUtils.checkHeaderChanges(clientHeadersSnapshot, request.getHeaders(), GrizzlyConnector.this.getClass().getName());
                responseFuture.complete(translate(request, this.status, headers, entityStream));
                return STATE.CONTINUE;
            }

            @Override
            public STATE onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception {
                entityStream.put(bodyPart.getBodyByteBuffer());
                return STATE.CONTINUE;
            }

            @Override
            public Void onCompleted() throws Exception {
                entityStream.closeQueue();
                return null;
            }

            @Override
            public void onThrowable(Throwable t) {
                entityStream.closeQueue(t);
                if (futureSet.compareAndSet(false, true)) {
                    t = t instanceof IOException ? new ProcessingException(t.getMessage(), t) : t;
                    responseFuture.completeExceptionally(t);
                }
            }
        });
        return responseFuture.get();
    } catch (ExecutionException ex) {
        Throwable e = ex.getCause() == null ? ex : ex.getCause();
        throw new ProcessingException(e.getMessage(), e);
    } catch (InterruptedException ex) {
        throw new ProcessingException(ex.getMessage(), ex);
    }
}
Also used : ClientResponse(org.glassfish.jersey.client.ClientResponse) HttpResponseHeaders(com.ning.http.client.HttpResponseHeaders) HttpResponseStatus(com.ning.http.client.HttpResponseStatus) Request(com.ning.http.client.Request) ClientRequest(org.glassfish.jersey.client.ClientRequest) ByteBufferInputStream(org.glassfish.jersey.internal.util.collection.ByteBufferInputStream) IOException(java.io.IOException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) ProcessingException(javax.ws.rs.ProcessingException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) ExecutionException(java.util.concurrent.ExecutionException) HttpResponseBodyPart(com.ning.http.client.HttpResponseBodyPart) ProcessingException(javax.ws.rs.ProcessingException)

Example 5 with HttpResponseHeaders

use of com.ning.http.client.HttpResponseHeaders in project connect-java-library by urbanairship.

the class StreamConnectionResponseHandlerTest method testExceptionAfterConnect.

@Test
public void testExceptionAfterConnect() throws Exception {
    int code = HttpURLConnection.HTTP_OK;
    String message = RandomStringUtils.randomAlphabetic(20);
    HttpResponseStatus status = mock(HttpResponseStatus.class);
    when(status.getStatusCode()).thenReturn(code);
    when(status.getStatusText()).thenReturn(message);
    HttpResponseHeaders headers = mock(HttpResponseHeaders.class);
    when(headers.getHeaders()).thenReturn(new FluentCaseInsensitiveStringsMap(Collections.<String, Collection<String>>emptyMap()));
    handler.onStatusReceived(status);
    handler.onHeadersReceived(headers);
    Throwable exception = new RuntimeException("boom");
    handler.onThrowable(exception);
    Optional<Throwable> error = handler.getError();
    assertTrue(error.isPresent());
    assertEquals(exception, error.get());
}
Also used : HttpResponseHeaders(com.ning.http.client.HttpResponseHeaders) HttpResponseStatus(com.ning.http.client.HttpResponseStatus) FluentCaseInsensitiveStringsMap(com.ning.http.client.FluentCaseInsensitiveStringsMap) Collection(java.util.Collection) Test(org.junit.Test)

Aggregations

HttpResponseHeaders (com.ning.http.client.HttpResponseHeaders)5 HttpResponseStatus (com.ning.http.client.HttpResponseStatus)5 FluentCaseInsensitiveStringsMap (com.ning.http.client.FluentCaseInsensitiveStringsMap)3 HttpResponseBodyPart (com.ning.http.client.HttpResponseBodyPart)3 Collection (java.util.Collection)3 Test (org.junit.Test)3 Request (com.ning.http.client.Request)2 IOException (java.io.IOException)2 CompletableFuture (java.util.concurrent.CompletableFuture)2 ExecutionException (java.util.concurrent.ExecutionException)2 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)2 ProcessingException (javax.ws.rs.ProcessingException)2 ClientRequest (org.glassfish.jersey.client.ClientRequest)2 ByteBufferInputStream (org.glassfish.jersey.internal.util.collection.ByteBufferInputStream)2 AsyncHandler (com.ning.http.client.AsyncHandler)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 ExecutorService (java.util.concurrent.ExecutorService)1 TimeoutException (java.util.concurrent.TimeoutException)1 ClientResponse (org.glassfish.jersey.client.ClientResponse)1