Example usage for javax.servlet ServletResponse flushBuffer

List of usage examples for javax.servlet ServletResponse flushBuffer

Introduction

In this page you can find the example usage for javax.servlet ServletResponse flushBuffer.

Prototype

public void flushBuffer() throws IOException;

Source Link

Document

Forces any content in the buffer to be written to the client.

Usage

From source file:net.jforum.core.tags.ImportFileTag.java

/**
 * @see javax.servlet.jsp.tagext.SimpleTagSupport#doTag()
 */// w  w w  .  j a v a2s . c om
@Override
public void doTag() throws JspException, IOException {
    // check the URL
    if (StringUtils.isEmpty(url))
        throw new NullAttributeException("import", "url");

    String jsp = this.getFile(url);

    ServletRequest request = this.request();
    ServletResponse respose = this.response();
    HttpSession session = ((HttpServletRequest) request).getSession();
    ServletContext servletContext = session.getServletContext();

    String jspPath = servletContext.getRealPath(jsp);
    File jspFile = new File(jspPath);
    if (!jspFile.exists())
        return;

    respose.flushBuffer();
    RequestDispatcher rd = this.pageContext().getRequest().getRequestDispatcher(jsp);
    try {
        // include the resource, using our custom wrapper
        ImportResponseWrapper irw = new ImportResponseWrapper((HttpServletResponse) respose);
        irw.setCharacterEncoding(charEncoding);
        rd.include(request, irw);
        // disallow inappropriate response codes per JSTL spec
        if (irw.getStatus() < 200 || irw.getStatus() > 299) {
            throw new JspTagException(irw.getStatus() + " " + jsp);
        }

        // recover the response String from our wrapper
        pageContext().getOut().print(irw.getString());
    } catch (ServletException e) {
        e.printStackTrace();
    }
}

From source file:edu.mayo.cts2.framework.plugin.namespace.ui.osgi.StaticHttpService.java

public void service(final ServletRequest req, final ServletResponse res) throws ServletException, IOException {
    // don't really expect to be called within a non-HTTP environment
    service((HttpServletRequest) req, (HttpServletResponse) res);

    // ensure response has been sent back and response is committed
    // (we are authorative for our URL space and no other servlet should
    // interfere)
    res.flushBuffer();
}

From source file:com.erudika.para.utils.filters.ErrorFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
        ErrorWrapperResponse wrapped = new ErrorWrapperResponse((HttpServletResponse) response);
        try {/*from   ww  w .j  a v  a2  s .  co  m*/
            chain.doFilter(request, wrapped);
            int status = wrapped.getStatus();
            if (status >= 400) {
                setErrorAttributes(request, status, wrapped.getMessage());
            }
        } catch (Throwable ex) {
            rethrow(ex);
        }
        response.flushBuffer();
    } else {
        chain.doFilter(request, response);
    }
}

From source file:org.apache.solr.servlet.SolrDispatchFilter.java

private boolean authenticateRequest(ServletRequest request, ServletResponse response,
        final AtomicReference<ServletRequest> wrappedRequest) throws IOException {
    boolean requestContinues = false;
    final AtomicBoolean isAuthenticated = new AtomicBoolean(false);
    AuthenticationPlugin authenticationPlugin = cores.getAuthenticationPlugin();
    if (authenticationPlugin == null) {
        return true;
    } else {/* ww w.j ava 2  s. c o m*/
        // /admin/info/key must be always open. see SOLR-9188
        // tests work only w/ getPathInfo
        //otherwise it's just enough to have getServletPath()
        if (PKIAuthenticationPlugin.PATH.equals(((HttpServletRequest) request).getServletPath())
                || PKIAuthenticationPlugin.PATH.equals(((HttpServletRequest) request).getPathInfo()))
            return true;
        String header = ((HttpServletRequest) request).getHeader(PKIAuthenticationPlugin.HEADER);
        if (header != null && cores.getPkiAuthenticationPlugin() != null)
            authenticationPlugin = cores.getPkiAuthenticationPlugin();
        try {
            log.debug("Request to authenticate: {}, domain: {}, port: {}", request, request.getLocalName(),
                    request.getLocalPort());
            // upon successful authentication, this should call the chain's next filter.
            requestContinues = authenticationPlugin.doAuthenticate(request, response, (req, rsp) -> {
                isAuthenticated.set(true);
                wrappedRequest.set(req);
            });
        } catch (Exception e) {
            log.info("Error authenticating", e);
            throw new SolrException(ErrorCode.SERVER_ERROR, "Error during request authentication, ", e);
        }
    }
    // requestContinues is an optional short circuit, thus we still need to check isAuthenticated.
    // This is because the AuthenticationPlugin doesn't always have enough information to determine if
    // it should short circuit, e.g. the Kerberos Authentication Filter will send an error and not
    // call later filters in chain, but doesn't throw an exception.  We could force each Plugin
    // to implement isAuthenticated to simplify the check here, but that just moves the complexity to
    // multiple code paths.
    if (!requestContinues || !isAuthenticated.get()) {
        response.flushBuffer();
        return false;
    }
    return true;
}

