Java Code Examples for javax.servlet.http.httpservletrequest#startAsync()

The following examples show how to use javax.servlet.http.httpservletrequest#startAsync() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WebLogicRequestUpgradeStrategy.java    From spring-analysis-note with MIT License 8 votes vote down vote up
@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);
}
 
Example 2
Source File: TestAsyncContextImpl.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest request,
        HttpServletResponse response)
        throws ServletException, IOException {

    final AsyncContext asyncContext =
        request.startAsync(request, response);

    asyncContext.addListener(new TrackingListener(false, false, null));

    asyncContext.start(new Runnable() {

        @Override
        public void run() {
            try {
                Thread.sleep(THREAD_SLEEP_TIME);
                TestAsyncContextImpl.track("Runnable-");
                asyncContext.complete();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}
 
Example 3
Source File: ByteCounter.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
protected void doPost(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")
    CounterListener listener = new CounterListener(
            ac, req.getInputStream(), resp.getOutputStream());
}
 
Example 4
Source File: ByteCounter.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
protected void doPost(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")
    CounterListener listener = new CounterListener(
            ac, req.getInputStream(), resp.getOutputStream());
}
 
Example 5
Source File: NumberWriter.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@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());

}
 
Example 6
Source File: HttpRequestDispatch.java    From vespa with Apache License 2.0 6 votes vote down vote up
public HttpRequestDispatch(JDiscContext jDiscContext,
                           AccessLogEntry accessLogEntry,
                           Context metricContext,
                           HttpServletRequest servletRequest,
                           HttpServletResponse servletResponse) throws IOException {
    this.jDiscContext = jDiscContext;

    requestHandler = newRequestHandler(jDiscContext, accessLogEntry, servletRequest);

    this.jettyRequest = (Request) servletRequest;
    this.metricReporter = new MetricReporter(jDiscContext.metric, metricContext, jettyRequest.getTimeStamp());
    this.servletResponseController = new ServletResponseController(
            servletRequest,
            servletResponse,
            jDiscContext.janitor,
            metricReporter,
            jDiscContext.developerMode());
    markConnectionAsNonPersistentIfThresholdReached(servletRequest);
    this.async = servletRequest.startAsync();
    async.setTimeout(0);
    metricReporter.uriLength(jettyRequest.getOriginalURI().length());
}
 
Example 7
Source File: TestAsyncContextImpl.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req,
        final HttpServletResponse resp)
        throws ServletException, IOException {
    final AsyncContext ctx = req.startAsync();
    ctx.start(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(THREAD_SLEEP_TIME);
                resp.setHeader("A", "xyz");
                resp.setContentType("text/plain");
                resp.setContentLength("OK".getBytes().length);
                resp.getWriter().print("OK");
                ctx.complete();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}
 
Example 8
Source File: ProxyServlet.java    From logbook-kai with MIT License 6 votes vote down vote up
@Override
protected void service(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    URI rewrittenURI = this.rewriteURI(request);

    if (this._isDebugEnabled) {
        StringBuffer uri = request.getRequestURL();
        if (request.getQueryString() != null)
            uri.append("?").append(request.getQueryString());
        this._log.debug("{} rewriting: {} -> {}", getRequestId(request), uri, rewrittenURI);
    }

    if (rewrittenURI == null) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    AsyncContext asyncContext = request.startAsync();
    // We do not timeout the continuation, but the proxy request
    asyncContext.setTimeout(0);
    request.setAttribute(ASYNC_CONTEXT, asyncContext);

    ProxyRequestHandler proxyRequestHandler = new ProxyRequestHandler(request, response, rewrittenURI);
    proxyRequestHandler.send();
}
 
Example 9
Source File: TestNonBlockingAPI.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean notify = Boolean.parseBoolean(request.getParameter("notify"));
    AsyncContext ctx = request.startAsync();
    ctx.setTimeout(1000);
    if (!notify) {
        emitters.add(new Emitter(ctx));
        latch.countDown();
    } else {
        for (Emitter e : emitters) {
            e.emit();
        }
        response.getOutputStream().println("OK");
        response.getOutputStream().flush();
        ctx.complete();
    }
}
 
Example 10
Source File: ServletServerHttpAsyncRequestControl.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public void start(long timeout) {
	Assert.state(!isCompleted(), "Async processing has already completed");
	if (isStarted()) {
		return;
	}

	HttpServletRequest servletRequest = this.request.getServletRequest();
	HttpServletResponse servletResponse = this.response.getServletResponse();

	this.asyncContext = servletRequest.startAsync(servletRequest, servletResponse);
	this.asyncContext.addListener(this);

	if (timeout != NO_TIMEOUT_VALUE) {
		this.asyncContext.setTimeout(timeout);
	}
}
 
Example 11
Source File: SampleResource.java    From wingtips with Apache License 2.0 6 votes vote down vote up
protected void doGetInternal(HttpServletRequest request, HttpServletResponse response) {
    logger.info("Async endpoint hit");
    AsyncContext asyncContext = request.startAsync(request, response);

    executor.execute(runnableWithTracing(() -> {
        try {
            logger.info("Async endpoint async logic");
            sleepThread(SLEEP_TIME_MILLIS);
            asyncContext.getResponse().getWriter().print(ASYNC_RESULT);
            asyncContext.complete();
        }
        catch (IOException e) {
            throw new RuntimeException(e);
        }
    }));
}
 
Example 12
Source File: TestHttp11Processor.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (bug55772IsSecondRequest) {
        Cookie[] cookies = req.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : req.getCookies()) {
                if (cookie.getName().equalsIgnoreCase("something.that.should.not.leak")) {
                    bug55772RequestStateLeaked = true;
                }
            }
        }
        bug55772Latch3.countDown();
    } else {
        req.getCookies(); // We have to do this so Tomcat will actually parse the cookies from the request
    }

    req.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", Boolean.TRUE);
    AsyncContext asyncContext = req.startAsync();
    asyncContext.setTimeout(5000);

    bug55772Latch1.countDown();

    PrintWriter writer = asyncContext.getResponse().getWriter();
    writer.print('\n');
    writer.flush();

    bug55772Latch2.countDown();
}
 
