Search in sources :

Example 46 with AsyncContext

use of javax.servlet.AsyncContext in project platformlayer by platformlayer.

the class RestLoginServlet method processRequest.

protected void processRequest(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse, final AuthenticateRequest request, boolean checkLimit) throws IOException {
    try {
        if (request.auth == null) {
            httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        String username = getUsername(request);
        if (Strings.isNullOrEmpty(username)) {
            httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        if (checkLimit && limits.isOverLimit(httpRequest, username)) {
            final AsyncContext asyncContext = httpRequest.startAsync(httpRequest, httpResponse);
            asyncExecutor.schedule(LoginService.OVER_LIMIT_DELAY, new Runnable() {

                @Override
                public void run() {
                    try {
                        processRequest(httpRequest, httpResponse, request, false);
                        asyncContext.complete();
                    } catch (Exception e) {
                        log.error("Unexpected error caught in async task", e);
                    }
                }
            });
            return;
        }
        AuthenticateResponse authenticateResponse = loginService.authenticate(httpRequest, request);
        if (authenticateResponse == null) {
            limits.recordFail(httpRequest, username);
            httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        marshaller.write(httpRequest, httpResponse, authenticateResponse);
    } catch (WebApplicationException e) {
        log.info("Returning exception from servlet", e);
        httpResponse.sendError(e.getResponse().getStatus());
    } catch (Exception e) {
        log.warn("Unexpected error in servlet", e);
        httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}
Also used : AuthenticateResponse(org.platformlayer.auth.model.AuthenticateResponse) WebApplicationException(javax.ws.rs.WebApplicationException) AsyncContext(javax.servlet.AsyncContext) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) WebApplicationException(javax.ws.rs.WebApplicationException)

Example 47 with AsyncContext

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

the class ServerHttpRequestTests method createHttpRequest.

private ServerHttpRequest createHttpRequest(String path) throws Exception {
    HttpServletRequest request = new MockHttpServletRequest("GET", path) {

        @Override
        public ServletInputStream getInputStream() {
            return new TestServletInputStream();
        }
    };
    AsyncContext asyncContext = new MockAsyncContext(request, new MockHttpServletResponse());
    return new ServletServerHttpRequest(request, asyncContext, new DefaultDataBufferFactory(), 1024);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) MockHttpServletRequest(org.springframework.mock.web.test.MockHttpServletRequest) MockHttpServletRequest(org.springframework.mock.web.test.MockHttpServletRequest) DefaultDataBufferFactory(org.springframework.core.io.buffer.DefaultDataBufferFactory) MockAsyncContext(org.springframework.mock.web.test.MockAsyncContext) MockAsyncContext(org.springframework.mock.web.test.MockAsyncContext) AsyncContext(javax.servlet.AsyncContext) MockHttpServletResponse(org.springframework.mock.web.test.MockHttpServletResponse)

Example 48 with AsyncContext

use of javax.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());
    for (Map.Entry<String, List<String>> entry : upgradeResponse.getHeaders().entrySet()) {
        response.addHeader(entry.getKey(), Utils.getHeaderFromList(entry.getValue()));
    }
    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) List(java.util.List) AsyncContext(javax.servlet.AsyncContext) Map(java.util.Map) Writer(org.glassfish.tyrus.spi.Writer)

Example 49 with AsyncContext

use of javax.servlet.AsyncContext in project rest.li by linkedin.

the class AbstractAsyncR2Servlet method service.

@Override
public void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
    RequestContext requestContext = readRequestContext(req);
    RestRequest restRequest;
    try {
        restRequest = readFromServletRequest(req);
    } catch (URISyntaxException e) {
        writeToServletError(resp, RestStatus.BAD_REQUEST, e.toString());
        return;
    }
    final AsyncContext ctx = req.startAsync(req, resp);
    ctx.setTimeout(_timeout);
    ctx.addListener(new AsyncListener() {

        @Override
        public void onTimeout(AsyncEvent event) throws IOException {
            AsyncContext ctx = event.getAsyncContext();
            writeToServletError((HttpServletResponse) ctx.getResponse(), RestStatus.INTERNAL_SERVER_ERROR, "Server Timeout");
            ctx.complete();
        }

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

        @Override
        public void onError(AsyncEvent event) throws IOException {
            writeToServletError((HttpServletResponse) event.getSuppliedResponse(), RestStatus.INTERNAL_SERVER_ERROR, "Server Error");
            ctx.complete();
        }

        @Override
        public void onComplete(AsyncEvent event) throws IOException {
            Object exception = req.getAttribute(TRANSPORT_CALLBACK_IOEXCEPTION);
            if (exception != null)
                throw new IOException((IOException) exception);
        }
    });
    TransportCallback<RestResponse> callback = new TransportCallback<RestResponse>() {

        @Override
        public void onResponse(final TransportResponse<RestResponse> response) {
            // TransportCallback is usually invoked by non-servlet threads; hence we cannot assume that it's ok to
            // do blocking IO there. As a result, we should use AsyncContext.start() to do blocking IO using the
            // container/servlet threads. This still maintains the advantage of Async, meaning servlet thread is not
            // blocking-wait when the response is not ready.
            ctx.start(new Runnable() {

                @Override
                public void run() {
                    try {
                        writeToServletResponse(response, (HttpServletResponse) ctx.getResponse());
                    } catch (IOException e) {
                        req.setAttribute(TRANSPORT_CALLBACK_IOEXCEPTION, e);
                    } finally {
                        ctx.complete();
                    }
                }
            });
        }
    };
    getDispatcher().handleRequest(restRequest, requestContext, callback);
}
Also used : TransportCallback(com.linkedin.r2.transport.common.bridge.common.TransportCallback) RestResponse(com.linkedin.r2.message.rest.RestResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) AsyncContext(javax.servlet.AsyncContext) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) AsyncEvent(javax.servlet.AsyncEvent) TransportResponse(com.linkedin.r2.transport.common.bridge.common.TransportResponse) RestRequest(com.linkedin.r2.message.rest.RestRequest) AsyncListener(javax.servlet.AsyncListener) RequestContext(com.linkedin.r2.message.RequestContext)

