Example usage for javax.servlet AsyncContext addListener

List of usage examples for javax.servlet AsyncContext addListener

Introduction

In this page you can find the example usage for javax.servlet AsyncContext addListener.

Prototype

public void addListener(AsyncListener listener);

Source Link

Document

Registers the given AsyncListener with the most recent asynchronous cycle that was started by a call to one of the ServletRequest#startAsync methods.

Usage

From source file:org.apache.vysper.xmpp.extension.xep0124.BoshBackedSessionContextTest.java

@Test
public void testAddRequest() {
    // addRequest
    HttpServletRequest httpServletRequest1 = mocksControl.createMock(HttpServletRequest.class);
    HttpServletRequest httpServletRequest2 = mocksControl.createMock(HttpServletRequest.class);
    AsyncContext asyncContext1 = mocksControl.createMock(AsyncContext.class);
    AsyncContext asyncContext2 = mocksControl.createMock(AsyncContext.class);
    BoshStanzaUtils boshStanzaUtils = mocksControl.createMock(BoshStanzaUtils.class);

    expect(httpServletRequest1.startAsync()).andReturn(asyncContext1).atLeastOnce();
    expect(httpServletRequest1.getAsyncContext()).andReturn(asyncContext1).atLeastOnce();

    expect(httpServletRequest2.startAsync()).andReturn(asyncContext2).atLeastOnce();
    expect(httpServletRequest2.getAsyncContext()).andReturn(asyncContext2).anyTimes();

    asyncContext1.setTimeout(anyLong());
    Capture<BoshRequest> br1 = new Capture<BoshRequest>();
    httpServletRequest1.setAttribute(eq(BOSH_REQUEST_ATTRIBUTE), EasyMock.<BoshRequest>capture(br1));

    asyncContext2.setTimeout(anyLong());
    Capture<BoshRequest> br2 = new Capture<BoshRequest>();
    httpServletRequest2.setAttribute(eq(BOSH_REQUEST_ATTRIBUTE), EasyMock.<BoshRequest>capture(br2));

    asyncContext1.addListener(EasyMock.<AsyncListener>anyObject());
    asyncContext2.addListener(EasyMock.<AsyncListener>anyObject());

    asyncContext1.dispatch();/*from w w  w.j a  va2  s. c o m*/
    expectLastCall().atLeastOnce();

    Stanza body = BoshStanzaUtils.EMPTY_BOSH_RESPONSE;

    // write0
    Capture<BoshResponse> captured = new Capture<BoshResponse>();
    httpServletRequest1.setAttribute(eq(BOSH_RESPONSE_ATTRIBUTE), EasyMock.<BoshResponse>capture(captured));

    mocksControl.replay();
    BoshBackedSessionContext boshBackedSessionContext = new BoshBackedSessionContext(serverRuntimeContext, null,
            inactivityChecker);

    boshBackedSessionContext.setHold(2);
    // consecutive writes with RID 1 and 2
    long maxRID = 2L;
    boshBackedSessionContext.insertRequest(new BoshRequest(httpServletRequest1, body, 1L));
    boshBackedSessionContext.insertRequest(new BoshRequest(httpServletRequest2, body, maxRID));
    boshBackedSessionContext.writeBoshResponse(body);
    mocksControl.verify();

    assertEquals(httpServletRequest1, br1.getValue().getHttpServletRequest());
    assertEquals(httpServletRequest2, br2.getValue().getHttpServletRequest());

    // expect ack for newest/largest RID
    final Stanza ackedResponse = BoshStanzaUtils.addAttribute(body, "ack", Long.toString(maxRID));
    assertEquals(new Renderer(ackedResponse).getComplete(), new String(captured.getValue().getContent()));
    assertEquals(BoshServlet.XML_CONTENT_TYPE, captured.getValue().getContentType());
}

From source file:org.apache.vysper.xmpp.extension.xep0124.BoshBackedSessionContextTest.java

