use of org.asynchttpclient.HttpResponseBodyPart in project async-http-client by AsyncHttpClient.
the class NettyReactiveStreamsTest method testRetryingOnFailingStream.
@Test(groups = "standalone")
public void testRetryingOnFailingStream() throws Exception {
try (AsyncHttpClient client = asyncHttpClient()) {
// allows us to wait until subscriber has received the first body chunk
final CountDownLatch streamStarted = new CountDownLatch(1);
// allows us to hold the subscriber from processing further body chunks
final CountDownLatch streamOnHold = new CountDownLatch(1);
// allows us to block until the request is being replayed ( this is what we want to test here!)
final CountDownLatch replayingRequest = new CountDownLatch(1);
// a ref to the publisher is needed to get a hold on the channel (if there is a better way, this should be changed)
final AtomicReference<StreamedResponsePublisher> publisherRef = new AtomicReference<>(null);
// executing the request
client.preparePost(getTargetUrl()).setBody(LARGE_IMAGE_BYTES).execute(new ReplayedSimpleAsyncHandler(replayingRequest, new BlockedStreamSubscriber(streamStarted, streamOnHold)) {
@Override
public State onStream(Publisher<HttpResponseBodyPart> publisher) {
if (!(publisher instanceof StreamedResponsePublisher)) {
throw new IllegalStateException(String.format("publisher %s is expected to be an instance of %s", publisher, StreamedResponsePublisher.class));
} else if (!publisherRef.compareAndSet(null, (StreamedResponsePublisher) publisher)) {
// abort on retry
return State.ABORT;
}
return super.onStream(publisher);
}
});
// before proceeding, wait for the subscriber to receive at least one body chunk
streamStarted.await();
// The stream has started, hence `StreamedAsyncHandler.onStream(publisher)` was called, and `publisherRef` was initialized with the `publisher` passed to `onStream`
assertTrue(publisherRef.get() != null, "Expected a not null publisher.");
// close the channel to emulate a connection crash while the response body chunks were being received.
StreamedResponsePublisher publisher = publisherRef.get();
final CountDownLatch channelClosed = new CountDownLatch(1);
getChannel(publisher).close().addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
channelClosed.countDown();
}
});
// the subscriber is set free to process new incoming body chunks.
streamOnHold.countDown();
// the channel is confirmed to be closed
channelClosed.await();
// now we expect a new connection to be created and AHC retry logic to kick-in automatically
// wait until we are notified the request is being replayed
replayingRequest.await();
// Change this if there is a better way of stating the test succeeded
assertTrue(true);
}
}
use of org.asynchttpclient.HttpResponseBodyPart in project async-http-client by AsyncHttpClient.
the class EmptyBodyTest method testEmptyBody.
@Test(groups = "standalone")
public void testEmptyBody() throws IOException {
try (AsyncHttpClient ahc = asyncHttpClient()) {
final AtomicBoolean err = new AtomicBoolean(false);
final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>();
final AtomicBoolean status = new AtomicBoolean(false);
final AtomicInteger headers = new AtomicInteger(0);
final CountDownLatch latch = new CountDownLatch(1);
ahc.executeRequest(ahc.prepareGet(getTargetUrl()).build(), new AsyncHandler<Object>() {
public void onThrowable(Throwable t) {
fail("Got throwable.", t);
err.set(true);
}
public State onBodyPartReceived(HttpResponseBodyPart e) throws Exception {
byte[] bytes = e.getBodyPartBytes();
if (bytes.length != 0) {
String s = new String(bytes);
logger.info("got part: {}", s);
logger.warn("Sampling stacktrace.", new Throwable("trace that, we should not get called for empty body."));
queue.put(s);
}
return State.CONTINUE;
}
public State onStatusReceived(HttpResponseStatus e) throws Exception {
status.set(true);
return AsyncHandler.State.CONTINUE;
}
public State onHeadersReceived(HttpResponseHeaders e) throws Exception {
if (headers.incrementAndGet() == 2) {
throw new Exception("Analyze this.");
}
return State.CONTINUE;
}
public Object onCompleted() throws Exception {
latch.countDown();
return null;
}
});
try {
assertTrue(latch.await(1, TimeUnit.SECONDS), "Latch failed.");
} catch (InterruptedException e) {
fail("Interrupted.", e);
}
assertFalse(err.get());
assertEquals(queue.size(), 0);
assertTrue(status.get());
assertEquals(headers.get(), 1);
}
}
use of org.asynchttpclient.HttpResponseBodyPart in project async-http-client by AsyncHttpClient.
the class ResumableAsyncHandlerTest method testOnBodyPartReceivedWithDecoratedAsyncHandler.
@Test
public void testOnBodyPartReceivedWithDecoratedAsyncHandler() throws Exception {
HttpResponseBodyPart bodyPart = PowerMockito.mock(HttpResponseBodyPart.class);
when(bodyPart.getBodyPartBytes()).thenReturn(new byte[0]);
ByteBuffer buffer = ByteBuffer.allocate(0);
when(bodyPart.getBodyByteBuffer()).thenReturn(buffer);
@SuppressWarnings("unchecked") AsyncHandler<Response> decoratedAsyncHandler = mock(AsyncHandler.class);
State mockState = mock(State.class);
when(decoratedAsyncHandler.onBodyPartReceived(bodyPart)).thenReturn(mockState);
// following is needed to set the url variable
HttpResponseStatus mockResponseStatus = mock(HttpResponseStatus.class);
when(mockResponseStatus.getStatusCode()).thenReturn(200);
Uri mockUri = mock(Uri.class);
when(mockUri.toUrl()).thenReturn("http://non.null");
when(mockResponseStatus.getUri()).thenReturn(mockUri);
ResumableAsyncHandler handler = new ResumableAsyncHandler(decoratedAsyncHandler);
handler.onStatusReceived(mockResponseStatus);
State state = handler.onBodyPartReceived(bodyPart);
assertEquals(state, mockState, "State should be equal to the state returned from decoratedAsyncHandler");
}
use of org.asynchttpclient.HttpResponseBodyPart in project async-http-client by AsyncHttpClient.
the class ResumableAsyncHandlerTest method testOnBodyPartReceived.
@Test
public void testOnBodyPartReceived() throws Exception {
ResumableAsyncHandler handler = new ResumableAsyncHandler();
HttpResponseBodyPart bodyPart = PowerMockito.mock(HttpResponseBodyPart.class);
when(bodyPart.getBodyPartBytes()).thenReturn(new byte[0]);
ByteBuffer buffer = ByteBuffer.allocate(0);
when(bodyPart.getBodyByteBuffer()).thenReturn(buffer);
State state = handler.onBodyPartReceived(bodyPart);
assertEquals(state, AsyncHandler.State.CONTINUE, "State should be CONTINUE for a successful onBodyPartReceived");
}
use of org.asynchttpclient.HttpResponseBodyPart in project async-http-client by AsyncHttpClient.
the class NettyResponse method getResponseBodyAsByteBuffer.
@Override
public ByteBuffer getResponseBodyAsByteBuffer() {
int length = 0;
for (HttpResponseBodyPart part : bodyParts) length += part.length();
ByteBuffer target = ByteBuffer.wrap(new byte[length]);
for (HttpResponseBodyPart part : bodyParts) target.put(part.getBodyPartBytes());
target.flip();
return target;
}
Aggregations