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:com.liferay.portal.struts.StrutsUtil.java

public static void forward(String uri, ServletContext ctx, HttpServletRequest req, HttpServletResponse res)
        throws ServletException {

    if (!res.isCommitted()) {
        String path = Constants.TEXT_HTML_DIR + uri;
        if (BrowserSniffer.is_wml(req)) {
            path = Constants.TEXT_WML_DIR + uri;
        }/* w  w  w .  j a va  2 s . c om*/

        ServletContext portalCtx = ctx.getContext(PropsUtil.get(PropsUtil.PORTAL_CTX));

        if (portalCtx == null) {
            portalCtx = ctx;
        }

        RequestDispatcher rd = portalCtx.getRequestDispatcher(path);

        try {
            rd.forward(req, res);
        } catch (IOException ioe1) {
            Logger.error(StrutsUtil.class, ioe1.getMessage(), ioe1);
        } catch (ServletException se1) {
            req.setAttribute(PageContext.EXCEPTION, se1.getRootCause());

            String errorPath = Constants.TEXT_HTML_DIR + Constants.COMMON_ERROR;
            if (BrowserSniffer.is_wml(req)) {
                path = Constants.TEXT_WML_DIR + Constants.COMMON_ERROR;
            }

            rd = portalCtx.getRequestDispatcher(errorPath);

            try {
                rd.forward(req, res);
            } catch (IOException ioe2) {
                Logger.error(StrutsUtil.class, ioe2.getMessage(), ioe2);
            } catch (ServletException se2) {
                throw se2;
            }
        }
    } else {
        _log.warn(uri + " is already committed");
    }
}

From source file:org.jumpmind.symmetric.web.ServletUtils.java

/**
 * Because you can't send an error when the response is already committed,
 * this helps to avoid unnecessary errors in the logs.
 * /*from   w  w w. j  a  v  a  2s .  com*/
 * @param resp
 * @param statusCode
 * @param message
 *            a message to put in the body of the response
 * @return true if the error could be sent to the response
 * @throws IOException
 */
public static boolean sendError(final HttpServletResponse resp, final int statusCode, final String message)
        throws IOException {
    boolean retVal = false;
    if (!resp.isCommitted()) {
        resp.sendError(statusCode, message);
        retVal = true;
    }
    return retVal;
}

From source file:org.squale.welcom.outils.excel.ExcelFactory.java

/**
 * @param exceldata les datas/*ww w .j  a  va 2 s  .c om*/
 * @param response la response
 * @param attachementFileName le nom du fichier
 * @param engine l'engine
 * @throws ExcelGenerateurException exception pouvant etre levee
 */
public static void generateExcelToHTTPResponse(final ExcelData exceldata, final HttpServletResponse response,
        final String attachementFileName, final ExcelEngine engine) throws ExcelGenerateurException {
    try {
        if (response.isCommitted()) {
            throw new ExcelGenerateurException(
                    "Le header a deja t envoy ... impossible d'ajouter le content-disposition");
        }
        final OutputStream os = response.getOutputStream();
        response.setContentType(CONTENT_TYPE);
        if (!GenericValidator.isBlankOrNull(attachementFileName)) {
            response.setHeader("Content-Disposition", "attachment;filename=" + attachementFileName + ";");
        }
        generateExcel(exceldata, os, engine);
    } catch (final IOException e) {
        throw new ExcelGenerateurException(e.getMessage(), e);
    }
}

From source file:org.b3log.latke.servlet.HTTPRequestDispatcher.java

/**
 * Dispatches with the specified context.
 * //from  ww w  .  j  a v  a  2s. c o m
 * @param context the specified specified context
 * @throws ServletException servlet exception
 * @throws IOException io exception 
 */