From source file:org.apache.catalina.core.StandardHostValve.java

/**
 * Handle the specified Throwable encountered while processing
 * the specified Request to produce the specified Response.  Any
 * exceptions that occur during generation of the exception report are
 * logged and swallowed.//from ww  w  . j a  va 2  s  . c om
 *
 * @param request The request being processed
 * @param response The response being generated
 * @param exception The exception that occurred (which possibly wraps
 *  a root cause exception
 */
protected void throwable(Request request, Response response, Throwable throwable) {
    Context context = request.getContext();
    if (context == null)
        return;

    Throwable realError = throwable;

    if (realError instanceof ServletException) {
        realError = ((ServletException) realError).getRootCause();
        if (realError == null) {
            realError = throwable;
        }
    }

    // If this is an aborted request from a client just log it and return
    if (realError instanceof ClientAbortException) {
        log.debug(sm.getString("standardHost.clientAbort",
                ((ClientAbortException) realError).getThrowable().getMessage()));
        return;
    }

    ErrorPage errorPage = findErrorPage(context, realError);

    if (errorPage != null) {
        response.setAppCommitted(false);
        ServletRequest sreq = request.getRequest();
        ServletResponse sresp = response.getResponse();
        sreq.setAttribute(ApplicationFilterFactory.DISPATCHER_REQUEST_PATH_ATTR, errorPage.getLocation());
        sreq.setAttribute(ApplicationFilterFactory.DISPATCHER_TYPE_ATTR,
                new Integer(ApplicationFilterFactory.ERROR));
        sreq.setAttribute(Globals.STATUS_CODE_ATTR, new Integer(HttpServletResponse.SC_INTERNAL_SERVER_ERROR));
        sreq.setAttribute(Globals.ERROR_MESSAGE_ATTR, throwable.getMessage());
        sreq.setAttribute(Globals.EXCEPTION_ATTR, realError);
        Wrapper wrapper = request.getWrapper();
        if (wrapper != null)
            sreq.setAttribute(Globals.SERVLET_NAME_ATTR, wrapper.getName());
        if (sreq instanceof HttpServletRequest)
            sreq.setAttribute(Globals.EXCEPTION_PAGE_ATTR, ((HttpServletRequest) sreq).getRequestURI());
        sreq.setAttribute(Globals.EXCEPTION_TYPE_ATTR, realError.getClass());
        if (custom(request, response, errorPage)) {
            try {
                sresp.flushBuffer();
            } catch (IOException e) {
                log("Exception Processing " + errorPage, e);
            }
        }
    } else {
        // A custom error-page has not been defined for the exception
        // that was thrown during request processing. Check if an
        // error-page for error code 500 was specified and if so, 
        // send that page back as the response.
        ServletResponse sresp = (ServletResponse) response;
        if (sresp instanceof HttpServletResponse) {
            ((HttpServletResponse) sresp).setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            // The response is an error
            response.setError();

            status(request, response);
        }
    }

}

From source file:org.apache.catalina.core.StandardHostValve.java

/**
 * Handle the HTTP status code (and corresponding message) generated
 * while processing the specified Request to produce the specified
 * Response.  Any exceptions that occur during generation of the error
 * report are logged and swallowed.//from   w  ww .j a  v  a2  s  .  c o m
 *
 * @param request The request being processed
 * @param response The response being generated
 */
