Search in sources :

Example 6 with AsyncContext

use of jakarta.servlet.AsyncContext in project tomcat by apache.

the class Async0 method service.

@Override
protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
    if (Boolean.TRUE.equals(req.getAttribute("dispatch"))) {
        log.info("Received dispatch, completing on the worker thread.");
        log.info("After complete called started:" + req.isAsyncStarted());
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
        resp.getWriter().write("Async dispatch worked: " + sdf.format(date) + "\n");
    } else {
        resp.setContentType("text/plain");
        final AsyncContext actx = req.startAsync();
        actx.setTimeout(Long.MAX_VALUE);
        Runnable run = new Runnable() {

            @Override
            public void run() {
                try {
                    req.setAttribute("dispatch", Boolean.TRUE);
                    Thread.currentThread().setName("Async0-Thread");
                    log.info("Putting AsyncThread to sleep");
                    Thread.sleep(2 * 1000);
                    log.info("Dispatching");
                    actx.dispatch();
                } catch (InterruptedException x) {
                    log.error("Async1", x);
                } catch (IllegalStateException x) {
                    log.error("Async1", x);
                }
            }
        };
        Thread t = new Thread(run);
        t.start();
    }
}
Also used : AsyncContext(jakarta.servlet.AsyncContext) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date)

Example 7 with AsyncContext

use of jakarta.servlet.AsyncContext in project tomcat by apache.

the class NumberWriter method doGet.

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("text/plain");
    resp.setCharacterEncoding("UTF-8");
    // Non-blocking IO requires async
    AsyncContext ac = req.startAsync();
    // Use a single listener for read and write. Listeners often need to
    // share state to coordinate reads and writes and this is much easier as
    // a single object.
    @SuppressWarnings("unused") NumberWriterListener listener = new NumberWriterListener(ac, req.getInputStream(), resp.getOutputStream());
}
Also used : AsyncContext(jakarta.servlet.AsyncContext)

Example 8 with AsyncContext

use of jakarta.servlet.AsyncContext in project tomcat by apache.

the class TestNonBlockingAPI method testNonBlockingWriteInternal.

