Example usage for javax.servlet.http HttpServletResponse isCommitted

List of usage examples for javax.servlet.http HttpServletResponse isCommitted

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse isCommitted.

Prototype

public boolean isCommitted();

Source Link

Document

Returns a boolean indicating if the response has been committed.

Usage

From source file:org.owasp.esapi.waf.ESAPIWebApplicationFirewallFilter.java

private void sendRedirect(InterceptingHTTPServletResponse response, HttpServletResponse httpResponse)
        throws IOException {
    /*//from www .j a  va2s  .  com
     * [chrisisbeef] - commented out as this is not currently used. Minor
     * performance tweak. String finalJavaScript =
     * AppGuardianConfiguration.JAVASCRIPT_REDIRECT; finalJavaScript =
     * finalJavaScript.replaceAll(AppGuardianConfiguration.
     * JAVASCRIPT_TARGET_TOKEN, appGuardConfig.getDefaultErrorPage());
     */

    if (response != null) {
        response.reset();
        response.resetBuffer();
        /*
         * response.setStatus(appGuardConfig.getDefaultResponseCode());
         * response.getOutputStream().write(finalJavaScript.getBytes());
         */
        response.sendRedirect(appGuardConfig.getDefaultErrorPage());

    } else {
        if (!httpResponse.isCommitted()) {
            httpResponse.sendRedirect(appGuardConfig.getDefaultErrorPage());
        } else {
            /*
             * Can't send redirect because response is already committed.
             * I'm not sure how this could happen, but I didn't want to
             * cause IOExceptions in case if it ever does.
             */
        }

    }
}

From source file:org.kantega.dogmaticmvc.web.DogmaticMVCHandler.java