public static void dispatch(final HTTPRequestContext context) throws ServletException, IOException {
    final HttpServletRequest request = context.getRequest();

    String requestURI = (String) request.getAttribute(Keys.HttpRequest.REQUEST_URI);

    if (Strings.isEmptyOrNull(requestURI)) {
        requestURI = request.getRequestURI();
    }

    String method = (String) request.getAttribute(Keys.HttpRequest.REQUEST_METHOD);

    if (Strings.isEmptyOrNull(method)) {
        method = request.getMethod();
    }

    LOGGER.log(Level.FINER, "Request[requestURI={0}, method={1}]", new Object[] { requestURI, method });

    try {
        final Object processorMethodRet = RequestProcessors.invoke(requestURI, Latkes.getContextPath(), method,
                context);
    } catch (final Exception e) {
        final String exceptionTypeName = e.getClass().getName();

        LOGGER.log(Level.FINER,
                "Occured error while processing request[requestURI={0}, method={1}, exceptionTypeName={2}, errorMsg={3}]",
                new Object[] { requestURI, method, exceptionTypeName, e.getMessage() });
        if ("com.google.apphosting.api.ApiProxy$OverQuotaException".equals(exceptionTypeName)) {
            PageCaches.removeAll();

            context.getResponse().sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            return;
        }

        throw new ServletException(e);
    } catch (final Error e) {
        final Runtime runtime = Runtime.getRuntime();

        LOGGER.log(Level.FINER, "Memory status[total={0}, max={1}, free={2}]",
                new Object[] { runtime.totalMemory(), runtime.maxMemory(), runtime.freeMemory() });

        LOGGER.log(Level.SEVERE, e.getMessage(), e);

        throw e;
    }

    // XXX: processor method ret?

    final HttpServletResponse response = context.getResponse();

    if (response.isCommitted()) { // Sends rdirect or send error
        final PrintWriter writer = response.getWriter();

        writer.flush();
        writer.close();

        return;
    }

    AbstractHTTPResponseRenderer renderer = context.getRenderer();

    if (null == renderer) {
        renderer = new HTTP404Renderer();
    }

    renderer.render(context);
}

From source file:io.druid.server.AsyncQueryForwardingServlet.java

private static void handleException(HttpServletResponse response, ObjectMapper objectMapper,
        Exception exception) throws IOException {
    if (!response.isCommitted()) {
        final String errorMessage = exception.getMessage() == null ? "null exception" : exception.getMessage();

        response.resetBuffer();//  w w  w  .  j a  va 2 s .c  o m
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        objectMapper.writeValue(response.getOutputStream(), ImmutableMap.of("error", errorMessage));
    }
    response.flushBuffer();
}

From source file:org.tuckey.web.filters.urlrewrite.RequestProxy.java

/**
 * This method performs the proxying of the request to the target address.
 *
 * @param target     The target address. Has to be a fully qualified address. The request is send as-is to this address.
 * @param hsRequest  The request data which should be send to the
 * @param hsResponse The response data which will contain the data returned by the proxied request to target.
 * @throws java.io.IOException Passed on from the connection logic.
 */// w  w w  .ja v a 2s. c  om
public static void execute(final String target, final HttpServletRequest hsRequest,
        final HttpServletResponse hsResponse) throws IOException {
    if (log.isInfoEnabled()) {
        log.info("execute, target is " + target);
        log.info("response commit state: " + hsResponse.isCommitted());
    }

    if (StringUtils.isBlank(target)) {
        log.error("The target address is not given. Please provide a target address.");
        return;
    }

    log.info("checking url");
    final URL url;
    try {
        url = new URL(target);
    } catch (MalformedURLException e) {
        log.error("The provided target url is not valid.", e);
        return;
    }

    log.info("seting up the host configuration");

    final HostConfiguration config = new HostConfiguration();

    ProxyHost proxyHost = getUseProxyServer((String) hsRequest.getAttribute("use-proxy"));
    if (proxyHost != null)
        config.setProxyHost(proxyHost);

    final int port = url.getPort() != -1 ? url.getPort() : url.getDefaultPort();
    config.setHost(url.getHost(), port, url.getProtocol());

    if (log.isInfoEnabled())
        log.info("config is " + config.toString());

    final HttpMethod targetRequest = setupProxyRequest(hsRequest, url);
    if (targetRequest == null) {
        log.error("Unsupported request method found: " + hsRequest.getMethod());
        return;
    }

    //perform the reqeust to the target server
    final HttpClient client = new HttpClient(new SimpleHttpConnectionManager());
    if (log.isInfoEnabled()) {
        log.info("client state" + client.getState());
        log.info("client params" + client.getParams().toString());
        log.info("executeMethod / fetching data ...");
    }

    final int result;
    if (targetRequest instanceof EntityEnclosingMethod) {
        final RequestProxyCustomRequestEntity requestEntity = new RequestProxyCustomRequestEntity(
                hsRequest.getInputStream(), hsRequest.getContentLength(), hsRequest.getContentType());
        final EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) targetRequest;
        entityEnclosingMethod.setRequestEntity(requestEntity);
        result = client.executeMethod(config, entityEnclosingMethod);

    } else {
        result = client.executeMethod(config, targetRequest);
    }

    //copy the target response headers to our response
    setupResponseHeaders(targetRequest, hsResponse);

    InputStream originalResponseStream = targetRequest.getResponseBodyAsStream();
    //the body might be null, i.e. for responses with cache-headers which leave out the body
    if (originalResponseStream != null) {
        OutputStream responseStream = hsResponse.getOutputStream();
        copyStream(originalResponseStream, responseStream);
    }

    log.info("set up response, result code was " + result);
}

