Example usage for javax.servlet.http HttpServletRequest startAsync

List of usage examples for javax.servlet.http HttpServletRequest startAsync

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest startAsync.

Prototype

public AsyncContext startAsync() throws IllegalStateException;

Source Link

Document

Puts this request into asynchronous mode, and initializes its AsyncContext with the original (unwrapped) ServletRequest and ServletResponse objects.

Usage

From source file:org.synchronoss.cloud.nio.multipart.example.web.MultipartController.java

static AsyncContext switchRequestToAsyncIfNeeded(final HttpServletRequest request) {
    if (request.isAsyncStarted()) {
        if (log.isDebugEnabled())
            log.debug("Async context already started. Return it");
        return request.getAsyncContext();
    } else {/*from   ww  w  .j  a v a  2  s  . c o m*/
        if (log.isDebugEnabled())
            log.info("Start async context and return it.");
        return request.startAsync();
    }
}

From source file:com.googlesource.gerrit.plugins.lfs.fs.LfsFsContentServlet.java

private void getObject(HttpServletRequest req, HttpServletResponse rsp, Optional<AnyLongObjectId> obj)
        throws IOException {
    if (obj.isPresent()) {
        AsyncContext context = req.startAsync();
        context.setTimeout(timeout);//w  ww . j  a va2  s . c o  m
        rsp.getOutputStream().setWriteListener(new ObjectDownloadListener(repository, context, rsp, obj.get()));
    }
}

From source file:org.eclipse.jgit.lfs.server.fs.FileLfsServlet.java

/**
 * Handle object uploads//  www  .  java  2s . com
 *
 * @param req
 *            servlet request
 * @param rsp
 *            servlet response
 * @throws ServletException
 *             if a servlet-specific error occurs
 * @throws IOException
 *             if an I/O error occurs
 */
@Override
protected void doPut(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
    AnyLongObjectId id = getObjectToTransfer(req, rsp);
    if (id != null) {
        AsyncContext context = req.startAsync();
        context.setTimeout(timeout);
        req.getInputStream().setReadListener(new ObjectUploadListener(repository, context, req, rsp, id));
    }
}

From source file:io.atrato.pubsubserver.PubsubRestProvider.java

@GET
@Path("topics/{topic}")
@Produces(MediaType.APPLICATION_JSON)//from   w  w  w  . j  a va  2 s .co m
public PubsubBroker.TimedTopicData getTopicData(@PathParam("topic") String topic,
        @QueryParam("laterThan") Long timestamp, @QueryParam("poll") Boolean poll,
        @Context HttpServletRequest request) {
    if (timestamp == null) {
        timestamp = -1L;
    }
    //LOG.debug("topic: {} poll: {}", topic, poll);
    PubsubBroker.TimedTopicData data = PubsubServer.getBroker().getLatestTopicData(topic, timestamp);
    if (data == null) {
        if (BooleanUtils.isTrue(poll)) {
            AsyncContext asyncContext = request.startAsync();
            PubsubServer.getBroker().oneTimeSubscribe(asyncContext, topic);
            asyncContext.addListener(new AsyncListener() {
                @Override
                public void onComplete(AsyncEvent asyncEvent) throws IOException {
                    PubsubServer.getBroker().invalidateOneTimeSubscriber(asyncEvent.getAsyncContext());
                }

                @Override
                public void onTimeout(AsyncEvent asyncEvent) throws IOException {
                    PubsubServer.getBroker().invalidateOneTimeSubscriber(asyncEvent.getAsyncContext());
                }

                @Override
                public void onError(AsyncEvent asyncEvent) throws IOException {
                    PubsubServer.getBroker().invalidateOneTimeSubscriber(asyncEvent.getAsyncContext());
                }

                @Override
                public void onStartAsync(AsyncEvent asyncEvent) throws IOException {
                }
            });
            return null;
        } else {
            throw new NotFoundException();
        }
    }
    LOG.debug("topic: {} poll: {} data: {}", topic, poll, (data != null ? data.getData() : data));
    return data;
}