@Override
public void handle(HttpServletRequest request, HttpServletResponse resp) {

    final ScriptCompiler compiler = getScriptCompiler(request);
    final Class handlerClass = compiler.compile(request);
    Map<String, byte[]> compiledClassBytes = compiler.getCompiledClassBytes(request);

    Method handlerMethod = findRequestHandlerMethod(handlerClass);

    if (handlerMethod == null) {
        TemplateEngine.Template template = templateEngine
                .createTemplate("org/kantega/dogmaticmvc/web/templates/norequestmethod.vm");
        template.setAttribute("className", handlerClass.getName());
        template.render(request, resp);/*from   ww  w  . ja  v  a 2 s .  co  m*/
        return;

    }

    try {
        if (!runVerificationPhases(handlerMethod, request, resp, compiler, compiledClassBytes)) {
            return;
        }

        Map<String, Object> model = new HashMap<String, Object>();

        Object[] params = parameterFactory.getMethodParameters(handlerMethod, request, resp, model);

        final Object result = handlerMethod.invoke(handlerClass.newInstance(), params);

        if (!resp.isCommitted() && result instanceof String) {
            for (Map.Entry<String, Object> e : model.entrySet()) {
                request.setAttribute(e.getKey(), e.getValue());
            }
            servletContext.getRequestDispatcher(String.class.cast(result)).forward(request,
                    wrapResponse(request, resp));
        }
        return;
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(e);
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    } catch (ServletException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

}

From source file:org.apache.struts.action.ExceptionHandler.java

/**
 * <p> Handle the Exception. Return the ActionForward instance (if any)
 * returned by the called ExceptionHandler. </p>
 *
 * @param ex           The exception to handle
 * @param ae           The ExceptionConfig corresponding to the exception
 * @param mapping      The ActionMapping we are processing
 * @param formInstance The ActionForm we are processing
 * @param request      The servlet request we are processing
 * @param response     The servlet response we are creating
 * @return The <code>ActionForward</code> instance (if any) returned by
 *         the called <code>ExceptionHandler</code>.
 * @throws ServletException if a servlet exception occurs
 * @since Struts 1.1/*from w w  w .  ja va  2  s.c o  m*/
 */
public ActionForward execute(Exception ex, ExceptionConfig ae, ActionMapping mapping, ActionForm formInstance,
        HttpServletRequest request, HttpServletResponse response) throws ServletException {
    LOG.debug("ExceptionHandler executing for exception " + ex);

    ActionForward forward;
    ActionMessage error;
    String property;

    // Build the forward from the exception mapping if it exists
    // or from the form input
    if (ae.getPath() != null) {
        forward = new ActionForward(ae.getPath());
    } else {
        forward = mapping.getInputForward();
    }

    // Figure out the error
    if (ex instanceof ModuleException) {
        error = ((ModuleException) ex).getActionMessage();
        property = ((ModuleException) ex).getProperty();
    } else {
        error = new ActionMessage(ae.getKey(), ex.getMessage());
        property = error.getKey();
    }

    this.logException(ex);

    // Store the exception
    request.setAttribute(Globals.EXCEPTION_KEY, ex);
    this.storeException(request, property, error, forward, ae.getScope());

    if (!response.isCommitted()) {
        return forward;
    }

    LOG.debug("Response is already committed, so forwarding will not work." + " Attempt alternate handling.");

    if (!silent(ae)) {
        handleCommittedResponse(ex, ae, mapping, formInstance, request, response, forward);
    } else {
        LOG.warn("ExceptionHandler configured with " + SILENT_IF_COMMITTED + " and response is committed.", ex);
    }

    return null;
}

From source file:org.codehaus.groovy.grails.web.sitemesh.GrailsPageFilter.java

@Override
protected DecoratorSelector initDecoratorSelector(SiteMeshWebAppContext webAppContext) {
    // TODO: Remove heavy coupling on horrible SM2 Factory
    final Factory factory = Factory.getInstance(new Config(filterConfig));
    factory.refresh();/*  w w  w.j  a va2 s . c o  m*/
    return new DecoratorMapper2DecoratorSelector(factory.getDecoratorMapper()) {
        @Override
        public Decorator selectDecorator(Content content, SiteMeshContext context) {
            SiteMeshWebAppContext webAppContext = (SiteMeshWebAppContext) context;
            final com.opensymphony.module.sitemesh.Decorator decorator = factory.getDecoratorMapper()
                    .getDecorator(webAppContext.getRequest(), content2htmlPage(content));
            if (decorator == null || decorator.getPage() == null) {
                return new GrailsNoDecorator();
            } else {
                return new OldDecorator2NewDecorator(decorator) {
                    @Override
                    protected void render(Content content, HttpServletRequest request,
                            HttpServletResponse response, ServletContext servletContext,
                            SiteMeshWebAppContext webAppContext) throws IOException, ServletException {

                        HTMLPage htmlPage = content2htmlPage(content);
                        request.setAttribute(PAGE, htmlPage);

                        // see if the URI path (webapp) is set
                        if (decorator.getURIPath() != null) {
                            // in a security conscious environment, the servlet container
                            // may return null for a given URL
                            if (servletContext.getContext(decorator.getURIPath()) != null) {
                                servletContext = servletContext.getContext(decorator.getURIPath());
                            }
                        }
                        // get the dispatcher for the decorator
                        RequestDispatcher dispatcher = servletContext.getRequestDispatcher(decorator.getPage());
                        if (response.isCommitted()) {
                            dispatcher.include(request, response);
                        } else {
                            dispatcher.forward(request, response);
                        }

                        request.removeAttribute(PAGE);
                    }

                };
            }
        }
    };
}

From source file:org.nuxeo.ecm.platform.ui.web.auth.NuxeoAuthenticationFilter.java

/**
 * Save requested URL before redirecting to login form.
 * <p>/*from w w  w . j av a 2 s  .  c o  m*/
 * Returns true if target url is a valid startup page.
 */
public boolean saveRequestedURLBeforeRedirect(HttpServletRequest httpRequest,
        HttpServletResponse httpResponse) {

    final boolean hasRequestedSessionId = !StringUtils.isBlank(httpRequest.getRequestedSessionId());

    HttpSession session = httpRequest.getSession(false);
    final boolean isTimeout = session == null && hasRequestedSessionId;

    if (!httpResponse.isCommitted()) {
        session = httpRequest.getSession(true);
    }

    if (session == null) {
        return false;
    }

    String requestPage;
    boolean requestPageInParams = false;
    if (httpRequest.getParameter(REQUESTED_URL) != null) {
        requestPageInParams = true;
        requestPage = httpRequest.getParameter(REQUESTED_URL);
    } else {
        requestPage = getRequestedUrl(httpRequest);
    }

    if (requestPage == null) {
        return false;
    }

    // add a flag to tell that the Session looks like having timed out
    if (isTimeout && !requestPage.equals(LoginScreenHelper.getStartupPagePath())) {
        session.setAttribute(SESSION_TIMEOUT, Boolean.TRUE);
    } else {
        session.removeAttribute(SESSION_TIMEOUT);
    }

    // avoid redirect if not useful
    if (requestPage.startsWith(LoginScreenHelper.getStartupPagePath())) {
        return true;
    }

    // avoid saving to session is start page is not valid or if it's
    // already in the request params
    if (isStartPageValid(requestPage)) {
        if (!requestPageInParams) {
            session.setAttribute(START_PAGE_SAVE_KEY, requestPage);
        }
        return true;
    }

    return false;
}

From source file:org.acegisecurity.ui.AbstractProcessingFilter.java

protected void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url)
        throws IOException {
    String finalUrl;// ww  w  . j a v a 2s  . c om
    if (!url.startsWith("http://") && !url.startsWith("https://")) {
        if (useRelativeContext) {
            finalUrl = url;
        } else {
            finalUrl = request.getContextPath() + url;
        }
    } else if (useRelativeContext) {
        // Calculate the relative URL from the fully qualifed URL, minus the
        // protocol and base context.
        int len = request.getContextPath().length();
        int index = url.indexOf(request.getContextPath()) + len;
        finalUrl = url.substring(index);
        if (finalUrl.length() > 1 && finalUrl.charAt(0) == '/') {
            finalUrl = finalUrl.substring(1);
        }
    } else {
        finalUrl = url;
    }

    Assert.isTrue(!response.isCommitted(),
            "Response already committed; the authentication mechanism must be able to modify buffer size");
    response.setBufferSize(bufferSize);
    response.sendRedirect(response.encodeRedirectURL(finalUrl));
}

