Example usage for javax.servlet AsyncContext getResponse

List of usage examples for javax.servlet AsyncContext getResponse

Introduction

In this page you can find the example usage for javax.servlet AsyncContext getResponse.

Prototype

public ServletResponse getResponse();

Source Link

Document

Gets the response that was used to initialize this AsyncContext by calling ServletRequest#startAsync() or ServletRequest#startAsync(ServletRequest,ServletResponse) .

Usage

From source file:org.forumj.web.requesthandler.handler.ForumThreadHandler.java

@Override
protected void doHandle(AsyncContext context) throws FJWebException {
    try {//from w w  w . j a  va 2 s .c om
        HttpServletRequest request = (HttpServletRequest) context.getRequest();
        HttpServletResponse response = (HttpServletResponse) context.getResponse();
        long startTime = new Date().getTime();
        StringBuffer buffer = new StringBuffer();
        HttpSession session = request.getSession();
        cache(response);
        //  ?  ?? ?  ,  
        Integer pageNumber = request.getParameter("page") == null ? 1
                : Integer.valueOf(request.getParameter("page"));
        // id 
        Long threadId = request.getParameter("id") == null ? 1 : Long.valueOf(request.getParameter("id"));
        // ? ?,   
        String replyPostParameter = request.getParameter("reply");
        String end = request.getParameter("end");
        //  ? ??
        String msg = request.getParameter("msg");
        VoiceService voiceService = FJServiceHolder.getVoiceService();
        PostService postService = FJServiceHolder.getPostService();
        SubscribeService subscribeService = FJServiceHolder.getSubscribeService();
        ThreadService treadService = FJServiceHolder.getThreadService();
        IFJThread thread = treadService.readThread(threadId);
        boolean isAnswer = replyPostParameter != null && !"".equals(replyPostParameter.trim());
        LocaleString locale = (LocaleString) session.getAttribute("locale");
        IUser user = (IUser) session.getAttribute("user");
        IgnorService ignorService = FJServiceHolder.getIgnorService();
        List<IIgnor> ignorList = ignorService.readUserIgnor(user.getId());
        //  ??
        Integer count = thread.getPcount();
        Integer couP = (int) (Math.floor((double) count / user.getPt()) + 2);
        // ?   ? ?,    ?
        boolean lastPost = false;
        if (isAnswer || end != null) {
            pageNumber = couP - 1;
            lastPost = true;
        }
        int nfirstpost = (pageNumber - 1) * user.getPt();
        List<IFJPost> posts = postService.readPosts(user, threadId, nfirstpost, user.getPt(), pageNumber,
                lastPost);
        int postsAmount = posts.size();
        //  ?? ?
        session.setAttribute("page", pageNumber);
        session.setAttribute("id", threadId);
        session.setAttribute("where", request.getContextPath() + "?id=" + threadId + "&page=" + pageNumber);
        int countPosts = 0;
        if (msg != null && !"".equals(msg.trim())) {
            try {
                Long msgId = new Long(msg);
                countPosts = postService.getPostsCountInThread(threadId, msgId);
            } catch (NumberFormatException e) {
                e.printStackTrace();
                msg = null;
            }
            pageNumber = (int) (Math.floor(countPosts / user.getPt()) + 1);
        }
        // ? ?
        // ?
        if (!isRobot(request)) {
            // ?
            treadService.setSeen(user, threadId);
        }
        // ?   ?     colspan!
        buffer.append("<div>");
        buffer.append("<table width=100%>");
        buffer.append("<tr>");
        buffer.append("<td>");
        buffer.append("<table>");
        buffer.append("<tr>");
        buffer.append("<td class='page'>");
        buffer.append("<font class=mnuforum><b>" + locale.getString("mess22") + "&nbsp;</b></font>");
        buffer.append("</td>");
        int i2 = 0;
        for (int i1 = 1; i1 < couP; i1++) {
            i2 = i2 + 1;
            if ((i1 > (pageNumber - 5) && i1 < (pageNumber + 5)) || i2 == 10 || i1 == 1 || i1 == (couP - 1)) {
                if (i2 == 10)
                    i2 = 0;
                if (i1 == pageNumber) {
                    buffer.append("<td class='pagecurrent'>");
                    buffer.append("<span class=mnuforum><b>" + i1 + "</b></span>");
                    buffer.append("</td>");
                } else {
                    buffer.append("<td class='page'>");
                    buffer.append("<a class=mnuforum href='" + FJUrl.VIEW_THREAD + "?page=" + i1 + "&id="
                            + threadId + "'>" + i1 + "</a>");
                    buffer.append("</td>");
                }
            }
        }
        buffer.append("</tr>");
        buffer.append("</table>");

        buffer.append("</td>");

        buffer.append("<td align=right>");
        //  ? :)
        buffer.append("<span class=posthead>" + locale.getString("mess91") + "</span>");
        buffer.append("</td>");
        buffer.append("</tr></table>");
        buffer.append("</td>");
        buffer.append("</tr></table></td></tr>");
        //   ?? ?
        // ?  
        buffer.append("<tr><td height='400' valign='top'>");
        //  
        buffer.append("<table border='0' cellpadding='2' cellspacing='0' width='100%'>");
        // ? - ? 
        if (postsAmount > count) {
            postsAmount = count - (pageNumber - 1) * user.getPt();
        } else {
            postsAmount = user.getPt();
        }
        // 
        //  ?
        for (int postIndex = 0; postIndex < posts.size(); postIndex++) {
            IFJPost post = posts.get(postIndex);
            buffer.append(writePost(post, ignorList, user, pageNumber, locale, thread, voiceService));
        }
        // / 
        buffer.append("</table>");
        // "" 
        buffer.append("</td>");
        buffer.append("</tr>");
        //   ??
        // ?  ?
        buffer.append("<tr>");
        buffer.append("<td width='100%'>");
        buffer.append("<table border='0' style='border-collapse: collapse' width='100%'>");
        buffer.append("<tr>");
        buffer.append("<td colspan='5'>");
        buffer.append("<table>");
        buffer.append("<tr>");
        buffer.append("<td class='page'>");
        buffer.append("<font class=mnuforum><b>" + locale.getString("mess22") + "&nbsp;</b></font>");
        buffer.append("</td>");
        i2 = 0;
        for (int i1 = 1; i1 < couP; i1++) {
            i2 = i2 + 1;
            if ((i1 > (pageNumber - 5) && i1 < (pageNumber + 5)) || i2 == 10 || i1 == 1 || i1 == (couP - 1)) {
                if (i2 == 10)
                    i2 = 0;
                if (i1 == pageNumber) {
                    buffer.append("<td class='pagecurrent'>");
                    buffer.append("<span class=mnuforum><b>" + i1 + "</b></span>");
                    buffer.append("</td>");
                } else {
                    buffer.append("<td class='page'>");
                    buffer.append("<a class=mnuforum href='" + FJUrl.VIEW_THREAD + "?page=" + i1 + "&id="
                            + threadId + "'>" + i1 + "</a>");
                    buffer.append("</td>");
                }
            }
        }
        buffer.append("</tr>");
        buffer.append("</table>");
        buffer.append("</td>");
        buffer.append("</tr>");
        //  ""
        buffer.append("</table></td></tr>");
        if (user.isLogined() && !user.isBanned() && !thread.isClosed()) {
            // ?/?   
            //  ??
            String action = "";
            String mess = "";
            if (subscribeService.isUserSubscribed(threadId, user.getId())) {
                //? ?,  ??
                action = FJUrl.DELETE_SUBSCRIBE + "?pg=" + pageNumber;
                mess = locale.getString("mess90");
            } else {
                //?  -   ???
                action = FJUrl.ADD_SUBSCRIBE + "?pg=" + pageNumber;
                mess = locale.getString("mess89");
            }
            buffer.append("<tr>");
            buffer.append("<td align=right>");
            buffer.append("<form id='subs' action='" + action + "' method='post'>");
            buffer.append("<table>");
            buffer.append("<tr>");
            buffer.append("<td>");
            buffer.append(fd_button(mess, "subscribe();", "btn_subs", "1"));
            //  ...
            buffer.append("<input type=hidden name='IDT' value='" + threadId + "'>");
            buffer.append(fd_form_add(user));
            buffer.append("</td>");
            buffer.append("</tr>");
            buffer.append("</table>");
            buffer.append("</form>");
            buffer.append("</td>");
            buffer.append("</tr>");
            String re = "";
            String head = thread.getHead();
            IFJPost replyPost = null;
            // ? /
            if (isAnswer) {
                replyPost = postService.read(Long.valueOf(replyPostParameter));
                head = removeSlashes(replyPost.getHead().getTitle());
            }
            // ? 
            //   ?
            buffer.append("<tr>");
            buffer.append("<td>");
            buffer.append("<a name='edit'>&nbsp;");
            buffer.append("</a>");
            buffer.append("<table>");
            buffer.append("<tr>");
            buffer.append("<td>");
            buffer.append("<form name='post' action='" + FJUrl.ADD_POST + "' method='post'>");
            buffer.append("<table width='100%'>");
            //
            buffer.append("<tr>");
            buffer.append("<td colspan='2' align='CENTER'>");
            buffer.append("<table>");
            buffer.append("<tr>");
            buffer.append("<td>");
            buffer.append(locale.getString("mess59") + ":&nbsp;");
            buffer.append("</td>");
            buffer.append("<td>");
            buffer.append(fd_input("NHEAD", re + HtmlChars.convertHtmlSymbols(head), "70", "1"));
            buffer.append("</td>");
            buffer.append("</tr>");
            buffer.append("</table>");
            buffer.append("</td>");
            buffer.append("</tr>");
            buffer.append("<tr>");
            // 
            buffer.append("<td width='400' align='CENTER'>");
            buffer.append("<p>");
            buffer.append(locale.getString("mess21") + ":");
            buffer.append("</p>");
            buffer.append("</td>");
            //
            buffer.append("<td align='CENTER'>");
            buffer.append("<p>");
            buffer.append(locale.getString("mess12"));
            buffer.append("</p>");
            buffer.append("</td>");
            buffer.append("</tr>");
            //?
            buffer.append("<tr>");
            buffer.append("<td valign='TOP' width='100%' height='100%'>");
            //
            buffer.append(smiles_add(locale.getString("mess11")));
            buffer.append("</td>");
            buffer.append("<td width='500' align='CENTER' valign='top'>");
            //?
            buffer.append(autotags_add());
            // ?
            String textarea = "";
            if (isAnswer) {
                String ans = request.getParameter("ans");
                if (replyPost.getHead().getAuth().equals(user.getId())) {
                    textarea += HtmlChars.convertHtmlSymbols(removeSlashes(replyPost.getBody().getBody()));
                } else if (ans == null) {
                    textarea += "[quote][b]" + HtmlChars.convertHtmlSymbols(
                            removeSlashes(replyPost.getHead().getAuthor().getNick())) + "[/b] ";
                    textarea += locale.getString("mess14") + String.valueOf((char) 13);
                    textarea += HtmlChars.convertHtmlSymbols(removeSlashes(replyPost.getBody().getBody()))
                            + "[/quote]";
                } else {
                    textarea += "[b]" + removeSlashes(replyPost.getHead().getAuthor().getNick()) + "[/b]";
                    textarea += ", ";
                }
            }
            buffer.append("<textarea rows='20' class='mnuforumSm' id='ed1' name='A2' cols='55'>" + textarea
                    + "</textarea>");
            buffer.append("<br>");
            buffer.append("<input type='checkbox' name='no_exit' value='1'>");
            buffer.append(locale.getString("mess123"));
            //
            buffer.append("<table>");
            buffer.append("<tr>");
            buffer.append("<td>");
            if (isAnswer && (replyPost.getHead().getAuth().equals(user.getId()))) {
                buffer.append(fd_button(locale.getString("mess13"), "post_submit(\"write_edit\");", "B1", "1"));
            } else {
                buffer.append(fd_button(locale.getString("mess13"), "post_submit(\"write_new\");", "B1", "1"));
            }
            buffer.append("</td>");
            buffer.append("<td>");
            if (isAnswer && (replyPost.getHead().getAuth().equals(user.getId()))) {
                buffer.append(fd_button(locale.getString("mess63"), "post_submit(\"view_edit\");", "B1", "1"));
            } else {
                buffer.append(fd_button(locale.getString("mess63"), "post_submit(\"view_new\");", "B3", "1"));
            }
            buffer.append("</td>");
            buffer.append("</tr>");
            buffer.append("</table>");
            //? 
            if (isAnswer && (replyPost.getHead().getAuth().equals(user.getId()))) {
                buffer.append("<input type=hidden name='IDB' size='20' value='" + replyPostParameter + "'>");
                buffer.append(
                        "<input type=hidden name='IDTbl' size='20' value='" + replyPost.getTablePost() + "'>");
                buffer.append("<input type=hidden name='IDPst' size='20' value='" + replyPost.getId().toString()
                        + "'>");
                buffer.append("<input type=hidden name='IDTblHead' size='20' value='" + replyPost.getTableHead()
                        + "'>");
                buffer.append("<input type=hidden name='IDHead' size='20' value='"
                        + replyPost.getId().toString() + "'>");
            }
            //id 
            buffer.append("<input type=hidden name='IDT' size='20' value='" + threadId + "'>");
            if (thread.isQuest()) {
                buffer.append("<input type=hidden name='ISQUEST' size='20' value='true'>");
            }
            buffer.append(fd_form_add(user));
            buffer.append("</td>");
            buffer.append("</tr>");
            buffer.append("</table>");
            buffer.append("</form>");
            buffer.append("</td>");
            buffer.append("</tr>");
            buffer.append("</table>");
            buffer.append("</td>");
            buffer.append("</tr>");
        }
        Double allTime = (double) ((new Date().getTime() - startTime));
        DecimalFormat format = new DecimalFormat("##0.###");
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter writer = response.getWriter();
        String out = buffer.toString();
        writer.write(out.replace("_", format.format(allTime / 1000)));
    } catch (Throwable e) {
        throw new FJWebException(e);
    }
}

