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.dbflute.saflute.web.servlet.filter.RequestLoggingFilter.java

protected void handle404NotFound(HttpServletRequest request, HttpServletResponse response,
        Request404NotFoundException notFoundEx) throws IOException {
    if (response.isCommitted()) {
        if (LOG.isDebugEnabled()) {
            String requestURI = request.getRequestURI();
            LOG.debug("*Cannot send error as '404 Not Found' because of already committed: path=" + requestURI);
        }// w w  w  . j a va2s . co m
        return; // cannot help it
    }
    if (LOG.isDebugEnabled()) {
        final String requestURI = request.getRequestURI();
        final StringBuilder sb = new StringBuilder();
        final Throwable nestEx = notFoundEx.getCause();
        sb.append("\n");
        sb.append(
                "/= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = *Manual 404 Not Found:\n");
        sb.append("...Sending error as '404 Not Found' manually\n");
        sb.append(" request: ").append(requestURI).append("\n");
        sb.append(" message: ").append(notFoundEx.getMessage()).append("\n");
        if (nestEx != null && !(nestEx instanceof Request404NotFoundException)) {
            sb.append(" nested:\n");
            sb.append("   ").append(nestEx.getClass().getName()).append("\n");
            sb.append("   ").append(nestEx.getMessage()).append("\n");
        }
        sb.append("= = = = = = = = = =/");
        final String msg = sb.toString();
        LOG.debug(msg);
    }
    try {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    } catch (IOException sendEx) {
        final String msg = "Failed to send error as '404 Not Found': " + sendEx.getMessage();
        if (errorLogging) {
            LOG.error(msg);
        } else {
            LOG.debug(msg);
        }
        return; // cannot help it
    }
}

From source file:org.jahia.bin.JahiaAdministration.java

/**
 * Display the login page, using doRedirect().
 *
 * @param request  Servlet request.//from w w w  .ja va2s  . co  m
 * @param response Servlet response.
 * @param session  Servlet session for the current user.
 */
private void displayLogin(HttpServletRequest request, HttpServletResponse response, HttpSession session)
        throws IOException, ServletException {
    if (!response.isCommitted()) {
        request.getRequestDispatcher(Login.getServletPath() + "?redirect="
                + URLEncoder.encode((request.getContextPath() + servletPath).replaceAll("//", "/"), "UTF-8"))
                .forward(request, response);
    } else {
        response.sendRedirect(response.encodeRedirectURL(Login.getServletPath() + "?redirect="
                + URLEncoder.encode((request.getContextPath() + servletPath).replaceAll("//", "/"), "UTF-8")));
    }
}

From source file:com.almende.eve.transport.http.AgentServlet.java