From source file:lucee.runtime.net.rpc.server.RPCServer.java

/**
 * write a message to the response, set appropriate headers for content
 * type..etc./*from   ww  w .j a va  2  s  .  c  o  m*/
 * @param res   response
 * @param responseMsg message to write
 * @throws AxisFault
 * @throws IOException if the response stream can not be written to
 */
private void sendResponseX(String contentType, HttpServletResponse res, Message responseMsg)
        throws AxisFault, IOException {
    if (responseMsg == null) {
        res.setStatus(HttpServletResponse.SC_NO_CONTENT);
        if (isDebug) {
            log.debug("NO AXIS MESSAGE TO RETURN!");
        }
    } else {
        if (isDebug) {
            log.debug("Returned Content-Type:" + contentType);
        }

        try {

            res.setContentType(contentType);
            responseMsg.writeTo(res.getOutputStream());
        } catch (SOAPException e) {
            logException(e);
        }
    }

    if (!res.isCommitted()) {
        res.flushBuffer(); // Force it right now.
    }
}

From source file:org.sakaiproject.nakamura.cluster.ClusterTrackingServiceImpl.java

/**
 * Track a user, called from a filter, this will update the central cache for the cookie
 * and set the cookie if not present.//  w  w w .  j  a  v  a  2 s  .  c  o m
 *
 * @param request
 *          the http request oject.
 * @param response
 *          the http response object which will, if there is no cookie present, and the
 *          response is not committed, have the cookie set.
 */
