use of javax.servlet.AsyncContext in project jetty.project by eclipse.
the class AsyncListenerServlet method doPost.
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
AsyncContext asyncContext = req.startAsync();
MyAsyncListener listener = asyncContext.createListener(MyAsyncListener.class);
PrintWriter writer = resp.getWriter();
writer.println("<html>");
writer.println("<HEAD><link rel=\"stylesheet\" type=\"text/css\" href=\"../stylesheet.css\"/></HEAD>");
writer.println("<body>");
writer.println("<h1>AsyncListener</h2>");
writer.println("<pre>");
writer.println("<h2>@PostConstruct Callback</h2>");
writer.println("<pre>");
writer.println("@PostConstruct");
writer.println("private void postConstruct ()");
writer.println("{}");
writer.println("</pre>");
writer.println("<br/><b>Result: " + (listener.isPostConstructCalled() ? "<span class=\"pass\">PASS</span>" : "<span class=\"fail\">FAIL</span>") + "</b>");
writer.println("<h2>@Resource Injection for env-entry </h2>");
writer.println("<pre>");
writer.println("@Resource(mappedName=\"maxAmount\")");
writer.println("private Double maxAmount;");
writer.println("</pre>");
writer.println("<br/><b>Result: " + (listener.isResourceInjected() ? " <span class=\"pass\">PASS</span>" : " <span class=\"FAIL\">FAIL</span>") + "</b>");
writer.println("</body>");
writer.println("</html>");
writer.flush();
writer.close();
asyncContext.complete();
}
use of javax.servlet.AsyncContext in project jetty.project by eclipse.
the class AsyncRestServlet method doGet.
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Long start = System.nanoTime();
// Do we have results yet?
Queue<Map<String, String>> results = (Queue<Map<String, String>>) request.getAttribute(RESULTS_ATTR);
// If no results, this must be the first dispatch, so send the REST request(s)
if (results == null) {
// define results data structures
final Queue<Map<String, String>> resultsQueue = new ConcurrentLinkedQueue<>();
request.setAttribute(RESULTS_ATTR, results = resultsQueue);
// suspend the request
// This is done before scheduling async handling to avoid race of
// dispatch before startAsync!
final AsyncContext async = request.startAsync();
async.setTimeout(30000);
// extract keywords to search for
String[] keywords = sanitize(request.getParameter(ITEMS_PARAM)).split(",");
final AtomicInteger outstanding = new AtomicInteger(keywords.length);
// Send request each keyword
for (final String item : keywords) {
_client.newRequest(restURL(item)).method(HttpMethod.GET).send(new AsyncRestRequest() {
@Override
void onAuctionFound(Map<String, String> auction) {
resultsQueue.add(auction);
}
@Override
void onComplete() {
if (outstanding.decrementAndGet() <= 0)
async.dispatch();
}
});
}
// save timing info and return
request.setAttribute(START_ATTR, start);
request.setAttribute(DURATION_ATTR, System.nanoTime() - start);
return;
}
// We have results!
// Generate the response
String thumbs = generateThumbs(results);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><head>");
out.println(STYLE);
out.println("</head><body><small>");
long initial = (Long) request.getAttribute(DURATION_ATTR);
long start0 = (Long) request.getAttribute(START_ATTR);
long now = System.nanoTime();
long total = now - start0;
long generate = now - start;
long thread = initial + generate;
out.print("<b>Asynchronous: " + sanitize(request.getParameter(ITEMS_PARAM)) + "</b><br/>");
out.print("Total Time: " + ms(total) + "ms<br/>");
out.print("Thread held (<span class='red'>red</span>): " + ms(thread) + "ms (" + ms(initial) + " initial + " + ms(generate) + " generate )<br/>");
out.print("Async wait (<span class='green'>green</span>): " + ms(total - thread) + "ms<br/>");
out.println("<img border='0px' src='asyncrest/red.png' height='20px' width='" + width(initial) + "px'>" + "<img border='0px' src='asyncrest/green.png' height='20px' width='" + width(total - thread) + "px'>" + "<img border='0px' src='asyncrest/red.png' height='20px' width='" + width(generate) + "px'>");
out.println("<hr />");
out.println(thumbs);
out.println("</small>");
out.println("</body></html>");
out.close();
}
use of javax.servlet.AsyncContext in project jetty.project by eclipse.
the class Servlet3Continuation method complete.
/* ------------------------------------------------------------ */
@Override
public void complete() {
AsyncContext context = _context;
if (context == null)
throw new IllegalStateException();
_context.complete();
}
use of javax.servlet.AsyncContext in project jetty.project by eclipse.
the class AsyncDelayHandler method handle.
/* ------------------------------------------------------------ */
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
if (!isStarted() || _handler == null)
return;
// Get the dispatcher types
DispatcherType ctype = baseRequest.getDispatcherType();
DispatcherType dtype = (DispatcherType) baseRequest.getAttribute(AHW_ATTR);
Object async_context_path = null;
Object async_path_info = null;
Object async_query_string = null;
Object async_request_uri = null;
Object async_servlet_path = null;
// Is this request a restarted one?
boolean restart = false;
if (dtype != null) {
// fake the dispatch type to the original
baseRequest.setAttribute(AHW_ATTR, null);
baseRequest.setDispatcherType(dtype);
restart = true;
async_context_path = baseRequest.getAttribute(AsyncContext.ASYNC_CONTEXT_PATH);
baseRequest.setAttribute(AsyncContext.ASYNC_CONTEXT_PATH, null);
async_path_info = baseRequest.getAttribute(AsyncContext.ASYNC_PATH_INFO);
baseRequest.setAttribute(AsyncContext.ASYNC_PATH_INFO, null);
async_query_string = baseRequest.getAttribute(AsyncContext.ASYNC_QUERY_STRING);
baseRequest.setAttribute(AsyncContext.ASYNC_QUERY_STRING, null);
async_request_uri = baseRequest.getAttribute(AsyncContext.ASYNC_REQUEST_URI);
baseRequest.setAttribute(AsyncContext.ASYNC_REQUEST_URI, null);
async_servlet_path = baseRequest.getAttribute(AsyncContext.ASYNC_SERVLET_PATH);
baseRequest.setAttribute(AsyncContext.ASYNC_SERVLET_PATH, null);
}
// Should we handle this request now?
if (!startHandling(baseRequest, restart)) {
// No, so go async and remember dispatch type
AsyncContext context = baseRequest.startAsync();
baseRequest.setAttribute(AHW_ATTR, ctype);
delayHandling(baseRequest, context);
return;
}
// Handle the request
try {
_handler.handle(target, baseRequest, request, response);
} finally {
if (restart) {
// reset the request
baseRequest.setDispatcherType(ctype);
baseRequest.setAttribute(AsyncContext.ASYNC_CONTEXT_PATH, async_context_path);
baseRequest.setAttribute(AsyncContext.ASYNC_PATH_INFO, async_path_info);
baseRequest.setAttribute(AsyncContext.ASYNC_QUERY_STRING, async_query_string);
baseRequest.setAttribute(AsyncContext.ASYNC_REQUEST_URI, async_request_uri);
baseRequest.setAttribute(AsyncContext.ASYNC_SERVLET_PATH, async_servlet_path);
}
// signal the request is leaving the handler
endHandling(baseRequest);
}
}
use of javax.servlet.AsyncContext in project jetty.project by eclipse.
the class ThreadLimitHandler method handle.
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
// Allow ThreadLimit to be enabled dynamically without restarting server
if (!_enabled) {
// if disabled, handle normally
super.handle(target, baseRequest, request, response);
} else {
// Get the remote address of the request
Remote remote = getRemote(baseRequest);
if (remote == null) {
// if remote is not known, handle normally
super.handle(target, baseRequest, request, response);
} else {
// Do we already have a future permit from a previous invocation?
Closeable permit = (Closeable) baseRequest.getAttribute(PERMIT);
try {
if (permit != null) {
// Yes, remove it from any future async cycles.
baseRequest.removeAttribute(PERMIT);
} else {
// No, then lets try to acquire one
CompletableFuture<Closeable> future_permit = remote.acquire();
// Did we get a permit?
if (future_permit.isDone()) {
// yes
permit = future_permit.get();
} else {
if (LOG.isDebugEnabled())
LOG.debug("Threadlimited {} {}", remote, target);
// No, lets asynchronously suspend the request
AsyncContext async = baseRequest.startAsync();
// let's never timeout the async. If this is a DOS, then good to make them wait, if this is not
// then give them maximum time to get a thread.
async.setTimeout(0);
// dispatch the request when we do eventually get a pass
future_permit.thenAccept(c -> {
baseRequest.setAttribute(PERMIT, c);
async.dispatch();
});
return;
}
}
// Use the permit
super.handle(target, baseRequest, request, response);
} catch (InterruptedException | ExecutionException e) {
throw new ServletException(e);
} finally {
if (permit != null)
permit.close();
}
}
}
}
Aggregations