Search in sources :

Example 86 with AsyncContext

use of javax.servlet.AsyncContext in project jetty.project by eclipse.

the class AsyncIOTest method testLastContentAvailableBeforeService.

@Test
public void testLastContentAvailableBeforeService() throws Exception {
    start(new HttpServlet() {

        @Override
        protected void service(final HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // Wait for the data to fully arrive.
            sleep(1000);
            final AsyncContext asyncContext = request.startAsync();
            asyncContext.setTimeout(0);
            request.getInputStream().setReadListener(new EmptyReadListener() {

                @Override
                public void onDataAvailable() throws IOException {
                    ServletInputStream input = request.getInputStream();
                    while (input.isReady()) {
                        int read = input.read();
                        if (read < 0)
                            break;
                    }
                    if (input.isFinished())
                        asyncContext.complete();
                }
            });
        }
    });
    Session session = newClient(new Session.Listener.Adapter());
    HttpFields fields = new HttpFields();
    MetaData.Request metaData = newRequest("GET", fields);
    HeadersFrame frame = new HeadersFrame(metaData, null, false);
    final CountDownLatch latch = new CountDownLatch(1);
    FuturePromise<Stream> promise = new FuturePromise<>();
    session.newStream(frame, promise, new Stream.Listener.Adapter() {

        @Override
        public void onHeaders(Stream stream, HeadersFrame frame) {
            if (frame.isEndStream())
                latch.countDown();
        }
    });
    Stream stream = promise.get(5, TimeUnit.SECONDS);
    stream.data(new DataFrame(stream.getId(), ByteBuffer.allocate(16), true), Callback.NOOP);
    Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
}
Also used : ReadListener(javax.servlet.ReadListener) HttpServlet(javax.servlet.http.HttpServlet) FuturePromise(org.eclipse.jetty.util.FuturePromise) HttpServletResponse(javax.servlet.http.HttpServletResponse) AsyncContext(javax.servlet.AsyncContext) IOException(java.io.IOException) InterruptedIOException(java.io.InterruptedIOException) DataFrame(org.eclipse.jetty.http2.frames.DataFrame) CountDownLatch(java.util.concurrent.CountDownLatch) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ServletInputStream(javax.servlet.ServletInputStream) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) ServletInputStream(javax.servlet.ServletInputStream) Stream(org.eclipse.jetty.http2.api.Stream) Session(org.eclipse.jetty.http2.api.Session) Test(org.junit.Test)

Example 87 with AsyncContext

use of javax.servlet.AsyncContext in project jetty.project by eclipse.

the class AsyncIOTest method testLastContentAvailableAfterServiceReturns.

@Test
public void testLastContentAvailableAfterServiceReturns() throws Exception {
    start(new HttpServlet() {

        @Override
        protected void service(final HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            final AsyncContext asyncContext = request.startAsync();
            asyncContext.setTimeout(0);
            request.getInputStream().setReadListener(new EmptyReadListener() {

                @Override
                public void onDataAvailable() throws IOException {
                    ServletInputStream input = request.getInputStream();
                    while (input.isReady()) {
                        int read = input.read();
                        if (read < 0)
                            break;
                    }
                    if (input.isFinished())
                        asyncContext.complete();
                }
            });
        }
    });
    Session session = newClient(new Session.Listener.Adapter());
    HttpFields fields = new HttpFields();
    MetaData.Request metaData = newRequest("GET", fields);
    HeadersFrame frame = new HeadersFrame(metaData, null, false);
    final CountDownLatch latch = new CountDownLatch(1);
    FuturePromise<Stream> promise = new FuturePromise<>();
    session.newStream(frame, promise, new Stream.Listener.Adapter() {

        @Override
        public void onHeaders(Stream stream, HeadersFrame frame) {
            if (frame.isEndStream())
                latch.countDown();
        }
    });
    Stream stream = promise.get(5, TimeUnit.SECONDS);
    // Wait until service() returns.
    Thread.sleep(1000);
    stream.data(new DataFrame(stream.getId(), ByteBuffer.allocate(16), true), Callback.NOOP);
    Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
}
Also used : ReadListener(javax.servlet.ReadListener) HttpServlet(javax.servlet.http.HttpServlet) FuturePromise(org.eclipse.jetty.util.FuturePromise) HttpServletResponse(javax.servlet.http.HttpServletResponse) AsyncContext(javax.servlet.AsyncContext) IOException(java.io.IOException) InterruptedIOException(java.io.InterruptedIOException) DataFrame(org.eclipse.jetty.http2.frames.DataFrame) CountDownLatch(java.util.concurrent.CountDownLatch) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ServletInputStream(javax.servlet.ServletInputStream) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) ServletInputStream(javax.servlet.ServletInputStream) Stream(org.eclipse.jetty.http2.api.Stream) Session(org.eclipse.jetty.http2.api.Session) Test(org.junit.Test)