@Test
public void testAddRequestWithDelayedResponses() {
    HttpServletRequest httpServletRequest = mocksControl.createMock(HttpServletRequest.class);
    AsyncContext asyncContext = mocksControl.createMock(AsyncContext.class);
    expect(httpServletRequest.startAsync()).andReturn(asyncContext).atLeastOnce();
    expect(httpServletRequest.getAsyncContext()).andReturn(asyncContext).atLeastOnce();
    asyncContext.setTimeout(anyLong());//  w  w  w  .j ava2s.c o m
    httpServletRequest.setAttribute(eq(BOSH_REQUEST_ATTRIBUTE), EasyMock.<BoshRequest>notNull());

    asyncContext.addListener(EasyMock.<AsyncListener>anyObject());

    asyncContext.dispatch();
    expectLastCall().atLeastOnce();

    Stanza body = BoshStanzaUtils.createBoshStanzaBuilder().startInnerElement("presence").endInnerElement()
            .build();

    Capture<BoshResponse> captured = new Capture<BoshResponse>();
    httpServletRequest.setAttribute(eq(BOSH_RESPONSE_ATTRIBUTE), EasyMock.<BoshResponse>capture(captured));

    mocksControl.replay();

    BoshBackedSessionContext boshBackedSessionContext = new BoshBackedSessionContext(serverRuntimeContext, null,
            inactivityChecker);
    boshBackedSessionContext.writeBoshResponse(body); // queued for merging
    boshBackedSessionContext.writeBoshResponse(body); // queued for merging
    boshBackedSessionContext.writeBoshResponse(body); // queued for merging
    boshBackedSessionContext.insertRequest(new BoshRequest(httpServletRequest, body, 1L));

    mocksControl.verify();

    final String mergedAllBodiesStanza = new String(captured.getValue().getContent());
    assertEquals(3, StringUtils.countMatches(mergedAllBodiesStanza, "<presence"));
}

From source file:org.springframework.http.server.reactive.ServletHttpHandlerAdapter.java

@Override
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
    if (DispatcherType.ASYNC.equals(request.getDispatcherType())) {
        Throwable ex = (Throwable) request.getAttribute(WRITE_ERROR_ATTRIBUTE_NAME);
        throw new ServletException("Write publisher error", ex);
    }//from  ww w .j  a v  a 2s  . c o  m

    // Start async before Read/WriteListener registration
    AsyncContext asyncContext = request.startAsync();
    asyncContext.setTimeout(-1);

    ServerHttpRequest httpRequest = createRequest(((HttpServletRequest) request), asyncContext);
    ServerHttpResponse httpResponse = createResponse(((HttpServletResponse) response), asyncContext);

    if (HttpMethod.HEAD.equals(httpRequest.getMethod())) {
        httpResponse = new HttpHeadResponseDecorator(httpResponse);
    }

    AtomicBoolean isCompleted = new AtomicBoolean();
    HandlerResultAsyncListener listener = new HandlerResultAsyncListener(isCompleted);
    asyncContext.addListener(listener);

    HandlerResultSubscriber subscriber = new HandlerResultSubscriber(asyncContext, isCompleted);
    this.httpHandler.handle(httpRequest, httpResponse).subscribe(subscriber);
}

From source file:org.springframework.http.server.reactive.ServletServerHttpRequest.java

public ServletServerHttpRequest(HttpServletRequest request, AsyncContext asyncContext, String servletPath,
        DataBufferFactory bufferFactory, int bufferSize) throws IOException {

    super(initUri(request), request.getContextPath() + servletPath, initHeaders(request));

    Assert.notNull(bufferFactory, "'bufferFactory' must not be null");
    Assert.isTrue(bufferSize > 0, "'bufferSize' must be higher than 0");

    this.request = request;
    this.bufferFactory = bufferFactory;
    this.buffer = new byte[bufferSize];

    asyncContext.addListener(new RequestAsyncListener());

    // Tomcat expects ReadListener registration on initial thread
    ServletInputStream inputStream = request.getInputStream();
    this.bodyPublisher = new RequestBodyPublisher(inputStream);
    this.bodyPublisher.registerReadListener();
}

From source file:org.synchronoss.cloud.nio.multipart.example.web.MultipartController.java

/**
 * <p> This is an example how the NIO Parser can be used in a plain Servlet 3.1 fashion.
 *
 * @param request The {@code HttpServletRequest}
 * @throws IOException if an IO exception happens
 *///  ww w .  jav  a 2 s.  c  om
