use of org.eclipse.jetty.client.api.Response in project jetty.project by eclipse.
the class HttpClientStreamTest method testInputStreamResponseListenerClosedBeforeContent.
@Test(expected = AsynchronousCloseException.class)
public void testInputStreamResponseListenerClosedBeforeContent() throws Exception {
AtomicReference<AsyncContext> contextRef = new AtomicReference<>();
start(new AbstractHandler() {
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
baseRequest.setHandled(true);
contextRef.set(request.startAsync());
response.flushBuffer();
}
});
CountDownLatch latch = new CountDownLatch(1);
InputStreamResponseListener listener = new InputStreamResponseListener() {
@Override
public void onContent(Response response, ByteBuffer content, Callback callback) {
super.onContent(response, content, new Callback() {
@Override
public void failed(Throwable x) {
latch.countDown();
callback.failed(x);
}
});
}
};
client.newRequest("localhost", connector.getLocalPort()).scheme(getScheme()).send(listener);
Response response = listener.get(5, TimeUnit.SECONDS);
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
InputStream input = listener.getInputStream();
input.close();
AsyncContext asyncContext = contextRef.get();
asyncContext.getResponse().getOutputStream().write(new byte[1024]);
asyncContext.complete();
Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
// Throws
input.read();
}
use of org.eclipse.jetty.client.api.Response in project jetty.project by eclipse.
the class HttpClientTest method testClientManyWritesSlowServer.
@Test
public void testClientManyWritesSlowServer() throws Exception {
start(new AbstractHandler() {
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
baseRequest.setHandled(true);
long sleep = 1024;
long total = 0;
ServletInputStream input = request.getInputStream();
byte[] buffer = new byte[1024];
while (true) {
int read = input.read(buffer);
if (read < 0)
break;
total += read;
if (total >= sleep) {
sleep(250);
sleep += 256;
}
}
response.getOutputStream().print(total);
}
});
int chunks = 256;
int chunkSize = 16;
byte[][] bytes = IntStream.range(0, chunks).mapToObj(x -> new byte[chunkSize]).toArray(byte[][]::new);
BytesContentProvider contentProvider = new BytesContentProvider("application/octet-stream", bytes);
ContentResponse response = client.newRequest(newURI()).method(HttpMethod.POST).content(contentProvider).timeout(15, TimeUnit.SECONDS).send();
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
Assert.assertEquals(chunks * chunkSize, Integer.parseInt(response.getContentAsString()));
}
use of org.eclipse.jetty.client.api.Response in project jetty.project by eclipse.
the class HttpClientTest method testAsyncResponseContentBackPressure.
@Test
public void testAsyncResponseContentBackPressure() throws Exception {
start(new AbstractHandler() {
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
baseRequest.setHandled(true);
// Large write to generate multiple DATA frames.
response.getOutputStream().write(new byte[256 * 1024]);
}
});
CountDownLatch completeLatch = new CountDownLatch(1);
AtomicInteger counter = new AtomicInteger();
AtomicReference<Callback> callbackRef = new AtomicReference<>();
AtomicReference<CountDownLatch> latchRef = new AtomicReference<>(new CountDownLatch(1));
client.newRequest("localhost", connector.getLocalPort()).scheme(getScheme()).onResponseContentAsync((response, content, callback) -> {
if (counter.incrementAndGet() == 1) {
callbackRef.set(callback);
latchRef.get().countDown();
} else {
callback.succeeded();
}
}).send(result -> completeLatch.countDown());
Assert.assertTrue(latchRef.get().await(5, TimeUnit.SECONDS));
// Wait some time to verify that back pressure is applied correctly.
Thread.sleep(1000);
Assert.assertEquals(1, counter.get());
callbackRef.get().succeeded();
Assert.assertTrue(completeLatch.await(5, TimeUnit.SECONDS));
}
use of org.eclipse.jetty.client.api.Response in project jetty.project by eclipse.
the class HttpClientContinueTest method test_Expect100Continue_WithContent_WithResponseFailure_During100Continue.
@Test
public void test_Expect100Continue_WithContent_WithResponseFailure_During100Continue() throws Exception {
start(new AbstractHandler() {
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
baseRequest.setHandled(true);
// Send 100-Continue and consume the content
IO.copy(request.getInputStream(), new ByteArrayOutputStream());
}
});
client.getProtocolHandlers().clear();
client.getProtocolHandlers().put(new ContinueProtocolHandler() {
@Override
public Response.Listener getResponseListener() {
final Response.Listener listener = super.getResponseListener();
return new Response.Listener.Adapter() {
@Override
public void onBegin(Response response) {
response.abort(new Exception());
}
@Override
public void onFailure(Response response, Throwable failure) {
listener.onFailure(response, failure);
}
};
}
});
byte[] content = new byte[1024];
final CountDownLatch latch = new CountDownLatch(1);
client.newRequest(newURI()).header(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE.asString()).content(new BytesContentProvider(content)).send(new BufferingResponseListener() {
@Override
public void onComplete(Result result) {
Assert.assertTrue(result.isFailed());
Assert.assertNotNull(result.getRequestFailure());
Assert.assertNotNull(result.getResponseFailure());
latch.countDown();
}
});
Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
}
use of org.eclipse.jetty.client.api.Response in project druid by druid-io.
the class AsyncQueryForwardingServlet method service.
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
final boolean isSmile = SmileMediaTypes.APPLICATION_JACKSON_SMILE.equals(request.getContentType()) || APPLICATION_SMILE.equals(request.getContentType());
final ObjectMapper objectMapper = isSmile ? smileMapper : jsonMapper;
request.setAttribute(OBJECTMAPPER_ATTRIBUTE, objectMapper);
final String defaultHost = hostFinder.getDefaultHost();
request.setAttribute(HOST_ATTRIBUTE, defaultHost);
final boolean isQueryEndpoint = request.getRequestURI().startsWith("/druid/v2");
if (isQueryEndpoint && HttpMethod.DELETE.is(request.getMethod())) {
// query cancellation request
for (final String host : hostFinder.getAllHosts()) {
// to keep the code simple, the proxy servlet will also send a request to one of the default brokers
if (!host.equals(defaultHost)) {
// issue async requests
broadcastClient.newRequest(rewriteURI(request, host)).method(HttpMethod.DELETE).timeout(CANCELLATION_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS).send(new Response.CompleteListener() {
@Override
public void onComplete(Result result) {
if (result.isFailed()) {
log.warn(result.getFailure(), "Failed to forward cancellation request to [%s]", host);
}
}
});
}
interruptedQueryCount.incrementAndGet();
}
} else if (isQueryEndpoint && HttpMethod.POST.is(request.getMethod())) {
// query request
try {
Query inputQuery = objectMapper.readValue(request.getInputStream(), Query.class);
if (inputQuery != null) {
request.setAttribute(HOST_ATTRIBUTE, hostFinder.getHost(inputQuery));
if (inputQuery.getId() == null) {
inputQuery = inputQuery.withId(UUID.randomUUID().toString());
}
}
request.setAttribute(QUERY_ATTRIBUTE, inputQuery);
} catch (IOException e) {
log.warn(e, "Exception parsing query");
final String errorMessage = e.getMessage() == null ? "no error message" : e.getMessage();
requestLogger.log(new RequestLogLine(new DateTime(), request.getRemoteAddr(), null, new QueryStats(ImmutableMap.<String, Object>of("success", false, "exception", errorMessage))));
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.setContentType(MediaType.APPLICATION_JSON);
objectMapper.writeValue(response.getOutputStream(), ImmutableMap.of("error", errorMessage));
return;
} catch (Exception e) {
handleException(response, objectMapper, e);
return;
}
}
super.service(request, response);
}
Aggregations