Example 88 with AsyncContext

use of javax.servlet.AsyncContext in project jetty.project by eclipse.

the class AbstractProxyServlet method onProxyResponseSuccess.

protected void onProxyResponseSuccess(HttpServletRequest clientRequest, HttpServletResponse proxyResponse, Response serverResponse) {
    if (_log.isDebugEnabled())
        _log.debug("{} proxying successful", getRequestId(clientRequest));
    AsyncContext asyncContext = clientRequest.getAsyncContext();
    asyncContext.complete();
}
Also used : AsyncContext(javax.servlet.AsyncContext)

Example 89 with AsyncContext

use of javax.servlet.AsyncContext in project jetty.project by eclipse.

the class AsyncMiddleManServlet method service.

@Override
protected void service(HttpServletRequest clientRequest, HttpServletResponse proxyResponse) throws ServletException, IOException {
    String rewrittenTarget = rewriteTarget(clientRequest);
    if (_log.isDebugEnabled()) {
        StringBuffer target = clientRequest.getRequestURL();
        if (clientRequest.getQueryString() != null)
            target.append("?").append(clientRequest.getQueryString());
        _log.debug("{} rewriting: {} -> {}", getRequestId(clientRequest), target, rewrittenTarget);
    }
    if (rewrittenTarget == null) {
        onProxyRewriteFailed(clientRequest, proxyResponse);
        return;
    }
    final Request proxyRequest = getHttpClient().newRequest(rewrittenTarget).method(clientRequest.getMethod()).version(HttpVersion.fromString(clientRequest.getProtocol()));
    copyRequestHeaders(clientRequest, proxyRequest);
    addProxyHeaders(clientRequest, proxyRequest);
    final AsyncContext asyncContext = clientRequest.startAsync();
    // We do not timeout the continuation, but the proxy request.
    asyncContext.setTimeout(0);
    proxyRequest.timeout(getTimeout(), TimeUnit.MILLISECONDS);
    // to allow optimization of the Content-Length header.
    if (hasContent(clientRequest)) {
        DeferredContentProvider provider = newProxyContentProvider(clientRequest, proxyResponse, proxyRequest);
        proxyRequest.content(provider);
        if (expects100Continue(clientRequest)) {
            proxyRequest.attribute(CLIENT_REQUEST_ATTRIBUTE, clientRequest);
            proxyRequest.attribute(CONTINUE_ACTION_ATTRIBUTE, (Runnable) () -> {
                try {
                    ServletInputStream input = clientRequest.getInputStream();
                    input.setReadListener(newProxyReadListener(clientRequest, proxyResponse, proxyRequest, provider));
                } catch (Throwable failure) {
                    onClientRequestFailure(clientRequest, proxyRequest, proxyResponse, failure);
                }
            });
            sendProxyRequest(clientRequest, proxyResponse, proxyRequest);
        } else {
            ServletInputStream input = clientRequest.getInputStream();
            input.setReadListener(newProxyReadListener(clientRequest, proxyResponse, proxyRequest, provider));
        }
    } else {
        sendProxyRequest(clientRequest, proxyResponse, proxyRequest);
    }
}
Also used : ServletInputStream(javax.servlet.ServletInputStream) DeferredContentProvider(org.eclipse.jetty.client.util.DeferredContentProvider) Request(org.eclipse.jetty.client.api.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) AsyncContext(javax.servlet.AsyncContext)

Example 90 with AsyncContext

use of javax.servlet.AsyncContext in project jetty.project by eclipse.

