List of usage examples for javax.servlet AsyncContext getResponse
public ServletResponse getResponse();
From source file:org.siphon.d2js.DispatchServlet.java
@Override protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); request.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true); AsyncContext asyncContext = request.startAsync(request, response); D2jsRunner d2jsRunner = this.getD2jsRunner(); try {//from ww w . j av a2s. c om d2jsRunner.run((HttpServletRequest) asyncContext.getRequest(), (HttpServletResponse) asyncContext.getResponse(), "modify"); } finally { asyncContext.complete(); } }
From source file:org.structr.pdf.servlet.PdfServlet.java
@Override protected void renderAsyncOutput(HttpServletRequest request, HttpServletResponse response, App app, RenderContext renderContext, DOMNode rootElement) throws IOException { final AsyncContext async = request.startAsync(); final ServletOutputStream out = async.getResponse().getOutputStream(); final AtomicBoolean finished = new AtomicBoolean(false); final DOMNode rootNode = rootElement; response.setContentType("application/pdf"); response.setHeader("Content-Disposition", "attachment;filename=\"FileName.pdf\""); threadPool.submit(new Runnable() { @Override/* w w w . j a va 2 s .c o m*/ public void run() { try (final Tx tx = app.tx()) { // render rootNode.render(renderContext, 0); finished.set(true); tx.success(); } catch (Throwable t) { t.printStackTrace(); logger.warn("Error while rendering page {}: {}", rootNode.getName(), t.getMessage()); try { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); finished.set(true); } catch (IOException ex) { logger.warn("", ex); } } } }); // start output write listener out.setWriteListener(new WriteListener() { @Override public void onWritePossible() throws IOException { try { final Queue<String> queue = renderContext.getBuffer().getQueue(); String pageContent = ""; while (out.isReady()) { String buffer = null; synchronized (queue) { buffer = queue.poll(); } if (buffer != null) { pageContent += buffer; } else { if (finished.get()) { // TODO: implement parameters for wkhtmltopdf in settings Pdf pdf = new Pdf(); pdf.addPageFromString(pageContent); out.write(pdf.getPDF()); async.complete(); // prevent this block from being called again break; } Thread.sleep(1); } } } catch (EofException ee) { logger.warn( "Could not flush the response body content to the client, probably because the network connection was terminated."); } catch (IOException | InterruptedException t) { logger.warn("Unexpected exception", t); } } @Override public void onError(Throwable t) { if (t instanceof EofException) { logger.warn( "Could not flush the response body content to the client, probably because the network connection was terminated."); } else { logger.warn("Unexpected exception", t); } } }); }
From source file:org.siphon.d2js.DispatchServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); request.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true); AsyncContext asyncContext = request.startAsync(request, response); D2jsRunner d2jsRunner = this.getD2jsRunner(); String method = StringUtils.defaultIfEmpty(request.getParameter("_m"), "create"); try {/*from www. j a v a 2 s. c o m*/ d2jsRunner.run((HttpServletRequest) asyncContext.getRequest(), (HttpServletResponse) asyncContext.getResponse(), method); } finally { asyncContext.complete(); } }
From source file:org.siphon.d2js.DispatchServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); request.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true); AsyncContext asyncContext = request.startAsync(request, response); D2jsRunner d2jsRunner = this.getD2jsRunner(); String method = StringUtils.defaultIfEmpty(request.getParameter("_m"), "fetch"); try {/*w ww . j ava 2s. c o m*/ d2jsRunner.run((HttpServletRequest) asyncContext.getRequest(), (HttpServletResponse) asyncContext.getResponse(), method); } finally { asyncContext.complete(); } }
From source file:com.kurento.kmf.content.internal.ControlProtocolManager.java
/** * Internal implementation for sending JSON (called from sendJsonAnswer and * sendJsonError methods)./*w w w .j a v a 2 s .com*/ * * @param asyncCtx * Asynchronous context * @param message * JSON message (as a Java class) * @throws IOException * Exception while parsing operating with asynchronous context */ private void internalSendJsonAnswer(AsyncContext asyncCtx, JsonRpcResponse message) { try { if (asyncCtx == null) { throw new KurentoMediaFrameworkException("Null asyncCtx found", 20017); } synchronized (asyncCtx) { if (!asyncCtx.getRequest().isAsyncStarted()) { throw new KurentoMediaFrameworkException("Cannot send message in completed asyncCtx", 1); // TODO } HttpServletResponse response = (HttpServletResponse) asyncCtx.getResponse(); response.setContentType("application/json"); OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream(), UTF8); osw.write(gson.toJson(message)); osw.flush(); log.info("Sent JsonRpc answer ...\n" + message); asyncCtx.complete(); } } catch (IOException ioe) { throw new KurentoMediaFrameworkException(ioe.getMessage(), ioe, 20018); } }
From source file:org.synchronoss.cloud.nio.multipart.example.web.MultipartController.java
void sendErrorOrSkip(final AtomicInteger synchronizer, final AsyncContext asyncContext, final String message) { if (synchronizer.getAndIncrement() <= 1) { try {/* ww w.java 2 s . c o m*/ final ServletResponse servletResponse = asyncContext.getResponse(); if (servletResponse instanceof HttpServletResponse) { ((HttpServletResponse) servletResponse).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); } else { asyncContext.getResponse().getWriter().write(message); } asyncContext.complete(); } catch (Exception e) { log.error("Failed to send back the error response", e); } } }
From source file:jetbrains.buildServer.clouds.azure.arm.web.SettingsController.java
private void doPost(@NotNull final HttpServletRequest request, @NotNull final HttpServletResponse response) { final Element xmlResponse = XmlResponseUtil.newXmlResponse(); final ActionErrors errors = new ActionErrors(); final String[] resources = request.getParameterValues("resource"); final List<Promise<Content, Throwable, Void>> promises = new ArrayList<>(resources.length); for (final String resource : resources) { final ResourceHandler handler = HANDLERS.get(resource); if (handler == null) continue; try {/*ww w .j av a 2 s. c o m*/ final Promise<Content, Throwable, Void> promise = handler.handle(request) .fail(new FailCallback<Throwable>() { @Override public void onFail(Throwable result) { LOG.debug(result); errors.addError(resource, result.getMessage()); } }); promises.add(promise); } catch (Throwable t) { LOG.debug(t); errors.addError(resource, t.getMessage()); } } if (promises.size() == 0) { if (errors.hasErrors()) { errors.serialize(xmlResponse); } writeResponse(xmlResponse, response); return; } final AsyncContext context = request.startAsync(request, response); myManager.when(promises.toArray(new Promise[] {})).always(new AlwaysCallback<MultipleResults, OneReject>() { @Override public void onAlways(Promise.State state, MultipleResults resolved, OneReject rejected) { if (errors.hasErrors()) { errors.serialize(xmlResponse); } else { for (OneResult oneResult : resolved) { xmlResponse.addContent((Content) oneResult.getResult()); } } writeResponse(xmlResponse, context.getResponse()); context.complete(); } }); }
From source file:org.synchronoss.cloud.nio.multipart.example.web.MultipartController.java
void sendResponseOrSkip(final AtomicInteger synchronizer, final AsyncContext asyncContext, final VerificationItems verificationItems) { if (synchronizer.getAndIncrement() == 1) { try {// w ww . ja v a 2 s . c o m final Writer responseWriter = asyncContext.getResponse().getWriter(); responseWriter.write(GSON.toJson(verificationItems)); asyncContext.complete(); } catch (Exception e) { log.error("Failed to send back the response", e); } } }
From source file:eu.rethink.lhcb.broker.servlet.WellKnownServlet.java
private void handleRequest(HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { // add header for cross domain stuff resp.addHeader("Access-Control-Allow-Origin", "*"); String host = req.getHeader("X-Forwarded-Host"); if (host == null) host = req.getHeader("Host"); // setting external host here helps BrokerWebSocketListener to return info about HTTP interface // Broker might not know how it is accessible. This is a workaround for it LHCBBroker.externalHost = host;/*from w w w .ja v a 2 s .c om*/ final AsyncContext asyncContext = req.startAsync(); asyncContext.start(() -> { ServletRequest aReq = asyncContext.getRequest(); String payload = null; try { payload = IOUtils.toString(aReq.getReader()); } catch (IOException e) { e.printStackTrace(); } String finalPayload = payload; Map<String, String[]> params = aReq.getParameterMap(); LOG.debug("payload: {}\r\nparams: {}", payload, params); RequestCallback cb = new RequestCallback() { @Override public void response(Message msg) { resp.setStatus(HttpServletResponse.SC_OK); try { asyncContext.getResponse().getWriter().write(msg.toString()); asyncContext.getResponse().getWriter().flush(); asyncContext.complete(); } catch (IOException e) { e.printStackTrace(); } } @Override public void error(Exception e) { String error = "Request failed.\r\npayload: " + finalPayload + "\r\nparams: " + params; LOG.error(error + "\r\nreason: " + e.getLocalizedMessage(), e instanceof InvalidMessageException ? null : e); if (e instanceof InvalidMessageException) { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); } else { resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } completeAsyncContext(asyncContext, error + "\r\nreason: " + e.getLocalizedMessage()); } }; try { Message msg = null; if (payload.length() > 0) { msg = Message.fromString(payload); } else { msg = Message.fromParams(params); } requestHandler.handleRequest(msg, cb); } catch (InvalidMessageException e) { cb.error(e); } }); }