protected void status(Request request, Response response) {

    // Do nothing on non-HTTP responses
    if (!(response instanceof HttpResponse))
        return;
    HttpResponse hresponse = (HttpResponse) response;
    if (!(response.getResponse() instanceof HttpServletResponse))
        return;
    int statusCode = hresponse.getStatus();

    // Handle a custom error page for this status code
    Context context = request.getContext();
    if (context == null)
        return;

    ErrorPage errorPage = context.findErrorPage(statusCode);
    if (errorPage != null) {
        response.setAppCommitted(false);
        ServletRequest sreq = request.getRequest();
        ServletResponse sresp = response.getResponse();
        sreq.setAttribute(Globals.STATUS_CODE_ATTR, new Integer(statusCode));
        String message = RequestUtil.filter(hresponse.getMessage());
        if (message == null)
            message = "";
        sreq.setAttribute(Globals.ERROR_MESSAGE_ATTR, message);
        sreq.setAttribute(ApplicationFilterFactory.DISPATCHER_REQUEST_PATH_ATTR, errorPage.getLocation());
        sreq.setAttribute(ApplicationFilterFactory.DISPATCHER_TYPE_ATTR,
                new Integer(ApplicationFilterFactory.ERROR));

        Wrapper wrapper = request.getWrapper();
        if (wrapper != null)
            sreq.setAttribute(Globals.SERVLET_NAME_ATTR, wrapper.getName());
        if (sreq instanceof HttpServletRequest)
            sreq.setAttribute(Globals.EXCEPTION_PAGE_ATTR, ((HttpServletRequest) sreq).getRequestURI());
        if (custom(request, response, errorPage)) {
            try {
                sresp.flushBuffer();
            } catch (IOException e) {
                log("Exception Processing " + errorPage, e);
            }
        }
    }

}

From source file:org.apache.felix.webconsole.internal.servlet.OsgiManager.java

/**
 * @see javax.servlet.GenericServlet#service(javax.servlet.ServletRequest, javax.servlet.ServletResponse)
 */// w  w  w  . j a  v  a 2 s. c  o m
public void service(final ServletRequest req, final ServletResponse res) throws ServletException, IOException {
    // don't really expect to be called within a non-HTTP environment
    service((HttpServletRequest) req, (HttpServletResponse) res);

    // ensure response has been sent back and response is committed
    // (we are authorative for our URL space and no other servlet should interfere)
    res.flushBuffer();
}

From source file:org.apache.myfaces.tomahawk.application.jsp.JspTilesTwoViewHandlerImpl.java

private void renderTilesView(FacesContext facesContext, Object[] requestObjects, TilesContainer container,
        UIViewRoot viewToRender, String viewId, String tilesId) throws IOException {
    ExternalContext externalContext = facesContext.getExternalContext();
    handleCharacterEncoding(viewId, externalContext, viewToRender);
    container.startContext(requestObjects);
    try {//w ww. jav a 2  s .  c om
        //container.render(tilesId,requestObjects);
        buildTilesViewLikeContainer(externalContext, container, tilesId, requestObjects);
    } catch (TilesException e) {
        throw new FacesException(e);
    } finally {
        container.endContext(requestObjects);
    }

    handleCharacterEncodingPostDispatch(externalContext);

    // render the view in this method (since JSF 1.2)
    RenderKitFactory renderFactory = (RenderKitFactory) FactoryFinder
            .getFactory(FactoryFinder.RENDER_KIT_FACTORY);
    RenderKit renderKit = renderFactory.getRenderKit(facesContext, viewToRender.getRenderKitId());
    ServletResponse response = (ServletResponse) requestObjects[1];
    ResponseWriter responseWriter = facesContext.getResponseWriter();
    if (responseWriter == null) {
        responseWriter = renderKit.createResponseWriter(response.getWriter(), null,
                ((HttpServletRequest) externalContext.getRequest()).getCharacterEncoding());
        facesContext.setResponseWriter(responseWriter);
    }

    ResponseWriter oldResponseWriter = responseWriter;
    StateMarkerAwareWriter stateAwareWriter = null;

    StateManager stateManager = facesContext.getApplication().getStateManager();
    if (stateManager.isSavingStateInClient(facesContext)) {
        stateAwareWriter = new StateMarkerAwareWriter();

        // Create a new response-writer using as an underlying writer the stateAwareWriter
        // Effectively, all output will be buffered in the stateAwareWriter so that later
        // this writer can replace the state-markers with the actual state.
        responseWriter = oldResponseWriter.cloneWithWriter(stateAwareWriter);
        facesContext.setResponseWriter(responseWriter);
    }

    actuallyRenderView(facesContext, viewToRender);

    //We're done with the document - now we can write all content
    //to the response, properly replacing the state-markers on the way out
    //by using the stateAwareWriter
    if (stateManager.isSavingStateInClient(facesContext)) {
        stateAwareWriter.flushToWriter(response.getWriter());
    } else {
        stateManager.saveView(facesContext);
    }

    // Final step - we output any content in the wrappedResponse response from above to the response,
    // removing the wrappedResponse response from the request, we don't need it anymore
    ViewResponseWrapper afterViewTagResponse = (ViewResponseWrapper) externalContext.getRequestMap()
            .get(AFTER_VIEW_TAG_CONTENT_PARAM);
    externalContext.getRequestMap().remove(AFTER_VIEW_TAG_CONTENT_PARAM);
    if (afterViewTagResponse != null) {
        afterViewTagResponse.flushToWriter(response.getWriter(),
                facesContext.getExternalContext().getResponseCharacterEncoding());
    }
    response.flushBuffer();
}

