use of org.asynchttpclient.HttpResponseStatus in project async-http-client by AsyncHttpClient.
the class ZeroCopyFileTest method zeroCopyFileTest.
@Test(groups = "standalone")
public void zeroCopyFileTest() throws IOException, ExecutionException, TimeoutException, InterruptedException, URISyntaxException {
File tmp = new File(System.getProperty("java.io.tmpdir") + File.separator + "zeroCopy.txt");
tmp.deleteOnExit();
try (AsyncHttpClient client = asyncHttpClient()) {
try (FileOutputStream stream = new FileOutputStream(tmp)) {
Response resp = client.preparePost("http://localhost:" + port1 + "/").setBody(SIMPLE_TEXT_FILE).execute(new AsyncHandler<Response>() {
public void onThrowable(Throwable t) {
}
public State onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception {
stream.write(bodyPart.getBodyPartBytes());
return State.CONTINUE;
}
public State onStatusReceived(HttpResponseStatus responseStatus) throws Exception {
return State.CONTINUE;
}
public State onHeadersReceived(HttpResponseHeaders headers) throws Exception {
return State.CONTINUE;
}
public Response onCompleted() throws Exception {
return null;
}
}).get();
assertNull(resp);
assertEquals(SIMPLE_TEXT_FILE.length(), tmp.length());
}
}
}
use of org.asynchttpclient.HttpResponseStatus in project async-http-client by AsyncHttpClient.
the class ZeroCopyFileTest method zeroCopyFileWithBodyManipulationTest.
@Test(groups = "standalone")
public void zeroCopyFileWithBodyManipulationTest() throws IOException, ExecutionException, TimeoutException, InterruptedException, URISyntaxException {
File tmp = new File(System.getProperty("java.io.tmpdir") + File.separator + "zeroCopy.txt");
tmp.deleteOnExit();
try (AsyncHttpClient client = asyncHttpClient()) {
try (FileOutputStream stream = new FileOutputStream(tmp)) {
Response resp = client.preparePost("http://localhost:" + port1 + "/").setBody(SIMPLE_TEXT_FILE).execute(new AsyncHandler<Response>() {
public void onThrowable(Throwable t) {
}
public State onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception {
stream.write(bodyPart.getBodyPartBytes());
if (bodyPart.getBodyPartBytes().length == 0) {
return State.ABORT;
}
return State.CONTINUE;
}
public State onStatusReceived(HttpResponseStatus responseStatus) throws Exception {
return State.CONTINUE;
}
public State onHeadersReceived(HttpResponseHeaders headers) throws Exception {
return State.CONTINUE;
}
public Response onCompleted() throws Exception {
return null;
}
}).get();
assertNull(resp);
assertEquals(SIMPLE_TEXT_FILE.length(), tmp.length());
}
}
}
use of org.asynchttpclient.HttpResponseStatus 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.HttpResponseStatus 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.HttpResponseStatus in project async-http-client by AsyncHttpClient.
the class WebSocketHandler method handleRead.
@Override
public void handleRead(Channel channel, NettyResponseFuture<?> future, Object e) throws Exception {
if (e instanceof HttpResponse) {
HttpResponse response = (HttpResponse) e;
if (logger.isDebugEnabled()) {
HttpRequest httpRequest = future.getNettyRequest().getHttpRequest();
logger.debug("\n\nRequest {}\n\nResponse {}\n", httpRequest, response);
}
WebSocketUpgradeHandler handler = (WebSocketUpgradeHandler) future.getAsyncHandler();
HttpResponseStatus status = new NettyResponseStatus(future.getUri(), response, channel);
HttpResponseHeaders responseHeaders = new HttpResponseHeaders(response.headers());
if (!interceptors.exitAfterIntercept(channel, future, handler, response, status, responseHeaders)) {
switch(handler.onStatusReceived(status)) {
case CONTINUE:
upgrade(channel, future, handler, response, responseHeaders);
break;
default:
abort(channel, future, handler, status);
}
}
} else if (e instanceof WebSocketFrame) {
final WebSocketFrame frame = (WebSocketFrame) e;
WebSocketUpgradeHandler handler = (WebSocketUpgradeHandler) future.getAsyncHandler();
NettyWebSocket webSocket = handler.onCompleted();
// retain because we might buffer the frame
if (webSocket.isReady()) {
webSocket.handleFrame(frame);
} else {
// WebSocket hasn't been open yet, but upgrading the pipeline triggered a read and a frame was sent along the HTTP upgrade response
// as we want to keep sequential order (but can't notify user of open before upgrading so he doesn't to try send immediately), we have to buffer
webSocket.bufferFrame(frame);
}
} else if (!(e instanceof LastHttpContent)) {
// ignore, end of handshake response
logger.error("Invalid message {}", e);
}
}
Aggregations