private void testNonBlockingWriteInternal(boolean keepAlive) throws Exception {
    AtomicBoolean asyncContextIsComplete = new AtomicBoolean(false);
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    NBWriteServlet servlet = new NBWriteServlet(asyncContextIsComplete);
    String servletName = NBWriteServlet.class.getName();
    Tomcat.addServlet(ctx, servletName, servlet);
    ctx.addServletMappingDecoded("/", servletName);
    // Note: Low values of socket.txBufSize can trigger very poor
    // performance. Set it just low enough to ensure that the
    // non-blocking write servlet will see isReady() == false
    Assert.assertTrue(tomcat.getConnector().setProperty("socket.txBufSize", "1048576"));
    tomcat.start();
    SocketFactory factory = SocketFactory.getDefault();
    Socket s = factory.createSocket("localhost", getPort());
    InputStream is = s.getInputStream();
    byte[] buffer = new byte[8192];
    ByteChunk result = new ByteChunk();
    OutputStream os = s.getOutputStream();
    if (keepAlive) {
        os.write(("OPTIONS * HTTP/1.1\r\n" + "Host: localhost:" + getPort() + "\r\n" + "\r\n").getBytes(StandardCharsets.ISO_8859_1));
        os.flush();
        // Make sure the entire response has been read.
        int read = is.read(buffer);
        // The response should end with CRLFCRLF
        Assert.assertEquals(buffer[read - 4], '\r');
        Assert.assertEquals(buffer[read - 3], '\n');
        Assert.assertEquals(buffer[read - 2], '\r');
        Assert.assertEquals(buffer[read - 1], '\n');
    }
    os.write(("GET / HTTP/1.1\r\n" + "Host: localhost:" + getPort() + "\r\n" + "Connection: close\r\n" + "\r\n").getBytes(StandardCharsets.ISO_8859_1));
    os.flush();
    int read = 0;
    int readSinceLastPause = 0;
    while (read != -1) {
        read = is.read(buffer);
        if (readSinceLastPause == 0) {
            log.info("Reading data");
        }
        if (read > 0) {
            result.append(buffer, 0, read);
        }
        readSinceLastPause += read;
        if (readSinceLastPause > WRITE_SIZE / 16) {
            log.info("Read " + readSinceLastPause + " bytes, pause 500ms");
            readSinceLastPause = 0;
            Thread.sleep(500);
        }
    }
    os.close();
    is.close();
    s.close();
    // Validate the result.
    // Response line
    String resultString = result.toString();
    log.info("Client read " + resultString.length() + " bytes");
    int lineStart = 0;
    int lineEnd = resultString.indexOf('\n', 0);
    String line = resultString.substring(lineStart, lineEnd + 1);
    Assert.assertEquals("HTTP/1.1 200 \r\n", line);
    // Check headers - looking to see if response is chunked (it should be)
    boolean chunked = false;
    while (line.length() > 2) {
        lineStart = lineEnd + 1;
        lineEnd = resultString.indexOf('\n', lineStart);
        line = resultString.substring(lineStart, lineEnd + 1);
        if (line.startsWith("Transfer-Encoding:")) {
            Assert.assertEquals("Transfer-Encoding: chunked\r\n", line);
            chunked = true;
        }
    }
    Assert.assertTrue(chunked);
    // Now check body size
    int totalBodyRead = 0;
    int chunkSize = -1;
    while (chunkSize != 0) {
        // Chunk size in hex
        lineStart = lineEnd + 1;
        lineEnd = resultString.indexOf('\n', lineStart);
        line = resultString.substring(lineStart, lineEnd + 1);
        Assert.assertTrue(line.endsWith("\r\n"));
        line = line.substring(0, line.length() - 2);
        log.info("[" + line + "]");
        chunkSize = Integer.parseInt(line, 16);
        // Read the chunk
        lineStart = lineEnd + 1;
        lineEnd = resultString.indexOf('\n', lineStart);
        log.info("Start : " + lineStart + ", End: " + lineEnd);
        if (lineEnd > lineStart) {
            line = resultString.substring(lineStart, lineEnd + 1);
        } else {
            line = resultString.substring(lineStart);
        }
        if (line.length() > 40) {
            log.info(line.substring(0, 32));
        } else {
            log.info(line);
        }
        if (chunkSize + 2 != line.length()) {
            log.error("Chunk wrong length. Was " + line.length() + " Expected " + (chunkSize + 2));
            byte[] resultBytes = resultString.getBytes();
            // Find error
            boolean found = false;
            for (int i = totalBodyRead; i < (totalBodyRead + line.length()); i++) {
                if (DATA[i] != resultBytes[lineStart + i - totalBodyRead]) {
                    int dataStart = i - 64;
                    if (dataStart < 0) {
                        dataStart = 0;
                    }
                    int dataEnd = i + 64;
                    if (dataEnd > DATA.length) {
                        dataEnd = DATA.length;
                    }
                    int resultStart = lineStart + i - totalBodyRead - 64;
                    if (resultStart < 0) {
                        resultStart = 0;
                    }
                    int resultEnd = lineStart + i - totalBodyRead + 64;
                    if (resultEnd > resultString.length()) {
                        resultEnd = resultString.length();
                    }
                    log.error("Mis-match tx: " + new String(DATA, dataStart, dataEnd - dataStart));
                    log.error("Mis-match rx: " + resultString.substring(resultStart, resultEnd));
                    found = true;
                    break;
                }
            }
            if (!found) {
                log.error("No mismatch. Data truncated");
            }
        }
        Assert.assertTrue(line, line.endsWith("\r\n"));
        Assert.assertEquals(chunkSize + 2, line.length());
        totalBodyRead += chunkSize;
    }
    Assert.assertEquals(WRITE_SIZE, totalBodyRead);
    Assert.assertTrue("AsyncContext should have been completed.", asyncContextIsComplete.get());
}
Also used : Context(org.apache.catalina.Context) AsyncContext(jakarta.servlet.AsyncContext) Tomcat(org.apache.catalina.startup.Tomcat) ByteChunk(org.apache.tomcat.util.buf.ByteChunk) SocketFactory(javax.net.SocketFactory) ServletInputStream(jakarta.servlet.ServletInputStream) InputStream(java.io.InputStream) ServletOutputStream(jakarta.servlet.ServletOutputStream) OutputStream(java.io.OutputStream) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Socket(java.net.Socket)

