下面列出了javax.servlet.http.HttpServletRequest#startAsync() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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());
}
@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();
}
}
});
}
@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());
}
@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());
}
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());
}
@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();
}
@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();
}
}
@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);
}
@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);
}
}
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);
}
}));
}
@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();
}
}
});
}
@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();
}
@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();
}
});
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
AsyncContext actxt = req.startAsync();
resp.setStatus(status);
actxt.complete();
}
@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();
}
@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));
}
@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();
}
});
}
@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");
}
});
}
@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();
}
}
@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();
}