From source file:org.apache.myfaces.tomahawk.util.ErrorPageWriter.java

public static void handleThrowable(FacesContext facesContext, Throwable ex)
        throws ServletException, IOException {

    prepareExceptionStack(ex);//from   w  w  w  .j av a 2  s .  com

    Object response = facesContext.getExternalContext().getResponse();
    if (response instanceof HttpServletResponse) {
        HttpServletResponse httpResp = (HttpServletResponse) response;
        if (!httpResp.isCommitted()) {
            httpResp.reset();
            httpResp.setContentType("text/html; charset=UTF-8");
            Writer writer = httpResp.getWriter();

            debugHtml(writer, facesContext, ex);

            log.error("An exception occurred", ex);
        } else {
            throwException(ex);
        }
    } else {
        throwException(ex);
    }
}

From source file:org.apache.myfaces.tomahawk.util.ErrorPageWriter.java

public static void handleExceptionList(FacesContext facesContext, List exceptionList)
        throws ServletException, IOException {
    for (int i = 0; i < exceptionList.size(); i++) {
        prepareExceptionStack((Exception) exceptionList.get(i));
    }/*  w  w  w. j  a v a  2s  .c om*/

    Object response = facesContext.getExternalContext().getResponse();
    if (response instanceof HttpServletResponse) {
        HttpServletResponse httpResp = (HttpServletResponse) response;
        if (!httpResp.isCommitted()) {
            httpResp.reset();
            httpResp.setContentType("text/html; charset=UTF-8");
            Writer writer = httpResp.getWriter();

            debugHtml(writer, facesContext, exceptionList);

            for (int i = 0; i < exceptionList.size(); i++) {
                log.error("An exception occurred", (Exception) exceptionList.get(i));
            }
        } else {
            throwException((Exception) exceptionList.get(0));
        }
    } else {
        throwException((Exception) exceptionList.get(0));
    }
}

From source file:com.fluidops.iwb.server.HybridSearchServlet.java

/**
 * Send the specified error message to the client (if the connection is
 * still open).//from   ww  w  .ja  v a 2s. c o  m
 * 
 * @param resp
 * @param errorCode
 * @param message
 */
protected static void error(HttpServletResponse resp, int errorCode, String message) {

    try {
        log.info("Error (" + errorCode + "): " + message);
        if (!resp.isCommitted())
            resp.sendError(errorCode, message);
    } catch (IllegalStateException e) {
        // should never occur
        log.warn("Error message could not be send. Stream is committed: " + message);
    } catch (IOException e) {
        log.error("Error message could not be sent", e);
    }
}

From source file:org.pentaho.platform.web.http.api.resources.XactionUtil.java

public static String postExecute(IRuntimeContext runtime, boolean debugMessages, boolean doWrapper,
        IOutputHandler outputHandler, Map<String, IParameterProvider> parameterProviders,
        HttpServletRequest request, HttpServletResponse response, List<?> messages) throws Exception {
    StringBuffer buffer = new StringBuffer();

    boolean hasResponse = outputHandler.isResponseExpected();
    IContentItem responseContentItem = outputHandler.getOutputContentItem(IOutputHandler.RESPONSE,
            IOutputHandler.CONTENT, null, null);

    boolean success = (runtime != null && runtime.getStatus() == IRuntimeContext.RUNTIME_STATUS_SUCCESS);
    boolean printSuccess = (runtime != null) && success && (!hasResponse || debugMessages);
    boolean printError = (runtime != null) && !success && !response.isCommitted();

    if (printSuccess || printError) {
        final String htmlMimeType = "text/html"; //$NON-NLS-1$
        responseContentItem.setMimeType(htmlMimeType);
        response.setContentType(htmlMimeType);
        IMessageFormatter formatter = PentahoSystem.get(IMessageFormatter.class,
                PentahoSessionHolder.getSession());

        if (printSuccess) {
            formatter.formatSuccessMessage(htmlMimeType, runtime, buffer, debugMessages, doWrapper);
        } else {/*from   ww w .  ja v a  2 s  . c  o m*/
            response.resetBuffer();
            formatter.formatFailureMessage(htmlMimeType, runtime, buffer, messages);
        }
    }
    return buffer.toString();
}