From source file:com.ibm.amc.feedback.FeedbackHandler.java

public void handleRequest(final HttpServletRequest request, final HttpServletResponse response) {
    if (logger.isEntryEnabled())
        logger.entry("handleRequest", request, response);

    final String user = request.getRemoteUser();
    final Queue<ActionStatusResponse> statuses = getActionStatuses(user);
    if (statuses.isEmpty()) {
        // No updates pending - register listener
        final AsyncContext asyncContext = request.startAsync(request, response);
        asyncContext.setTimeout(900000000L);
        logger.debug("handleRequest", "Registering new listener for user " + user);
        synchronized (feedbackListeners) {
            Set<AsyncContext> contexts = feedbackListeners.get(user);
            if (contexts == null) {
                contexts = new HashSet<AsyncContext>();
                feedbackListeners.put(user, contexts);
            }/*www  .  j a  va2  s  .c om*/
            contexts.add(asyncContext);
        }

        // Timeout listener
        executor.schedule(new Runnable() {

            @Override
            public void run() {
                synchronized (feedbackListeners) {
                    final Set<AsyncContext> contexts = feedbackListeners.get(user);
                    if (contexts.remove(asyncContext)) {
                        if (logger.isDebugEnabled())
                            logger.debug("handleRequest$Runnable.run", "Timing out listener for user " + user);
                        writeResponse(asyncContext.getResponse(), new LinkedList<ActionStatusResponse>());
                        asyncContext.complete();
                        if (contexts.isEmpty())
                            feedbackListeners.remove(user);
                    }
                }
            }

        }, POLLING_TIMEOUT, TimeUnit.SECONDS);
    } else {
        // Update pending - send response immediately
        writeResponse(response, statuses);
    }

    if (logger.isEntryEnabled())
        logger.exit("handleRequest");
}