From source file:org.apache.shale.tiles.TilesViewHandler.java

/**
 * <p>Render a view according to the algorithm described in this class's
 * description: Based on the view Id of the <code>viewToRender</code>,
 * this method either renders a tile or delegates rendering to the default
 * view handler, which takes care of business as usual.</p>
 *
 * @param facesContext The faces context object for this request
 * @param viewToRender The view that we're rendering
 *
 * Modified to do the same thing as SunRI wjb Oct 2006 courtesy sdoglesby
 *
 * March 2007 significantly rewritten //from w ww . ja  va  2s  . com
 * @author wbossons
 */
public void renderView(FacesContext facesContext, UIViewRoot viewToRender) throws IOException, FacesException {
    String viewId = viewToRender.getViewId();
    String tileName = getTileName(viewId);
    ComponentDefinition tile = getTile(tileName);
    //DEBUG: Significant rewrite.
    if (!viewToRender.isRendered()) {
        return;
    }

    if (tile != null) {
        ExternalContext extContext = facesContext.getExternalContext();

        dispatchToTile(extContext, tile);

        ServletRequest request = (ServletRequest) extContext.getRequest();
        ServletResponse response = (ServletResponse) extContext.getResponse();

        try {
            if (executePageToBuildView(facesContext, viewToRender, tile)) {
                response.flushBuffer();
                ApplicationAssociate applicationassociate = ApplicationAssociate.getInstance(extContext);
                this.responseRendered();
                return;
            }
        } catch (IOException e) {
            throw new FacesException(e);
        }
        if (logger.isLoggable(Level.WARNING)) { //default was fine
            logger.log(Level.FINE, "Completed building view for : \n" + viewToRender.getViewId());
        }
        if (logger.isLoggable(Level.INFO)) { // default was finest
            logger.log(Level.FINEST,
                    "+=+=+=+=+=+= Printout for " + viewToRender.getViewId() + " about to render.");
            DebugUtil.printTree(viewToRender, logger, Level.FINEST);
        }

        // set up the ResponseWriter

        RenderKitFactory renderFactory = (RenderKitFactory) FactoryFinder
                .getFactory(FactoryFinder.RENDER_KIT_FACTORY);
        RenderKit renderKit = renderFactory.getRenderKit(facesContext, viewToRender.getRenderKitId());

        ResponseWriter oldWriter = facesContext.getResponseWriter();

        if (bufSize == -1) {
            WebConfiguration webConfig = WebConfiguration.getInstance(facesContext.getExternalContext());
            try {
                bufSize = Integer.parseInt(
                        webConfig.getContextInitParameter(WebContextInitParameter.ResponseBufferSize));
            } catch (NumberFormatException nfe) {
                bufSize = Integer.parseInt(WebContextInitParameter.ResponseBufferSize.getDefaultValue());
            }
        }
        WriteBehindStringWriter strWriter = new WriteBehindStringWriter(facesContext, bufSize);
        ResponseWriter newWriter;
        if (null != oldWriter) {
            newWriter = oldWriter.cloneWithWriter(strWriter);
        } else {
            newWriter = renderKit.createResponseWriter(strWriter, null, request.getCharacterEncoding());
        }
        facesContext.setResponseWriter(newWriter);

        newWriter.startDocument();

        doRenderView(facesContext, viewToRender);

        newWriter.endDocument();

        // replace markers in the body content and write it to response.

        ResponseWriter responseWriter;
        if (null != oldWriter) {
            responseWriter = oldWriter.cloneWithWriter(response.getWriter());
        } else {
            responseWriter = newWriter.cloneWithWriter(response.getWriter());
        }
        facesContext.setResponseWriter(responseWriter);

        strWriter.flushToWriter(responseWriter);

        if (null != oldWriter) {
            facesContext.setResponseWriter(oldWriter);
        }

        // write any AFTER_VIEW_CONTENT to the response
        writeAfterViewContent(extContext, response);
    } else { // no tile, use default viewhandler
        if (logger.isLoggable(Level.WARNING)) //default was fine
            logger.log(Level.WARNING, "tiles.dispatchingToViewHandler");
        if (logger.isLoggable(Level.INFO)) { // default was finest
            logger.log(Level.FINEST,
                    "+=+=+=+=+=+= Printout for " + viewToRender.getViewId() + " about to render.");
            DebugUtil.printTree(viewToRender, logger, Level.INFO);
        }
        getWrapped().renderView(facesContext, viewToRender);
    }
}