@RequestMapping(value = "/nio/multipart", method = RequestMethod.POST)
public @ResponseBody void nioMultipart(final HttpServletRequest request) throws IOException {

    assertRequestIsMultipart(request);

    final VerificationItems verificationItems = new VerificationItems();
    final AsyncContext asyncContext = switchRequestToAsyncIfNeeded(request);
    final ServletInputStream inputStream = request.getInputStream();
    final AtomicInteger synchronizer = new AtomicInteger(0);

    final NioMultipartParserListener listener = new NioMultipartParserListener() {

        Metadata metadata;

        @Override
        public void onPartFinished(final StreamStorage partBodyStreamStorage,
                final Map<String, List<String>> headersFromPart) {
            if (log.isInfoEnabled())
                log.info("PARSER LISTENER - onPartFinished");
            final String fieldName = MultipartUtils.getFieldName(headersFromPart);
            final ChecksumStreamStorage checksumPartStreams = getChecksumStreamStorageOrThrow(
                    partBodyStreamStorage);
            if (METADATA_FIELD_NAME.equals(fieldName)) {
                metadata = unmarshalMetadataOrThrow(checksumPartStreams);
            } else {
                VerificationItem verificationItem = buildVerificationItem(checksumPartStreams, fieldName);
                verificationItems.getVerificationItems().add(verificationItem);
            }
        }

        @Override
        public void onNestedPartStarted(final Map<String, List<String>> headersFromParentPart) {
            if (log.isInfoEnabled())
                log.info("PARSER LISTENER - onNestedPartStarted");
        }

        @Override
        public void onNestedPartFinished() {
            if (log.isInfoEnabled())
                log.info("PARSER LISTENER - onNestedPartFinished");
        }

        @Override
        public void onFormFieldPartFinished(String fieldName, String fieldValue,
                Map<String, List<String>> headersFromPart) {
            if (log.isInfoEnabled())
                log.info("PARSER LISTENER - onFormFieldPartFinished");
            if (METADATA_FIELD_NAME.equals(fieldName)) {
                metadata = unmarshalMetadataOrThrow(fieldValue);
            }
        }

        @Override
        public void onAllPartsFinished() {
            if (log.isInfoEnabled())
                log.info("PARSER LISTENER - onAllPartsFinished");
            processVerificationItems(verificationItems, metadata, true);
            sendResponseOrSkip(synchronizer, asyncContext, verificationItems);
        }

        @Override
        public void onError(String message, Throwable cause) {
            // Probably invalid data...
            throw new IllegalStateException("Encountered an error during the parsing: " + message, cause);
        }

        synchronized Metadata unmarshalMetadataOrThrow(final String json) {
            if (metadata != null) {
                throw new IllegalStateException("Found two metadata fields");
            }
            return unmarshalMetadata(json);
        }

        synchronized Metadata unmarshalMetadataOrThrow(final ChecksumStreamStorage checksumPartStreams) {
            if (metadata != null) {
                throw new IllegalStateException("Found more than one metadata fields");
            }
            return unmarshalMetadata(checksumPartStreams.getInputStream());
        }

    };

    final MultipartContext ctx = getMultipartContext(request);
    final NioMultipartParser parser = multipart(ctx)
            .usePartBodyStreamStorageFactory(partBodyStreamStorageFactory).forNIO(listener);

    // Add a listener to ensure the parser is closed.
    asyncContext.addListener(new AsyncListener() {
        @Override
        public void onComplete(AsyncEvent event) throws IOException {
            parser.close();
        }

        @Override
        public void onTimeout(AsyncEvent event) throws IOException {
            parser.close();
        }

        @Override
        public void onError(AsyncEvent event) throws IOException {
            parser.close();
        }

        @Override
        public void onStartAsync(AsyncEvent event) throws IOException {
            // Nothing to do.
        }
    });

    inputStream.setReadListener(new ReadListener() {

        @Override
        public void onDataAvailable() throws IOException {
            if (log.isInfoEnabled())
                log.info("NIO READ LISTENER - onDataAvailable");
            int bytesRead;
            byte bytes[] = new byte[2048];
            while (inputStream.isReady() && (bytesRead = inputStream.read(bytes)) != -1) {
                parser.write(bytes, 0, bytesRead);
            }
            if (log.isInfoEnabled())
                log.info("Epilogue bytes...");
        }

        @Override
        public void onAllDataRead() throws IOException {
            if (log.isInfoEnabled())
                log.info("NIO READ LISTENER - onAllDataRead");
            sendResponseOrSkip(synchronizer, asyncContext, verificationItems);
        }

        @Override
        public void onError(Throwable throwable) {
            log.error("onError", throwable);
            IOUtils.closeQuietly(parser);
            sendErrorOrSkip(synchronizer, asyncContext, "Unknown error");
        }
    });

}