From source file:org.structr.web.servlet.HtmlServlet.java

@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) {

    final Authenticator auth = getConfig().getAuthenticator();
    List<Page> pages = null;
    boolean requestUriContainsUuids = false;

    SecurityContext securityContext;//w  w w  .ja  va 2s. c  o m
    final App app;

    try {
        final String path = request.getPathInfo();

        // check for registration (has its own tx because of write access
        if (checkRegistration(auth, request, response, path)) {

            return;
        }

        // check for registration (has its own tx because of write access
        if (checkResetPassword(auth, request, response, path)) {

            return;
        }

        // isolate request authentication in a transaction
        try (final Tx tx = StructrApp.getInstance().tx()) {
            securityContext = auth.initializeAndExamineRequest(request, response);
            tx.success();
        }

        app = StructrApp.getInstance(securityContext);

        try (final Tx tx = app.tx()) {

            // Ensure access mode is frontend
            securityContext.setAccessMode(AccessMode.Frontend);

            request.setCharacterEncoding("UTF-8");

            // Important: Set character encoding before calling response.getWriter() !!, see Servlet Spec 5.4
            response.setCharacterEncoding("UTF-8");

            boolean dontCache = false;

            logger.log(Level.FINE, "Path info {0}", path);

            // don't continue on redirects
            if (response.getStatus() == 302) {

                tx.success();
                return;
            }

            final Principal user = securityContext.getUser(false);
            if (user != null) {

                // Don't cache if a user is logged in
                dontCache = true;

            }

            final RenderContext renderContext = RenderContext.getInstance(securityContext, request, response);

            renderContext.setResourceProvider(config.getResourceProvider());

            final EditMode edit = renderContext.getEditMode(user);

            DOMNode rootElement = null;
            AbstractNode dataNode = null;

            final String[] uriParts = PathHelper.getParts(path);
            if ((uriParts == null) || (uriParts.length == 0)) {

                // find a visible page
                rootElement = findIndexPage(securityContext, pages, edit);

                logger.log(Level.FINE, "No path supplied, trying to find index page");

            } else {

                if (rootElement == null) {

                    rootElement = findPage(securityContext, pages, path, edit);

                } else {
                    dontCache = true;
                }
            }

            if (rootElement == null) { // No page found

                // Look for a file
                final File file = findFile(securityContext, request, path);
                if (file != null) {

                    streamFile(securityContext, file, request, response, edit);
                    tx.success();
                    return;

                }

                // store remaining path parts in request
                final Matcher matcher = threadLocalUUIDMatcher.get();

                for (int i = 0; i < uriParts.length; i++) {

                    request.setAttribute(uriParts[i], i);
                    matcher.reset(uriParts[i]);

                    // set to "true" if part matches UUID pattern
                    requestUriContainsUuids |= matcher.matches();

                }

                if (!requestUriContainsUuids) {

                    // Try to find a data node by name
                    dataNode = findFirstNodeByName(securityContext, request, path);

                } else {

                    dataNode = findNodeByUuid(securityContext, PathHelper.getName(path));

                }

                //if (dataNode != null && !(dataNode instanceof Linkable)) {
                if (dataNode != null) {

                    // Last path part matches a data node
                    // Remove last path part and try again searching for a page
                    // clear possible entry points
                    request.removeAttribute(POSSIBLE_ENTRY_POINTS_KEY);

                    rootElement = findPage(securityContext, pages,
                            StringUtils.substringBeforeLast(path, PathHelper.PATH_SEP), edit);

                    renderContext.setDetailsDataObject(dataNode);

                    // Start rendering on data node
                    if (rootElement == null && dataNode instanceof DOMNode) {

                        rootElement = ((DOMNode) dataNode);
                    }
                }
            }

            // look for pages with HTTP Basic Authentication (must be done as superuser)
            if (rootElement == null) {

                final HttpBasicAuthResult authResult = checkHttpBasicAuth(request, response, path);

                switch (authResult.authState()) {

                // Element with Basic Auth found and authentication succeeded
                case Authenticated:
                    final Linkable result = authResult.getRootElement();
                    if (result instanceof Page) {

                        rootElement = (DOMNode) result;
                        securityContext = authResult.getSecurityContext();
                        renderContext.pushSecurityContext(securityContext);

                    } else if (result instanceof File) {

                        streamFile(authResult.getSecurityContext(), (File) result, request, response,
                                EditMode.NONE);
                        tx.success();
                        return;

                    }
                    break;

                // Page with Basic Auth found but not yet authenticated
                case MustAuthenticate:
                    tx.success();
                    return;

                // no Basic Auth for given path, go on
                case NoBasicAuth:
                    break;
                }

            }

            // Still nothing found, do error handling
            if (rootElement == null) {
                rootElement = notFound(response, securityContext);
            }

            if (rootElement == null) {
                tx.success();
                return;
            }

            // check dont cache flag on page (if root element is a page)
            // but don't modify true to false
            dontCache |= rootElement.getProperty(Page.dontCache);

            if (EditMode.WIDGET.equals(edit) || dontCache) {

                setNoCacheHeaders(response);

            }

            if (!securityContext.isVisible(rootElement)) {

                rootElement = notFound(response, securityContext);
                if (rootElement == null) {

                    tx.success();
                    return;
                }

            } else {

                if (!EditMode.WIDGET.equals(edit) && !dontCache
                        && notModifiedSince(request, response, rootElement, dontCache)) {

                    ServletOutputStream out = response.getOutputStream();
                    out.flush();
                    //response.flushBuffer();
                    out.close();

                } else {

                    // prepare response
                    response.setCharacterEncoding("UTF-8");

                    String contentType = rootElement.getProperty(Page.contentType);

                    if (contentType == null) {

                        // Default
                        contentType = "text/html;charset=UTF-8";
                    }

                    if (contentType.equals("text/html")) {
                        contentType = contentType.concat(";charset=UTF-8");
                    }

                    response.setContentType(contentType);

                    setCustomResponseHeaders(response);

                    final boolean createsRawData = rootElement.getProperty(Page.pageCreatesRawData);

                    // async or not?
                    if (isAsync && !createsRawData) {

                        final AsyncContext async = request.startAsync();
                        final ServletOutputStream out = async.getResponse().getOutputStream();
                        final AtomicBoolean finished = new AtomicBoolean(false);
                        final DOMNode rootNode = rootElement;

                        threadPool.submit(new Runnable() {

                            @Override
                            public void run() {

                                try (final Tx tx = app.tx()) {

                                    //final long start = System.currentTimeMillis();
                                    // render
                                    rootNode.render(renderContext, 0);
                                    finished.set(true);

                                    //final long end = System.currentTimeMillis();
                                    //System.out.println("Done in " + (end-start) + " ms");
                                    tx.success();

                                } catch (Throwable t) {
                                    t.printStackTrace();
                                    final String errorMsg = t.getMessage();
                                    try {
                                        //response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                                        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                                errorMsg);
                                        finished.set(true);
                                    } catch (IOException ex) {
                                        ex.printStackTrace();
                                    }
                                }
                            }

                        });

                        // start output write listener
                        out.setWriteListener(new WriteListener() {

                            @Override
                            public void onWritePossible() throws IOException {

                                try {

                                    final Queue<String> queue = renderContext.getBuffer().getQueue();
                                    while (out.isReady()) {

                                        String buffer = null;

                                        synchronized (queue) {
                                            buffer = queue.poll();
                                        }

                                        if (buffer != null) {

                                            out.print(buffer);

                                        } else {

                                            if (finished.get()) {

                                                async.complete();
                                                response.setStatus(HttpServletResponse.SC_OK);

                                                // prevent this block from being called again
                                                break;
                                            }

                                            Thread.sleep(1);
                                        }
                                    }

                                } catch (Throwable t) {
                                    t.printStackTrace();
                                }
                            }

                            @Override
                            public void onError(Throwable t) {
                                t.printStackTrace();
                            }
                        });

                    } else {

                        final StringRenderBuffer buffer = new StringRenderBuffer();
                        renderContext.setBuffer(buffer);

                        // render
                        rootElement.render(renderContext, 0);

                        try {

                            response.getOutputStream().write(buffer.getBuffer().toString().getBytes("utf-8"));
                            response.getOutputStream().flush();
                            response.getOutputStream().close();

                        } catch (IOException ioex) {
                            ioex.printStackTrace();
                        }
                    }
                }
            }

            tx.success();

        } catch (FrameworkException fex) {
            fex.printStackTrace();
            logger.log(Level.SEVERE, "Exception while processing request", fex);
        }

    } catch (IOException | FrameworkException t) {

        t.printStackTrace();
        logger.log(Level.SEVERE, "Exception while processing request", t);
        UiAuthenticator.writeInternalServerError(response);
    }
}