Example 13
Source File: TestAsyncContextImpl.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    TestAsyncContextImpl.track("DispatchingServletGet-");
    resp.flushBuffer();

    final boolean first = TrackingServlet.first;
    TrackingServlet.first = false;

    final AsyncContext ctxt = req.startAsync();
    TrackingListener listener = new TrackingListener(false, true, null);
    ctxt.addListener(listener);
    ctxt.setTimeout(3000);

    Runnable run = new Runnable() {
        @Override
        public void run() {
            if (first) {
                ctxt.dispatch("/stage1");
            } else {
                ctxt.dispatch("/stage2");
            }
        }
    };
    if ("y".equals(req.getParameter("useThread"))) {
        new Thread(run).start();
    } else {
        run.run();
    }
}
 
Example 14
Source File: AsyncDispatchServlet.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    final AsyncContext ac = req.startAsync(req, new TestAsyncRespWrapper(resp));
    ac.start(new Runnable() {
        @Override
        public void run() {
            ac.dispatch("/message");
        }
    });
}
 
Example 15
Source File: Plaintext.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
		IOException {
	final AsyncContext async = req.startAsync();
	final ServletOutputStream out = resp.getOutputStream();
	LOGGER.debug("plaintext async start");
	resp.setContentType(Helper.MEDIATYPE_TEXT_PLAIN);

	out.setWriteListener(new WriteListener() {
		@Override
		public void onWritePossible() throws IOException {
			byte[] buffer = new byte[32];
			ByteArrayInputStream is = new ByteArrayInputStream(Helper.CONTENT);

			while (out.isReady()) {
				int len = is.read(buffer);

				if (len < 0) {
					async.complete();
					LOGGER.debug("plaintext async end");
					return;
				}
				out.write(buffer, 0, len);
			}
		}

		@Override
		public void onError(Throwable t) {
			LOGGER.error("plaintext async error", t);
			async.complete();
		}
	});
}
 
Example 16
Source File: KonduitServlet.java    From konduit-serving with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);
    AsyncContext aCtx = req.startAsync(req, resp);
    addLoggingListenerToCtx(aCtx);

    ServletInputStream inputStream = req.getInputStream();
    byte[] streamContent = IOUtils.toByteArray(inputStream);
    inputStream.close();

    String reqUrl = req.getRequestURL().toString();
    String baseUrl = reqUrl.replace(req.getContextPath() + "//", req.getContextPath() + "/");
    String url = baseUrl.replace(req.getContextPath(), "")
            .replace(String.valueOf(req.getLocalPort()),
                    String.valueOf(vertxConfig.getInteger("httpPort")));


    HttpClientRequest request = httpClient.request(HttpMethod.GET, url, httpClientResponse -> {
        httpClientResponse.exceptionHandler(exception -> {
            log("Error occurred", exception.getCause());
        });

        httpClientResponse.bodyHandler(body -> {
            try {
                final PrintWriter writer = aCtx.getResponse().getWriter();
                writer.write(body.toString());
                writer.flush();
                writer.close();
                aCtx.complete();
            } catch (IOException e) {
                log("Error occurred", e);
            }
        });
    });

    request.putHeader("Content-Type", req.getHeader("Content-Type"));
    request.setChunked(false);
    request.end(Buffer.buffer(streamContent));
}
 
Example 17
Source File: TestAsyncContextImpl.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    resp.setContentType("text/plain;UTF-8");

    asyncContext = req.startAsync();
    // This will commit the response
    asyncContext.complete();
}
 
Example 18
Source File: TestAsyncContextImpl.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    AsyncContext actxt = req.startAsync();
    resp.setStatus(status);
    actxt.complete();
}
 
Example 19
Source File: TestAsyncServlet.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
    final AsyncContext asyncContext = req.startAsync();
    asyncContext.start(new Runnable() {
        @Override
        public void run() {
            final Log4jWebSupport webSupport =
                WebLoggerContextUtils.getWebLifeCycle(TestAsyncServlet.this.getServletContext());
            webSupport.setLoggerContext();
            // do stuff
            webSupport.clearLoggerContext();
        }
    });
}
 
Example 20
Source File: TestAsyncContextImpl.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    req.getParameter(PARAM_NAME);
    AsyncContext actxt = req.startAsync();
    actxt.addListener(new Bug54178AsyncListener());
    actxt.complete();
}