/**
 * Delete an agent usage: DELETE /servlet/agentId.
 * // ww w . j a v  a 2  s .c o  m
 * @param req
 *            the req
 * @param resp
 *            the resp
 * @throws ServletException
 *             the servlet exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
@Override
protected void doDelete(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    final String agentUrl = req.getRequestURI();
    String agentId;
    try {
        agentId = httpTransport.getAgentId(new URI(agentUrl));
    } catch (URISyntaxException e) {
        throw new ServletException(AGENTURLWARNING, e);
    }

    if (!handleSession(req, resp)) {
        if (!resp.isCommitted()) {
            resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }
        return;
    }
    if (agentId == null) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "No agentId found in url.");
        return;
    }

    try {
        host.deleteAgent(agentId);
        resp.getWriter().write("Agent " + agentId + " deleted");
    } catch (final Exception e) {
        throw new ServletException(e);
    }
}

From source file:com.denksoft.springstarter.util.TilesViewExtended.java

protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    MutableTilesContainer container = (MutableTilesContainer) TilesAccess.getContainer(getServletContext());

    log.info("There is no definition registered. Registering a new definition " + getBeanName());
    Definition definition = new Definition();

    Attribute attr = new Attribute();
    attr.setName("body");
    attr.setValue("/WEB-INF/jsp/" + getBeanName() + ".jsp");

    definition.addAttribute(attr);//w  w w. j  a v a2  s. c om
    definition.setExtends("rootLayout");
    definition.setName(getBeanName());

    container.register(definition, request, response);

    exposeModelAsRequestAttributes(model, request);
    JstlUtils.exposeLocalizationContext(request, this.jstlAwareMessageSource);
    //container.render(getUrl(), request, response);

    if (!response.isCommitted()) {
        // Tiles is going to use a forward, but some web containers (e.g. OC4J 10.1.3)
        // do not properly expose the Servlet 2.4 forward request attributes... However,
        // must not do this on Servlet 2.5 or above, mainly for GlassFish compatibility.
        ServletContext sc = getServletContext();
        if (sc.getMajorVersion() == 2 && sc.getMinorVersion() < 5) {
            WebUtils.exposeForwardRequestAttributes(request);
        }
    }

    container.render(getUrl(), new Object[] { request, response });
}

From source file:com.netspective.sparx.form.DialogContext.java

public void performDefaultRedirect(Writer writer, String redirect) throws IOException {
    if (!redirectAfterExecute)
        return;//from ww  w.  jav a  2 s  .c  o  m

    ServletRequest request = getRequest();
    String redirectToUrl = redirect != null ? redirect : request.getParameter(DEFAULT_REDIRECT_PARAM_NAME);
    if (redirectToUrl == null) {
        redirectToUrl = request.getParameter(dialog.getPostExecuteRedirectUrlParamName());
        if (redirectToUrl == null)
            redirectToUrl = getNextActionUrl(state.getReferer());
    }

    if (redirectDisabled || redirectToUrl == null) {
        writer.write("<p><b>Redirect is disabled</b>.");
        writer.write("<br><code>redirect</code> method parameter is <code>" + redirect + "</code>");
        writer.write("<br><code>redirect</code> URL parameter is <code>"
                + request.getParameter(DEFAULT_REDIRECT_PARAM_NAME) + "</code>");
        writer.write("<br><code>redirect</code> form field is <code>"
                + request.getParameter(dialog.getPostExecuteRedirectUrlParamName()) + "</code>");
        writer.write("<br><code>getNextActionUrl</code> method result is <code>" + getNextActionUrl(null)
                + "</code>");
        writer.write("<br><code>original referer</code> url is <code>" + state.getReferer() + "</code>");
        writer.write("<p><font color=red>Would have redirected to <code>" + redirectToUrl + "</code>.</font>");
        return;
    }

    HttpServletResponse response = (HttpServletResponse) getResponse();
    if (response.isCommitted())
        skin.renderRedirectHtml(writer, this, response.encodeRedirectURL(redirectToUrl));
    else
        sendRedirect(redirectToUrl);
}

From source file:helma.servlet.AbstractServletClient.java

void sendError(HttpServletResponse response, int code, String message) throws IOException {
    if (response.isCommitted()) {
        return;// ww w  .j  av  a  2 s  . c  o  m
    }
    response.reset();
    response.setStatus(code);
    response.setContentType("text/html");

    if (!"true".equalsIgnoreCase(getApplication().getProperty("suppressErrorPage"))) {
        Writer writer = response.getWriter();

        writer.write("<html><body><h3>");
        writer.write("Error in application ");
        try {
            writer.write(getApplication().getName());
        } catch (Exception besafe) {
            // ignore
        }
        writer.write("</h3>");
        writer.write(message);
        writer.write("</body></html>");
        writer.flush();
    }
}

From source file:net.siegmar.japtproxy.packages.RepoPackageFinder.java

/**
 * Fetches an object from a specific backend.
 *
 * @param requestedData  the requested data.
 * @param targetResource the target resource.
 * @param poolObject     the pool object.
 * @param res            the HttpServletResponse object
 * @return true if the requested object was send successfully.
 * @throws IOException is thrown if an I/O error occurs.
 *///from w w w  .  j a v a 2  s. co m
