use of org.eclipse.jetty.client.api.Request in project jetty.project by eclipse.
the class HttpRedirector method redirect.
/**
* Redirects the given {@code response}, blocking until the redirect is complete.
*
* @param request the original request that triggered the redirect
* @param response the response to the original request
* @return a {@link Result} object containing the request to the redirected location and its response
* @throws InterruptedException if the thread is interrupted while waiting for the redirect to complete
* @throws ExecutionException if the redirect failed
* @see #redirect(Request, Response, Response.CompleteListener)
*/
public Result redirect(Request request, Response response) throws InterruptedException, ExecutionException {
final AtomicReference<Result> resultRef = new AtomicReference<>();
final CountDownLatch latch = new CountDownLatch(1);
Request redirect = redirect(request, response, new BufferingResponseListener() {
@Override
public void onComplete(Result result) {
resultRef.set(new Result(result.getRequest(), result.getRequestFailure(), new HttpContentResponse(result.getResponse(), getContent(), getMediaType(), getEncoding()), result.getResponseFailure()));
latch.countDown();
}
});
try {
latch.await();
Result result = resultRef.get();
if (result.isFailed())
throw new ExecutionException(result.getFailure());
return result;
} catch (InterruptedException x) {
// If the application interrupts, we need to abort the redirect
redirect.abort(x);
throw x;
}
}
use of org.eclipse.jetty.client.api.Request in project jetty.project by eclipse.
the class ProxyServlet method service.
@Override
protected void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
final int requestId = getRequestId(request);
String rewrittenTarget = rewriteTarget(request);
if (_log.isDebugEnabled()) {
StringBuffer uri = request.getRequestURL();
if (request.getQueryString() != null)
uri.append("?").append(request.getQueryString());
if (_log.isDebugEnabled())
_log.debug("{} rewriting: {} -> {}", requestId, uri, rewrittenTarget);
}
if (rewrittenTarget == null) {
onProxyRewriteFailed(request, response);
return;
}
final Request proxyRequest = getHttpClient().newRequest(rewrittenTarget).method(request.getMethod()).version(HttpVersion.fromString(request.getProtocol()));
copyRequestHeaders(request, proxyRequest);
addProxyHeaders(request, proxyRequest);
final AsyncContext asyncContext = request.startAsync();
// We do not timeout the continuation, but the proxy request
asyncContext.setTimeout(0);
proxyRequest.timeout(getTimeout(), TimeUnit.MILLISECONDS);
if (hasContent(request)) {
if (expects100Continue(request)) {
DeferredContentProvider deferred = new DeferredContentProvider();
proxyRequest.content(deferred);
proxyRequest.attribute(CLIENT_REQUEST_ATTRIBUTE, request);
proxyRequest.attribute(CONTINUE_ACTION_ATTRIBUTE, (Runnable) () -> {
try {
ContentProvider provider = proxyRequestContent(request, response, proxyRequest);
new DelegatingContentProvider(request, proxyRequest, response, provider, deferred).iterate();
} catch (Throwable failure) {
onClientRequestFailure(request, proxyRequest, response, failure);
}
});
} else {
proxyRequest.content(proxyRequestContent(request, response, proxyRequest));
}
}
sendProxyRequest(request, response, proxyRequest);
}
use of org.eclipse.jetty.client.api.Request in project jetty.project by eclipse.
the class AsyncMiddleManServletTest method testDiscardUpstreamAndDownstreamKnownContentLengthGzipped.
@Test
public void testDiscardUpstreamAndDownstreamKnownContentLengthGzipped() throws Exception {
final byte[] bytes = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".getBytes(StandardCharsets.UTF_8);
startServer(new HttpServlet() {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// decode input stream thru gzip
ByteArrayOutputStream bos = new ByteArrayOutputStream();
IO.copy(new GZIPInputStream(request.getInputStream()), bos);
// ensure decompressed is 0 length
Assert.assertEquals(0, bos.toByteArray().length);
response.setHeader(HttpHeader.CONTENT_ENCODING.asString(), "gzip");
response.getOutputStream().write(gzip(bytes));
}
});
startProxy(new AsyncMiddleManServlet() {
@Override
protected ContentTransformer newClientRequestContentTransformer(HttpServletRequest clientRequest, Request proxyRequest) {
return new GZIPContentTransformer(new DiscardContentTransformer());
}
@Override
protected ContentTransformer newServerResponseContentTransformer(HttpServletRequest clientRequest, HttpServletResponse proxyResponse, Response serverResponse) {
return new GZIPContentTransformer(new DiscardContentTransformer());
}
});
startClient();
ContentResponse response = client.newRequest("localhost", serverConnector.getLocalPort()).header(HttpHeader.CONTENT_ENCODING, "gzip").content(new BytesContentProvider(gzip(bytes))).timeout(5, TimeUnit.SECONDS).send();
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals(0, response.getContent().length);
}
use of org.eclipse.jetty.client.api.Request in project jetty.project by eclipse.
the class AsyncMiddleManServletTest method testAfterContentTransformerClosingFilesOnClientRequestException.
@Test
public void testAfterContentTransformerClosingFilesOnClientRequestException() throws Exception {
final Path targetTestsDir = prepareTargetTestsDir();
startServer(new HttpServlet() {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
IO.copy(request.getInputStream(), IO.getNullStream());
}
});
final CountDownLatch destroyLatch = new CountDownLatch(1);
startProxy(new AsyncMiddleManServlet() {
@Override
protected ContentTransformer newClientRequestContentTransformer(HttpServletRequest clientRequest, Request proxyRequest) {
return new AfterContentTransformer() {
{
setOverflowDirectory(targetTestsDir);
setMaxInputBufferSize(0);
setMaxOutputBufferSize(0);
}
@Override
public boolean transform(Source source, Sink sink) throws IOException {
IO.copy(source.getInputStream(), sink.getOutputStream());
return true;
}
@Override
public void destroy() {
super.destroy();
destroyLatch.countDown();
}
};
}
});
long idleTimeout = 1000;
proxyConnector.setIdleTimeout(idleTimeout);
startClient();
// Send only part of the content; the proxy will idle timeout.
final byte[] data = new byte[] { 'c', 'a', 'f', 'e' };
ContentResponse response = client.newRequest("localhost", serverConnector.getLocalPort()).content(new BytesContentProvider(data) {
@Override
public long getLength() {
return data.length + 1;
}
}).timeout(5 * idleTimeout, TimeUnit.MILLISECONDS).send();
Assert.assertTrue(destroyLatch.await(5 * idleTimeout, TimeUnit.MILLISECONDS));
Assert.assertEquals(HttpStatus.REQUEST_TIMEOUT_408, response.getStatus());
}
use of org.eclipse.jetty.client.api.Request in project jetty.project by eclipse.
the class AsyncMiddleManServletTest method testProxyRequestHeadersNotSentUntilContent.
@Test
public void testProxyRequestHeadersNotSentUntilContent() throws Exception {
startServer(new EchoHttpServlet());
final CountDownLatch proxyRequestLatch = new CountDownLatch(1);
startProxy(new AsyncMiddleManServlet() {
@Override
protected ContentTransformer newClientRequestContentTransformer(HttpServletRequest clientRequest, Request proxyRequest) {
return new BufferingContentTransformer();
}
@Override
protected void sendProxyRequest(HttpServletRequest clientRequest, HttpServletResponse proxyResponse, Request proxyRequest) {
proxyRequestLatch.countDown();
super.sendProxyRequest(clientRequest, proxyResponse, proxyRequest);
}
});
startClient();
DeferredContentProvider content = new DeferredContentProvider();
Request request = client.newRequest("localhost", serverConnector.getLocalPort()).timeout(5, TimeUnit.SECONDS).content(content);
FutureResponseListener listener = new FutureResponseListener(request);
request.send(listener);
// Send one chunk of content, the proxy request must not be sent.
ByteBuffer chunk1 = ByteBuffer.allocate(1024);
content.offer(chunk1);
Assert.assertFalse(proxyRequestLatch.await(1, TimeUnit.SECONDS));
// Send another chunk of content, the proxy request must not be sent.
ByteBuffer chunk2 = ByteBuffer.allocate(512);
content.offer(chunk2);
Assert.assertFalse(proxyRequestLatch.await(1, TimeUnit.SECONDS));
// Finish the content, request must be sent.
content.close();
Assert.assertTrue(proxyRequestLatch.await(1, TimeUnit.SECONDS));
ContentResponse response = listener.get(5, TimeUnit.SECONDS);
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
Assert.assertEquals(chunk1.capacity() + chunk2.capacity(), response.getContent().length);
}
Aggregations