Example usage for javax.servlet.http HttpServletResponse reset

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

Introduction

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

Prototype

public void reset();

Source Link

Document

Clears any data that exists in the buffer as well as the status code, headers.

Usage

From source file:com.glaf.oa.reports.web.springmvc.OAReportController.java

private void saveWorkbook(Workbook workBook, HttpServletResponse response, String targetName) {
    OutputStream os = null;/*  w  w  w. j  a  va2 s  .com*/
    try {
        response.reset(); // ???
        response.setHeader("content-disposition", "attachment; filename=" + targetName);
        response.setContentType("application/msexcel");
        os = response.getOutputStream();
        if (os != null) {
            workBook.write(os);
        }

    } catch (FileNotFoundException e) {
        logger.error("function saveWorkbook error:" + e.getMessage());
    } catch (IOException e) {
        logger.error("function saveWorkbook error:" + e.getMessage());
    } finally {
        try {
            if (os != null) {
                os.flush();
                os.close();
            }
        } catch (IOException e) {
            logger.error("function saveWorkbook error:" + e.getMessage());
        }

    }

}

From source file:org.wings.session.SessionServlet.java

/**
 * This method is called, whenever a Resource is requested whose
 * name is not known within this session.
 *
 * @param req the causing HttpServletRequest
 * @param res the HttpServletResponse of this request
 *///from   w w  w  .  ja v a 2s.  co m
protected void handleUnknownResourceRequested(HttpServletRequest req, HttpServletResponse res)
        throws IOException {
    //        res.setStatus(HttpServletResponse.SC_NOT_FOUND);
    //        res.setContentType("text/html");
    //        res.getOutputStream().println("<h1>404 Not Found</h1>Unknown Resource Requested: " + req.getPathInfo());
    res.reset();
    res.sendError(HttpServletResponse.SC_NOT_FOUND, req.getPathInfo());
}

From source file:org.sakaiproject.signup.tool.jsf.SignupUIBaseBean.java

/**
 * Send a warning message to user about failed ICS file generation
 * @param fileName// www . ja  v a  2  s  .  com
 * @param warningMsg
 */
protected void sendDownloadWarning(String fileName, String warningMsg) {

    FacesContext fc = FacesContext.getCurrentInstance();
    ServletOutputStream out = null;

    try {
        HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();

        response.reset();
        response.setHeader("Pragma", "public");
        response.setHeader("Cache-Control", "public, must-revalidate, post-check=0, pre-check=0, max-age=0");
        response.setContentType("text/plain");
        response.setHeader("Content-disposition", "attachment; filename=" + fileName);

        out = response.getOutputStream();
        warningMsg = warningMsg != null ? warningMsg : "Missing Scheduler tool on site";
        out.print(warningMsg);

        out.flush();
    } catch (IOException ex) {
        logger.warn("Error generating file for download:" + ex.getMessage());
    } finally {
        try {
            out.close();
        } catch (Exception e) {
            //do nothing;
        }
    }
    fc.responseComplete();

}

From source file:org.sakaiproject.signup.tool.jsf.SignupUIBaseBean.java

/**
 * Send a file for download. /*www  . ja  va 2 s . c om*/
 * 
 * @param filePath
 * 
 */
protected void sendDownload(String filePath, String mimeType) {

    FacesContext fc = FacesContext.getCurrentInstance();
    ServletOutputStream out = null;
    FileInputStream in = null;

    String filename = StringUtils.substringAfterLast(filePath, File.separator);

    try {
        HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();

        response.reset();
        response.setHeader("Pragma", "public");
        response.setHeader("Cache-Control", "public, must-revalidate, post-check=0, pre-check=0, max-age=0");
        response.setContentType(mimeType);
        response.setHeader("Content-disposition", "attachment; filename=" + filename);

        in = FileUtils.openInputStream(new File(filePath));
        out = response.getOutputStream();

        IOUtils.copy(in, out);

        out.flush();
    } catch (IOException ex) {
        logger.warn("Error generating file for download:" + ex.getMessage());
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }
    fc.responseComplete();

}

From source file:com.aurel.track.json.JSONUtility.java