public void trackClusterUser(HttpServletRequest request, HttpServletResponse response) {
    Cookie[] cookies = request.getCookies();
    String remoteUser = request.getRemoteUser();
    boolean tracking = false;
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie != null) {
                String cookieName = cookie.getName();
                if (cookieName.equals(SAKAI_TRACKING)) {
                    String trackingCookie = cookie.getValue();
                    if (isServerAlive(trackingCookie)) {
                        try {
                            pingTracking(trackingCookie, remoteUser);
                            tracking = true;
                        } catch (PingRemoteTrackingFailedException e) {
                            LOGGER.warn(e.getMessage());
                        }
                    }
                }
            }
        }
    }
    if (!tracking && !response.isCommitted()) {
        // the tracking cookie is the a sha1 hash of the thread, the server startup id and
        // time
        String seed = Thread.currentThread().getName() + ":" + componentStartTime + ":"
                + System.currentTimeMillis();
        String trackingCookie = Thread.currentThread().getName() + ":" + System.currentTimeMillis();
        try {
            trackingCookie = serverId + "-" + StringUtils.sha1Hash(seed);
        } catch (Exception e) {
            LOGGER.error("Failed to hash new cookie ", e);
        }

        Cookie cookie = new Cookie(SAKAI_TRACKING, trackingCookie);
        cookie.setMaxAge(-1);
        cookie.setComment("Cluster User Tracking");
        cookie.setPath("/");
        cookie.setVersion(0);
        response.addCookie(cookie);
        // we *do not* track cookies the first time, to avoid DOS on the cookie store.
        // pingTracking(trackingCookie, remoteUser);
    }

}

From source file:nl.armatiek.xslweb.web.servlet.XSLWebServlet.java

@SuppressWarnings("unchecked")
@Override/*from   w ww  .  ja  v  a 2s . co m*/
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    OutputStream respOs = resp.getOutputStream();
    WebApp webApp = null;
    try {
        webApp = (WebApp) req.getAttribute(Definitions.ATTRNAME_WEBAPP);
        if (webApp.isClosed()) {
            resp.resetBuffer();
            resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            resp.setContentType("text/html; charset=UTF-8");
            Writer w = new OutputStreamWriter(respOs, "UTF-8");
            w.write("<html><body><h1>Service temporarily unavailable</h1></body></html>");
            return;
        }
        executeRequest(webApp, req, resp, respOs);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        if (webApp != null && webApp.getDevelopmentMode()) {
            resp.setContentType("text/plain; charset=UTF-8");
            e.printStackTrace(new PrintStream(respOs));
        } else if (!resp.isCommitted()) {
            resp.resetBuffer();
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            resp.setContentType("text/html; charset=UTF-8");
            Writer w = new OutputStreamWriter(respOs, "UTF-8");
            w.write("<html><body><h1>Internal Server Error</h1></body></html>");
        }
    } finally {
        // Delete any registered temporary files:
        try {
            List<File> tempFiles = (List<File>) req.getAttribute(Definitions.ATTRNAME_TEMPFILES);
            if (tempFiles != null) {
                ListIterator<File> li = tempFiles.listIterator();
                while (li.hasNext()) {
                    File file;
                    if ((file = li.next()) != null) {
                        FileUtils.deleteQuietly(file);
                    }
                }
            }
        } catch (Exception se) {
            logger.error("Error deleting registered temporary files", se);
        }

        // Close any closeables:
        try {
            List<Closeable> closeables = (List<Closeable>) req.getAttribute("xslweb-closeables");
            if (closeables != null) {
                ListIterator<Closeable> li = closeables.listIterator(closeables.size());
                while (li.hasPrevious()) {
                    li.previous().close();
                }
            }
        } catch (Exception se) {
            logger.error("Could not close Closeable", se);
        }
    }
}

From source file:it.classhidra.core.controller.bsController.java

public static void service_Redirect(String redirectURI, ServletContext servletContext,
        HttpServletRequest request, HttpServletResponse response) {
    try {/*  w  ww .  jav a 2 s  .  c  o  m*/
        String id_rtype = (String) request.getAttribute(CONST_ID_REQUEST_TYPE);
        if (id_rtype == null)
            id_rtype = CONST_REQUEST_TYPE_FORWARD;
        if (id_rtype.equals(CONST_REQUEST_TYPE_FORWARD)) {
            if (!response.isCommitted())
                servletContext.getRequestDispatcher(redirectURI).forward(request, response);
            else
                servletContext.getRequestDispatcher(redirectURI).include(request, response);
        } else {
            servletContext.getRequestDispatcher(redirectURI).include(request, response);
        }

    } catch (Exception ex) {
        writeLog(request, "Controller generic redirect error. Session timeout.");
    }
}