From source file:com.sishuok.chapter3.web.controller.StreamingController.java

@RequestMapping("/async3")
public void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    resp.setHeader("Connection", "Keep-Alive");
    resp.addHeader("Cache-Control", "private");
    resp.addHeader("Pragma", "no-cache");
    resp.setContentType("text/html;charset=utf-8");
    resp.flushBuffer();/*from   ww w. j a v a 2  s .c  om*/

    //1??
    final AsyncContext asyncContext = req.startAsync();

    asyncContext.addListener(new AsyncListener() {
        @Override
        public void onComplete(final AsyncEvent event) throws IOException {
            queue.remove(event.getAsyncContext());
        }

        @Override
        public void onTimeout(final AsyncEvent event) throws IOException {
            event.getAsyncContext().complete();
            queue.remove(event.getAsyncContext());
        }

        @Override
        public void onError(final AsyncEvent event) throws IOException {
            queue.remove(event.getAsyncContext());
        }

        @Override
        public void onStartAsync(final AsyncEvent event) throws IOException {
        }
    });

    //????
    queue.add(asyncContext);

}

From source file:com.googlesource.gerrit.plugins.lfs.fs.LfsFsContentServlet.java

@Override
protected void doPut(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
    AnyLongObjectId id = getObjectToTransfer(req, rsp);
    if (id == null) {
        return;/*from w w  w .  j a  v  a 2s .  co  m*/
    }

    if (!authorizer.verifyAuthInfo(req.getHeader(HDR_AUTHORIZATION), UPLOAD, id)) {
        sendError(rsp, HttpStatus.SC_UNAUTHORIZED,
                MessageFormat.format(LfsServerText.get().failedToCalcSignature, "Invalid authorization token"));
        return;
    }

    AsyncContext context = req.startAsync();
    context.setTimeout(timeout);
    req.getInputStream().setReadListener(new ObjectUploadListener(repository, context, req, rsp, id));
}

From source file:org.eclipse.jgit.lfs.server.fs.FileLfsServlet.java

/**
 * Handles object downloads/*ww w .  j  a v  a  2  s .c  o m*/
 *
 * @param req
 *            servlet request
 * @param rsp
 *            servlet response
 * @throws ServletException
 *             if a servlet-specific error occurs
 * @throws IOException
 *             if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
    AnyLongObjectId obj = getObjectToTransfer(req, rsp);
    if (obj != null) {
        if (repository.getSize(obj) == -1) {
            sendError(rsp, HttpStatus.SC_NOT_FOUND,
                    MessageFormat.format(LfsServerText.get().objectNotFound, obj.getName()));
            return;
        }
        AsyncContext context = req.startAsync();
        context.setTimeout(timeout);
        rsp.getOutputStream().setWriteListener(new ObjectDownloadListener(repository, context, rsp, obj));
    }
}

From source file:org.sample.nonblocking.WriteTestServlet.java

/**
 * Processes requests for both HTTP//from w w  w  . j  av  a  2 s . c om
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet WriteServlet</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet WriteServlet at " + request.getContextPath() + "</h1>");

        AsyncContext context = request.startAsync();
        ServletOutputStream output = response.getOutputStream();
        output.setWriteListener(new MyWriteListener(output, context));

        out.println("</body>");
        out.println("</html>");
    }
}

From source file:org.sample.nonblocking.ReadTestServlet.java

/**
 * Processes requests for both HTTP/*from   w w w  .ja v  a  2s .c  o  m*/
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter output = response.getWriter()) {
        output.println("<html>");
        output.println("<head>");
        output.println("<title>Servlet ReadTestServlet</title>");
        output.println("</head>");
        output.println("<body>");
        output.println("<h1>Servlet ReadTestServlet at " + request.getContextPath() + "</h1>");

        AsyncContext context = request.startAsync();
        ServletInputStream input = request.getInputStream();
        input.setReadListener(new MyReadListener(input, context));

        output.println("</body>");
        output.println("</html>");
    }
}

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 . j  av a2s.  c  o m
    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);
        }
    });
}