public static void prepareServletResponseJSON(HttpServletResponse httpServletResponse,
        boolean jsonContentType) {
    try {//from  w w w .j  a  va2  s  . c o m
        httpServletResponse.reset();
        httpServletResponse.setCharacterEncoding("UTF-8");
    } catch (Exception e) {
        //when the <s:action/> is present on the jsp
        //(mainly getting root nodes the same response object is used, and second time it can't be reseted)
    }
    if (jsonContentType) {
        httpServletResponse.setContentType("application/json");
    } else {
        httpServletResponse.setContentType("text/html");
    }
    //httpServletResponse.setContentType("text/javascript");
    DownloadUtil.prepareCacheControlHeader(ServletActionContext.getRequest(), httpServletResponse);
    /*DetectBrowser dtb = new DetectBrowser();
    dtb.setRequest(ServletActionContext.getRequest());
    // Workaround for a IE bug
    if (dtb.getIsIE()) {
       httpServletResponse.setHeader("Cache-Control", "private");
       httpServletResponse.addHeader("Expires", "0");
    } else {
       httpServletResponse.setHeader("Cache-Control", "no-cache");
    }*/
}

From source file:no.sesat.search.http.filters.SiteLocatorFilter.java

/** Will redirect to correct (search-config) url for resources (css,images, javascript).
 *
 * @param request The servlet request we are processing
 * @param r The servlet response// w  w  w .  j  a  va 2  s. c  om
 * @param chain The filter chain we are processing
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 */
@Override
public void doFilter(final ServletRequest request, final ServletResponse r, final FilterChain chain)
        throws IOException, ServletException {

    LOG.trace("doFilter(..)");

    final StopWatch stopWatch = new StopWatch();
    stopWatch.start();

    final ServletResponse response = r instanceof HttpServletResponse
            ? new AccessLogResponse((HttpServletResponse) r)
            : r;

    try {
        if (request instanceof HttpServletRequest) {
            final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            final HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            if (httpServletRequest.getRequestURI().contains(CONFIGURATION_RESOURCE)) {
                /* We are looping, looking for a site search which does not exsist */
                LOG.info("We are looping, looking for a site search which does not exist");
                httpServletResponse.reset();
                httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
        }

        doBeforeProcessing(request, response);
        logAccessRequest(request);

        if (request instanceof HttpServletRequest) {

            final HttpServletRequest req = (HttpServletRequest) request;
            final HttpServletResponse res = (HttpServletResponse) response;
            final Site site = (Site) req.getAttribute(Site.NAME_KEY);
            final String uri = req.getRequestURI();
            final String resource = uri;
            final String rscDir = resource != null && resource.indexOf('/', 1) >= 0
                    ? resource.substring(0, resource.indexOf('/', 1) + 1)
                    : null;

            if (isAccessAllowed(req)) {

                if (rscDir != null && EXTERNAL_DIRS.contains(rscDir)) {

                    // This URL does not belong to search-portal
                    final String url = FindResource.find(site, resource);

                    if (url != null) {
                        // Cache the client-resource redirects on a short (session-equivilant) period
                        res.setHeader("Cache-Control", "Public");
                        res.setDateHeader("Expires", System.currentTimeMillis() + 1000 * 60 * 10); // ten minutes
                        // send the redirect to where the resource really resides
                        res.sendRedirect(url);
                        LOG.trace(resource + DEBUG_REDIRECTING_TO + url);

                    } else if (resource.startsWith(PUBLISH_DIR)) {
                        // XXX Why do we avoid sending 404 for publish resources?

                        res.sendError(HttpServletResponse.SC_NOT_FOUND);

                        if (resource.endsWith(".css")) {
                            LOG.info(ERR_NOT_FOUND + resource);
                        } else {
                            LOG.error(ERR_NOT_FOUND + resource);
                        }
                    }

                } else {
                    doChainFilter(chain, request, response);
                }

            } else {
                // Forbidden client
                res.sendError(HttpServletResponse.SC_FORBIDDEN);
            }

        } else {
            doChainFilter(chain, request, response);
        }

        doAfterProcessing(request, response);

    } catch (Exception e) {
        // Don't let anything through without logging it.
        //  Otherwise it ends in a different logfile.
        LOG.error(ERR_UNCAUGHT_RUNTIME_EXCEPTION);
        for (Throwable t = e; t != null; t = t.getCause()) {
            LOG.error(t.getMessage(), t);
        }
        throw new ServletException(e);

    } finally {
        logAccessResponse(request, response, stopWatch);
    }

}

From source file:org.orderofthebee.addons.support.tools.share.LogFileHandler.java

protected void handleLogZipRequest(final List<String> filePaths, final HttpServletRequest req,
        final HttpServletResponse res, final Map<String, Object> model) throws IOException {
    try {//from   w w w .ja  v a2s .c o m
        final List<File> files = LogFileHandler.validateFilePaths(filePaths);
        final File logFileZip = TempFileProvider.createTempFile("ootbee-support-tools-logFiles", "zip");
        try {
            this.createZip(files, logFileZip);

            this.contentStreamer.streamContent(req, res, logFileZip, logFileZip.lastModified(), false,
                    "log-files.zip", model, "application/zip");
        } finally {
            // eager cleanup
            if (!logFileZip.delete()) {
                logFileZip.deleteOnExit();
            }
        }
    } catch (final WebScriptException wsex) {
        if (!res.isCommitted()) {
            res.reset();
            res.sendError(wsex.getStatus(), wsex.getMessage());
        } else {
            LOGGER.info("Could not send error via committed response", wsex);
        }
    }
}

From source file:com.iyonger.apm.web.controller.PerfTestController.java

/**
 * Show the given log for the perf test having the given id.
 *
 * @param id       test id/*from ww  w  .j a v  a 2  s  . c om*/
 * @param path     path in the log folder
 * @param response response
 */
@RequestMapping(value = "/{id}/show_log/**")
public void showLog(@PathVariable("id") long id, @RemainedPath String path, HttpServletResponse response) {
    getOneWithPermissionCheck(getCurrentUser(), id, false);
    File targetFile = perfTestService.getLogFile(id, path);
    response.reset();
    response.setContentType("text/plain");
    response.setCharacterEncoding("UTF-8");
    FileInputStream fileInputStream = null;
    try {
        fileInputStream = new FileInputStream(targetFile);
        ServletOutputStream outputStream = response.getOutputStream();
        if (FilenameUtils.isExtension(targetFile.getName(), "zip")) {
            // Limit log view to 1MB
            outputStream.println(" Only the last 1MB of a log shows.\n");
            outputStream
                    .println("==========================================================================\n\n");
            LogCompressUtils.decompress(fileInputStream, outputStream, 1 * 1024 * 1204);
        } else {
            IOUtils.copy(fileInputStream, outputStream);
        }
    } catch (Exception e) {
        CoreLogger.LOGGER.error("Error while processing log. {}", targetFile, e);
    } finally {
        IOUtils.closeQuietly(fileInputStream);
    }
}

From source file:org.alfresco.web.app.Application.java

/**
 * Handles error conditions detected by servlets.
 * /*w w  w . jav a  2s  .c o  m*/
 * @param servletContext
 *           The servlet context
 * @param request
 *           The HTTP request
 * @param response
 *           The HTTP response
 * @param messageKey
 *           the resource bundle key for the error mesage
 * @param statusCode
 *           the status code to set on the response
 * @param logger
 *           The logger
 * @throws IOException
 *            Signals that an I/O exception has occurred.
 * @throws ServletException
 *            the servlet exception
 */
public static void handleSystemError(ServletContext servletContext, HttpServletRequest request,
        HttpServletResponse response, String messageKey, int statusCode, Log logger)
        throws IOException, ServletException {
    // get the error bean from the session and set the error that occurred.
    HttpSession session = request.getSession();
    ErrorBean errorBean = (ErrorBean) session.getAttribute(ErrorBean.ERROR_BEAN_NAME);
    if (errorBean == null) {
        errorBean = new ErrorBean();
        session.setAttribute(ErrorBean.ERROR_BEAN_NAME, errorBean);
    }
    errorBean.setErrorMessageKey(messageKey);
    errorBean.setReturnPage(null);

    // try and find the configured error page
    boolean errorShown = false;
    String errorPage = getErrorPage(servletContext);

    if (errorPage != null) {
        if (logger.isDebugEnabled())
            logger.debug("An error has occurred, forwarding to error page: " + errorPage);

        if (!response.isCommitted()) {
            errorShown = true;
            response.reset();
            response.setStatus(statusCode);
            response.setContentType(MimetypeMap.MIMETYPE_HTML);
            response.setCharacterEncoding("utf-8");
            servletContext.getRequestDispatcher(errorPage).include(request, response);
        } else {
            if (logger.isDebugEnabled())
                logger.debug("Response is already committed, re-throwing error");
        }
    } else {
        if (logger.isDebugEnabled())
            logger.debug("No error page defined, re-throwing error");
    }

    // if we could not show the error page for whatever reason, re-throw the error
    if (!errorShown) {
        throw new ServletException(getMessage(session, messageKey));
    }
}

From source file:password.pwm.http.servlet.resource.ResourceFileServlet.java

protected void processAction(final PwmRequest pwmRequest)
        throws ServletException, IOException, PwmUnrecoverableException {
    if (pwmRequest.getMethod() != HttpMethod.GET) {
        throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_SERVICE_NOT_AVAILABLE,
                "unable to process resource request for request method " + pwmRequest.getMethod()));
    }//from   w w  w  .  j a v a  2s . c  o m

    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final ResourceServletService resourceService = pwmApplication.getResourceServletService();
    final ResourceServletConfiguration resourceConfiguration = resourceService
            .getResourceServletConfiguration();

    final String requestURI = stripNonceFromURI(resourceConfiguration,
            figureRequestPathMinusContext(pwmRequest.getHttpServletRequest()));

    try {
        if (handleEmbeddedURIs(pwmApplication, requestURI, pwmRequest.getPwmResponse().getHttpServletResponse(),
                resourceConfiguration)) {
            return;
        }
    } catch (Exception e) {
        LOGGER.error(pwmRequest, "unexpected error detecting/handling special request uri: " + e.getMessage());
    }

    final FileResource file;
    try {
        file = resolveRequestedFile(this.getServletContext(), requestURI, resourceConfiguration);
    } catch (PwmUnrecoverableException e) {
        pwmRequest.getPwmResponse().getHttpServletResponse()
                .sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        try {
            pwmRequest.debugHttpRequestToLog("returning HTTP 500 status");
        } catch (PwmUnrecoverableException e2) {
            /* noop */ }
        return;
    }

    if (file == null || !file.exists()) {
        pwmRequest.getPwmResponse().getHttpServletResponse().sendError(HttpServletResponse.SC_NOT_FOUND);
        try {
            pwmRequest.debugHttpRequestToLog("returning HTTP 404 status");
        } catch (PwmUnrecoverableException e) {
            /* noop */ }
        return;
    }

    // Get content type by file name and set default GZIP support and content disposition.
    String contentType = getMimeType(file.getName());
    boolean acceptsGzip = false;

    // If content type is unknown, then set the default value.
    // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
    // To add new content types, add new mime-mapping entry in web.xml.
    if (contentType == null) {
        contentType = "application/octet-stream";
    }

    // If content type is text, then determine whether GZIP content encoding is supported by
    // the browser and expand content type with the one and right character encoding.
    if (resourceConfiguration.isEnableGzip()) {
        if (contentType.startsWith("text") || contentType.contains("javascript")) {
            final String acceptEncoding = pwmRequest.readHeaderValueAsString(HttpHeader.Accept_Encoding);
            acceptsGzip = acceptEncoding != null && accepts(acceptEncoding, "gzip");
            contentType += ";charset=UTF-8";
        }
    }

    final HttpServletResponse response = pwmRequest.getPwmResponse().getHttpServletResponse();
    final String eTagValue = resourceConfiguration.getNonceValue();

    { // reply back with etag.
        final String ifNoneMatchValue = pwmRequest.readHeaderValueAsString(HttpHeader.If_None_Match);
        if (ifNoneMatchValue != null && ifNoneMatchValue.equals(eTagValue)) {
            response.reset();
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            try {
                pwmRequest.debugHttpRequestToLog("returning HTTP 304 status");
            } catch (PwmUnrecoverableException e2) {
                /* noop */ }
            return;
        }
    }

    // Initialize response.
    addExpirationHeaders(resourceConfiguration, response);
    response.setHeader("ETag", resourceConfiguration.getNonceValue());
    response.setContentType(contentType);

    try {
        boolean fromCache = false;
        StringBuilder debugText = new StringBuilder();
        try {
            fromCache = handleCacheableResponse(resourceConfiguration, response, file, acceptsGzip,
                    resourceService.getCacheMap());
            if (fromCache || acceptsGzip) {
                debugText.append("(");
                if (fromCache) {
                    debugText.append("cached");
                }
                if (fromCache && acceptsGzip) {
                    debugText.append(", ");
                }
                if (acceptsGzip) {
                    debugText.append("gzip");
                }
                debugText.append(")");
            } else {
                debugText = new StringBuilder("(not cached)");
            }
            StatisticsManager.incrementStat(pwmApplication, Statistic.HTTP_RESOURCE_REQUESTS);
        } catch (UncacheableResourceException e) {
            handleUncachedResponse(response, file, acceptsGzip);
            debugText = new StringBuilder();
            debugText.append("(uncacheable");
            if (acceptsGzip) {
                debugText.append(", gzip");
            }
            debugText.append(")");
        }
        try {
            pwmRequest.debugHttpRequestToLog(debugText.toString());
        } catch (PwmUnrecoverableException e) {
            /* noop */
        }

        final EventRateMeter.MovingAverage cacheHitRatio = resourceService.getCacheHitRatio();
        cacheHitRatio.update(fromCache ? 1 : 0);
    } catch (Exception e) {
        LOGGER.error(pwmRequest,
                "error fulfilling response for url '" + requestURI + "', error: " + e.getMessage());
    }
}