protected boolean handleBackend(final RequestedData requestedData, final URL targetResource,
        final PoolObject poolObject, final HttpServletResponse res) throws IOException {
    try {
        // Send and save data
        final boolean locallyCached = ioHandler.sendAndSave(requestedData, poolObject, targetResource, res);

        // If a new version was downloaded and if the configuration
        // specifies a max-version parameter, remove old versions
        if (!locallyCached && configuration.getMaxVersions() != null) {
            packagePool.removeOldPackages(poolObject);
        }

        return true;
    } catch (final ResourceUnavailableException e) {
        LOG.info("Resource '{}' not found", targetResource);
    } catch (final IOException e) {
        LOG.warn(String.format("IOException while getting data from '%s'", targetResource), e);

        if (res.isCommitted()) {
            LOG.info("IOException occured but headers are already sent. Have to rethrow exception", e);
            throw e;
        }
        res.reset();
    } catch (final InitializationException e) {
        LOG.warn("Resource '{}' could not be fetched", targetResource, e);
    }

    return false;
}

From source file:org.springframework.security.ui.ntlm.NtlmAuthenticationFilterEntryPoint.java

/**
 * Sends an NTLM challenge to the browser requiring authentication. The
 * WWW-Authenticate header is populated with the appropriate information
 * during the negotiation lifecycle by calling the getMessage() method
 * from an NTLM-specific subclass of {@link NtlmBaseException}:
 * <p>/*from   w w  w.  j a va  2  s .  c  o m*/
 * <ul>
 * <li>{@link NtlmBeginHandshakeException}: NTLM
 * <li>{@link NtlmType2MessageException}: NTLM &lt;base64-encoded type-2-message&gt;
 * </ul>
 *
 * If the {@link AuthenticationException} is not a subclass of
 * {@link NtlmBaseException}, then redirect the user to the authentication
 * failure URL.
 *
 * @param request The {@link HttpServletRequest} object.
 * @param response Then {@link HttpServletResponse} object.
 * @param authException Either {@link NtlmBeginHandshakeException},
 *                   {@link NtlmType2MessageException}, or
 *                   {@link AuthenticationException}
 */
public void commence(final HttpServletRequest request, final HttpServletResponse response,
        final AuthenticationException authException) throws IOException, ServletException {
    final HttpServletResponse resp = response;

    if (authException instanceof NtlmBaseException) {
        if (authException instanceof NtlmType2MessageException) {
            ((NtlmType2MessageException) authException).preserveAuthentication();
        }
        resp.setHeader("WWW-Authenticate", authException.getMessage());
        resp.setHeader("Connection", "Keep-Alive");
        resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        resp.setContentLength(0);
        resp.flushBuffer();

        LOGGER.debug("NTLM auth exception: ", authException);
        return;
    }

    if (authenticationFailureUrl == null) {
        if (!response.isCommitted()) {
            (response).sendError(HttpServletResponse.SC_FORBIDDEN, authException.getMessage());
        }
    } else {
        String url = authenticationFailureUrl;
        if (!url.startsWith("http://") && !url.startsWith("https://")) {
            url = (request).getContextPath() + url;
        }

        resp.sendRedirect(resp.encodeRedirectURL(url));
    }
}

From source file:org.nema.medical.mint.server.controller.TypesController.java

@RequestMapping("/types/{type}")
public String typeEntry(@PathVariable("type") final String type, final HttpServletRequest req,
        final HttpServletResponse res, final ModelMap map) {
    if (StringUtils.isBlank(type)) {
        res.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        map.put("error_msg", "must specify type");
        return "error";
    }/*from  ww  w.  j av a2 s  . com*/

    //In case of file extension, take off .xml for name
    final String typeName = type.endsWith(".xml") ? type.substring(0, ".xml".length()) : type;
    final File typeFile = availableTypeFiles.get(typeName);

    if (typeFile.exists() && typeFile.canRead()) {
        try {
            res.setContentType("text/xml");
            res.setContentLength(Long.valueOf(typeFile.length()).intValue());
            res.setBufferSize(fileResponseBufferSize);
            Utils.streamFile(typeFile, res.getOutputStream(), fileStreamBufferSize);
        } catch (final IOException e) {
            if (!res.isCommitted()) {
                res.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                map.put("error_msg", "Failed to stream type definition document");
                return "error";
            }
        }
    } else {
        res.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        map.put("error_msg", "Type specified does not exist");
        return "error";
    }

    return null;
}