Example usage for javax.servlet.http HttpServletResponse resetBuffer

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

Introduction

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

Prototype


public void resetBuffer();

Source Link

Document

Clears the content of the underlying buffer in the response without clearing headers or status code.

Usage

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();
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        objectMapper.writeValue(response.getOutputStream(), ImmutableMap.of("error", errorMessage));
    }/*from w  w  w.  j  av  a 2 s. c o m*/
    response.flushBuffer();
}

From source file:com.intel.rsa.podm.rest.filters.UrlValidationFilter.java

private void setErrorResponse(HttpServletResponse httpServletResponse, ErrorResponse error) {
    httpServletResponse.reset();/*from w ww . j a  va  2 s.co m*/
    httpServletResponse.resetBuffer();

    //we have to add since this request is outside our app
    httpServletResponse.addHeader("OData-Version", "4.0");
    httpServletResponse.addHeader("Cache-Control", "max-age=0");
    httpServletResponse.addHeader("Access-Control-Allow-Origin", "*");

    httpServletResponse.setCharacterEncoding(DEFAULT_ENCODING_HTTP);
    httpServletResponse.setContentType(MediaType.APPLICATION_JSON);
    httpServletResponse.setStatus(error.getErrorCode());

    try (PrintWriter responseWriter = httpServletResponse.getWriter()) {
        responseWriter.print(getJsonResponse(error));
        responseWriter.flush();
    } catch (IOException e) {
        logger.e("Unable to write response. Sending empty body response.", e);
    }
}

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

private void handleBadRequest(HttpServletResponse response, String errorMessage) throws IOException {
    if (!response.isCommitted()) {
        response.resetBuffer();
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        jsonMapper.writeValue(response.getOutputStream(), ImmutableMap.of("error", errorMessage));
    }//w ww .  j a  v a  2  s .c  o  m
    response.flushBuffer();
}

From source file:de.betterform.agent.web.servlet.XFormsErrorServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.reset();//w w w . j a va  2s . co  m
    response.resetBuffer();

    response.setContentType("text/html");
    PrintWriter writer = response.getWriter();
    writer.println(getHtmlhead(request.getContextPath()));
    writer.println(getHTML(request));
    writer.println(HTMLFOOT);
    writer.flush();
    response.getOutputStream().close();

}

From source file:com.zlfun.framework.excel.ExcelUtils.java