Example 50 with AsyncContext

use of javax.servlet.AsyncContext in project JessMA by ldcsaa.

the class ActionSupport method startAsync.

/** 启动异步任务
	 * 
	 *  @param task			: 异步任务对象
	 *  @param timeout		: 任务超时值(毫秒),应用框架会以 {@linkplain ActionSupport#getAsyncTimeoutResult() 
	 *  					  getAsyncTimeoutResult()} 得到的值作为 Action 的最终处理结果,并立刻返回到客户端。此时,
	 *  					  {@linkplain AsyncTask} 的 {@linkplain AsyncTask#run() run()} 方法仍然继续执行,但会忽略其结果。
	 *  					  <ul>
	 *  						<li><b>小于 0:</b>使用 Web 容器的默认超时值</li>
	 *  						<li><b>等于 0:</b>永不超时</li>
	 *  						<li><b>大于 0:</b>使用设定的超时值</li>
	 *  					  </ul>
	 *  @param launcher		: 异步任务启动器,如果为 <b>null</b> 则使用容器内置的线程池启动异步任务。
	 *  @param listeners	: 异步任务监听器,用于监听异步任务执行状态。
	 *  @since				  Servlet 3.0
	 */
protected void startAsync(AsyncTask task, long timeout, AsyncTaskLauncher launcher, AsyncListener... listeners) {
    HttpServletRequest request = getRequest();
    HttpServletResponse response = getResponse();
    if (!request.isAsyncSupported())
        throw new UnsupportedOperationException("async operation is not supported by current request");
    checkTaskType(task);
    AsyncContext ctx = request.startAsync(request, response);
    if (timeout >= 0)
        ctx.setTimeout(timeout);
    if (listeners != null) {
        for (AsyncListener listener : listeners) ctx.addListener(listener, request, response);
    }
    Runnable runner = new AsyncTaskRunner(ctx, task);
    if (launcher == null)
        ctx.start(runner);
    else
        launcher.start(runner);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) AsyncListener(javax.servlet.AsyncListener) HttpServletResponse(javax.servlet.http.HttpServletResponse) AsyncContext(javax.servlet.AsyncContext)

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