the class ConnectHandler method handleConnect.

/**
     * <p>Handles a CONNECT request.</p>
     * <p>CONNECT requests may have authentication headers such as {@code Proxy-Authorization}
     * that authenticate the client with the proxy.</p>
     *
     * @param baseRequest  Jetty-specific http request
     * @param request       the http request
     * @param response      the http response
     * @param serverAddress the remote server address in the form {@code host:port}
     */
protected void handleConnect(Request baseRequest, HttpServletRequest request, HttpServletResponse response, String serverAddress) {
    baseRequest.setHandled(true);
    try {
        boolean proceed = handleAuthentication(request, response, serverAddress);
        if (!proceed) {
            if (LOG.isDebugEnabled())
                LOG.debug("Missing proxy authentication");
            sendConnectResponse(request, response, HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED);
            return;
        }
        HostPort hostPort = new HostPort(serverAddress);
        String host = hostPort.getHost();
        int port = hostPort.getPort(80);
        if (!validateDestination(host, port)) {
            if (LOG.isDebugEnabled())
                LOG.debug("Destination {}:{} forbidden", host, port);
            sendConnectResponse(request, response, HttpServletResponse.SC_FORBIDDEN);
            return;
        }
        HttpTransport transport = baseRequest.getHttpChannel().getHttpTransport();
        // TODO Handle CONNECT over HTTP2!
        if (!(transport instanceof HttpConnection)) {
            if (LOG.isDebugEnabled())
                LOG.debug("CONNECT not supported for {}", transport);
            sendConnectResponse(request, response, HttpServletResponse.SC_FORBIDDEN);
            return;
        }
        AsyncContext asyncContext = request.startAsync();
        asyncContext.setTimeout(0);
        if (LOG.isDebugEnabled())
            LOG.debug("Connecting to {}:{}", host, port);
        connectToServer(request, host, port, new Promise<SocketChannel>() {

            @Override
            public void succeeded(SocketChannel channel) {
                ConnectContext connectContext = new ConnectContext(request, response, asyncContext, (HttpConnection) transport);
                if (channel.isConnected())
                    selector.accept(channel, connectContext);
                else
                    selector.connect(channel, connectContext);
            }

            @Override
            public void failed(Throwable x) {
                onConnectFailure(request, response, asyncContext, x);
            }
        });
    } catch (Exception x) {
        onConnectFailure(request, response, null, x);
    }
}
Also used : SocketChannel(java.nio.channels.SocketChannel) HttpConnection(org.eclipse.jetty.server.HttpConnection) HostPort(org.eclipse.jetty.util.HostPort) AsyncContext(javax.servlet.AsyncContext) EndPoint(org.eclipse.jetty.io.EndPoint) SelectChannelEndPoint(org.eclipse.jetty.io.SelectChannelEndPoint) SocketChannelEndPoint(org.eclipse.jetty.io.SocketChannelEndPoint) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) HttpTransport(org.eclipse.jetty.server.HttpTransport)

Aggregations

AsyncContext (javax.servlet.AsyncContext)120 IOException (java.io.IOException)61 HttpServletRequest (javax.servlet.http.HttpServletRequest)53 ServletException (javax.servlet.ServletException)52 HttpServletResponse (javax.servlet.http.HttpServletResponse)50 Test (org.junit.Test)43 CountDownLatch (java.util.concurrent.CountDownLatch)33 HttpServlet (javax.servlet.http.HttpServlet)32 InterruptedIOException (java.io.InterruptedIOException)24 ServletOutputStream (javax.servlet.ServletOutputStream)20 ReadListener (javax.servlet.ReadListener)19 ServletInputStream (javax.servlet.ServletInputStream)19 AsyncEvent (javax.servlet.AsyncEvent)18 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)18 AsyncListener (javax.servlet.AsyncListener)15 UncheckedIOException (java.io.UncheckedIOException)14 DeferredContentProvider (org.eclipse.jetty.client.util.DeferredContentProvider)14 Request (org.eclipse.jetty.server.Request)13 Matchers.containsString (org.hamcrest.Matchers.containsString)13 WriteListener (javax.servlet.WriteListener)11