public static <T> void httpOutput(String name, Class<T> clazz, List<T> list, HttpServletRequest request,
        HttpServletResponse response) {
    try {/*from w w w  .  j av a2 s.c  om*/
        request.setCharacterEncoding("UTF-8");//request???
        String fileName = name;//??
        String contentType = "application/vnd.ms-excel";//?
        String recommendedName = new String(fileName.getBytes(), "iso_8859_1");//????
        response.setContentType(contentType);//?
        response.setHeader("Content-Disposition", "attachment; filename=" + recommendedName + "\"");//
        response.resetBuffer();
        //?
        ServletOutputStream sos = response.getOutputStream();
        write(name, clazz, list, sos);
        sos.flush();
        sos.close();
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(ExcelUtils.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ExcelUtils.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:ie.wombat.rt.fireeagle.CookieConsumer.java

/**
 * Handle an exception that occurred while processing an HTTP request.
 * Depending on the exception, either send a response, redirect the client
 * or propagate an exception./*w w  w.j a  va  2 s .  c om*/
 */
public static void handleException(Exception e, HttpServletRequest request, HttpServletResponse response,
        OAuthConsumer consumer) throws IOException, ServletException {
    if (e instanceof RedirectException) {
        RedirectException redirect = (RedirectException) e;
        String targetURL = redirect.getTargetURL();
        if (targetURL != null) {
            response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
            response.setHeader("Location", targetURL);
        }
    } else if (e instanceof OAuthProblemException) {
        OAuthProblemException p = (OAuthProblemException) e;
        String problem = p.getProblem();
        if (consumer != null && RECOVERABLE_PROBLEMS.contains(problem)) {
            try {
                CookieMap cookies = new CookieMap(request, response);
                OAuthAccessor accessor = newAccessor(consumer, cookies);
                getAccessToken(request, cookies, accessor);
                // getAccessToken(request, consumer,
                // new CookieMap(request, response));
            } catch (Exception e2) {
                handleException(e2, request, response, null);
            }
        } else {
            try {
                StringWriter s = new StringWriter();
                PrintWriter pw = new PrintWriter(s);
                e.printStackTrace(pw);
                pw.flush();
                p.setParameter("stack trace", s.toString());
            } catch (Exception rats) {
            }
            response.setStatus(p.getHttpStatusCode());
            response.resetBuffer();
            request.setAttribute("OAuthProblemException", p);
            request.getRequestDispatcher //
            ("/OAuthProblemException.jsp").forward(request, response);
        }
    } else if (e instanceof IOException) {
        throw (IOException) e;
    } else if (e instanceof ServletException) {
        throw (ServletException) e;
    } else if (e instanceof RuntimeException) {
        throw (RuntimeException) e;
    } else {
        throw new ServletException(e);
    }
}

From source file:fr.univlille2.ecm.platform.ui.web.auth.cas2.SecurityExceptionHandler.java

@Override
public void handleException(HttpServletRequest request, HttpServletResponse response, Throwable t)
        throws IOException, ServletException {

    @SuppressWarnings("deprecation")
    Throwable unwrappedException = unwrapException(t);
    log.debug("handleException#in");
    if (!ExceptionHelper.isSecurityError(unwrappedException)
            && !response.containsHeader(SSO_INITIAL_URL_REQUEST_KEY)) {
        super.handleException(request, response, t);
        return;/*w  w w.  j a  v a2s .c  om*/
    }

    Principal principal = request.getUserPrincipal();
    NuxeoPrincipal nuxeoPrincipal = null;
    if (principal instanceof NuxeoPrincipal) {
        nuxeoPrincipal = (NuxeoPrincipal) principal;
        // redirect to login than to requested page
        if (nuxeoPrincipal.isAnonymous()) {
            response.resetBuffer();

            String urlToReach = getURLToReach(request);
            log.debug(String.format("handleException#urlToReach#%s", urlToReach));
            Cookie cookieUrlToReach = new Cookie(NXAuthConstants.SSO_INITIAL_URL_REQUEST_KEY, urlToReach);
            cookieUrlToReach.setPath("/");
            cookieUrlToReach.setMaxAge(60);
            response.addCookie(cookieUrlToReach);
            log.debug(String.format("handleException#cookieUrlToReach#%s", cookieUrlToReach.getName()));
            if (!response.isCommitted()) {
                request.getRequestDispatcher(CAS_REDIRECTION_URL).forward(request, response);
            }
            FacesContext.getCurrentInstance().responseComplete();
        }
    }
    // go back to default handler
    super.handleException(request, response, t);
}

From source file:net.gplatform.sudoor.server.cors.CorsFilter.java

/**
 * Handles a CORS request that violates specification.
 * /*w  w  w  . j  a v a2 s .c o  m*/
 * @param request
 *            The {@link HttpServletRequest} object.
 * @param response
 *            The {@link HttpServletResponse} object.
 * @param filterChain
 *            The {@link FilterChain} object.
 */
private void handleInvalidCORS(final HttpServletRequest request, final HttpServletResponse response,
        final FilterChain filterChain) {
    String origin = request.getHeader(CorsFilter.REQUEST_HEADER_ORIGIN);
    String method = request.getMethod();
    String accessControlRequestHeaders = request.getHeader(REQUEST_HEADER_ACCESS_CONTROL_REQUEST_HEADERS);

    response.setContentType("text/plain");
    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
    response.resetBuffer();

    if (log.isDebugEnabled()) {
        // Debug so no need for i18n
        StringBuilder message = new StringBuilder("Invalid CORS request; Origin=");
        message.append(origin);
        message.append(";Method=");
        message.append(method);
        if (accessControlRequestHeaders != null) {
            message.append(";Access-Control-Request-Headers=");
            message.append(accessControlRequestHeaders);
        }
        log.debug(message.toString());
    }
}

From source file:com.ucap.uccc.cmis.impl.atompub.CmisAtomPubServlet.java

/**
 * Prints the error HTML page.//from w ww  .  j a v a2 s.co m
 */
protected void printError(Exception ex, HttpServletResponse response) {
    int statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    String exceptionName = "runtime";

    if (ex instanceof CmisRuntimeException) {
        LOG.error(ex.getMessage(), ex);
    } else if (ex instanceof CmisStorageException) {
        LOG.error(ex.getMessage(), ex);
        statusCode = getErrorCode((CmisStorageException) ex);
        exceptionName = ((CmisStorageException) ex).getExceptionName();
    } else if (ex instanceof CmisBaseException) {
        statusCode = getErrorCode((CmisBaseException) ex);
        exceptionName = ((CmisBaseException) ex).getExceptionName();
    } else if (ex instanceof IOException) {
        LOG.warn(ex.getMessage(), ex);
    } else {
        LOG.error(ex.getMessage(), ex);
    }

    if (response.isCommitted()) {
        LOG.warn("Failed to send error message to client. Response is already committed.", ex);
        return;
    }

    String message = ex.getMessage();
    if (!(ex instanceof CmisBaseException)) {
        message = "An error occurred!";
    }

    try {
        response.resetBuffer();
        response.setStatus(statusCode);
        response.setContentType("text/html");
        response.setCharacterEncoding(IOUtils.UTF8);

        PrintWriter pw = response.getWriter();

        pw.print("<html><head><title>Apache Chemistry OpenCMIS - " + exceptionName + " error</title>"
                + "<style><!--H1 {font-size:24px;line-height:normal;font-weight:bold;background-color:#f0f0f0;color:#003366;border-bottom:1px solid #3c78b5;padding:2px;} "
                + "BODY {font-family:Verdana,arial,sans-serif;color:black;font-size:14px;} "
                + "HR {color:#3c78b5;height:1px;}--></style></head><body>");
        pw.print("<h1>HTTP Status " + statusCode + " - <!--exception-->" + exceptionName
                + "<!--/exception--></h1>");
        pw.print("<p><!--message-->" + StringEscapeUtils.escapeHtml(message) + "<!--/message--></p>");

        String st = ExceptionHelper.getStacktraceAsString(ex);
        if (st != null) {
            pw.print("<hr noshade='noshade'/><!--stacktrace--><pre>\n" + st
                    + "\n</pre><!--/stacktrace--><hr noshade='noshade'/>");
        }

        pw.print("</body></html>");
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        try {
            response.sendError(statusCode, message);
        } catch (Exception en) {
            // there is nothing else we can do
        }
    }
}

From source file:com.ark.website.filter.CORSFilter.java

/**
 * Handles a CORS request that violates specification.
 * //  ww  w.j  a  v  a  2  s .  c  o m
 * @param request
 *            The {@link HttpServletRequest} object.
 * @param response
 *            The {@link HttpServletResponse} object.
 * @param filterChain
 *            The {@link FilterChain} object.
 * @throws IOException
 * @throws ServletException
 */
public void handleInvalidCORS(final HttpServletRequest request, final HttpServletResponse response,
        final FilterChain filterChain) {
    String origin = request.getHeader(CORSFilter.REQUEST_HEADER_ORIGIN);
    String method = request.getMethod();
    String accessControlRequestHeaders = request.getHeader(REQUEST_HEADER_ACCESS_CONTROL_REQUEST_HEADERS);

    String message = "Invalid CORS request; Origin=" + origin + ";Method=" + method;
    if (accessControlRequestHeaders != null) {
        message = message + ";Access-Control-Request-Headers=" + accessControlRequestHeaders;
    }
    response.setContentType("text/plain");
    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
    response.resetBuffer();

    log(message);
}