Example 9 with AsyncContext

use of jakarta.servlet.AsyncContext in project spring-framework by spring-projects.

the class WebLogicRequestUpgradeStrategy method handleSuccess.

@Override
protected void handleSuccess(HttpServletRequest request, HttpServletResponse response, UpgradeInfo upgradeInfo, TyrusUpgradeResponse upgradeResponse) throws IOException, ServletException {
    response.setStatus(upgradeResponse.getStatus());
    upgradeResponse.getHeaders().forEach((key, value) -> response.addHeader(key, Utils.getHeaderFromList(value)));
    AsyncContext asyncContext = request.startAsync();
    asyncContext.setTimeout(-1L);
    Object nativeRequest = getNativeRequest(request);
    BeanWrapper beanWrapper = new BeanWrapperImpl(nativeRequest);
    Object httpSocket = beanWrapper.getPropertyValue("connection.connectionHandler.rawConnection");
    Object webSocket = webSocketHelper.newInstance(request, httpSocket);
    webSocketHelper.upgrade(webSocket, httpSocket, request.getServletContext());
    response.flushBuffer();
    boolean isProtected = request.getUserPrincipal() != null;
    Writer servletWriter = servletWriterHelper.newInstance(webSocket, isProtected);
    Connection connection = upgradeInfo.createConnection(servletWriter, noOpCloseListener);
    new BeanWrapperImpl(webSocket).setPropertyValue("connection", connection);
    new BeanWrapperImpl(servletWriter).setPropertyValue("connection", connection);
    webSocketHelper.registerForReadEvent(webSocket);
}
Also used : BeanWrapper(org.springframework.beans.BeanWrapper) BeanWrapperImpl(org.springframework.beans.BeanWrapperImpl) Connection(org.glassfish.tyrus.spi.Connection) AsyncContext(jakarta.servlet.AsyncContext) Writer(org.glassfish.tyrus.spi.Writer)

Example 10 with AsyncContext

use of jakarta.servlet.AsyncContext in project atmosphere by Atmosphere.

the class AtmosphereRequestImpl method startAsync.

@Override
public AsyncContext startAsync(ServletRequest request, ServletResponse response) {
    AsyncContext ac;
    if (AtmosphereResource.TRANSPORT.WEBSOCKET == resource().transport()) {
        noopsAsyncContextStarted = true;
        ac = new NoOpsAsyncContext(request, response);
    } else {
        ac = b.request.startAsync(request, response);
    }
    return isCompletionAware() ? new CompletionAwareAsyncContext(ac, (CompletionAware) resource().getResponse()) : ac;
}
Also used : AsyncContext(jakarta.servlet.AsyncContext)

Aggregations

AsyncContext (jakarta.servlet.AsyncContext)19 Test (org.junit.jupiter.api.Test)3 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)3 DelegatingSecurityContextRunnable (org.springframework.security.concurrent.DelegatingSecurityContextRunnable)3 SecurityContext (org.springframework.security.core.context.SecurityContext)3 HttpServletResponse (jakarta.servlet.http.HttpServletResponse)2 SimpleDateFormat (java.text.SimpleDateFormat)2 Date (java.util.Date)2 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)2 Context (org.apache.catalina.Context)2 Tomcat (org.apache.catalina.startup.Tomcat)2 AsyncListener (jakarta.servlet.AsyncListener)1 ServletException (jakarta.servlet.ServletException)1 ServletInputStream (jakarta.servlet.ServletInputStream)1 ServletOutputStream (jakarta.servlet.ServletOutputStream)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1 Socket (java.net.Socket)1 URI (java.net.URI)1