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:org.sakaiproject.sdata.tool.JCRHandler.java

@Override
public void doGet(final HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    OutputStream out = null;/*from   w  w w. j av a 2 s .  c o m*/
    InputStream in = null;
    try {
        snoopRequest(request);

        ResourceDefinition rp = resourceDefinitionFactory.getSpec(request);
        SDataFunction m = resourceFunctionFactory.get(rp.getFunctionDefinition());

        if (describe(request, response, m)) {
            return;
        }

        Node n = jcrNodeFactory.getNode(rp.getRepositoryPath());
        if (n == null) {
            response.reset();
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        String primaryNodeType = n.getPrimaryNodeType().getName();
        String version = rp.getVersion();
        if (version != null) {
            try {
                n = n.getVersionHistory().getVersion(version);
            } catch (VersionException e) {
                throw new SDataAccessException(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
            }
            n = n.getNode(JCRConstants.JCR_FROZENNODE);
            if (n.hasProperty(JCRConstants.JCR_FROZENPRIMARYTYPE)) {
                primaryNodeType = n.getProperty(JCRConstants.JCR_FROZENPRIMARYTYPE).getString();
            }
        }

        if (m != null) {
            m.call(this, request, response, n, rp);
        } else {

            if (JCRConstants.NT_FILE.equals(primaryNodeType)) {

                Node resource = n.getNode(JCRConstants.JCR_CONTENT);
                Property lastModified = resource.getProperty(JCRConstants.JCR_LASTMODIFIED);
                Property mimeType = resource.getProperty(JCRConstants.JCR_MIMETYPE);
                Property content = resource.getProperty(JCRConstants.JCR_DATA);

                response.setContentType(mimeType.getString());
                if (mimeType.getString().startsWith("text")) {
                    if (resource.hasProperty(JCRConstants.JCR_ENCODING)) {
                        Property encoding = resource.getProperty(JCRConstants.JCR_ENCODING);
                        response.setCharacterEncoding(encoding.getString());
                    }
                }
                response.setDateHeader(LAST_MODIFIED, lastModified.getDate().getTimeInMillis());
                setGetCacheControl(response, rp.isPrivate());

                String currentEtag = String.valueOf(lastModified.getDate().getTimeInMillis());
                response.setHeader("ETag", currentEtag);

                long lastModifiedTime = lastModified.getDate().getTimeInMillis();

                if (!checkPreconditions(request, response, lastModifiedTime, currentEtag)) {
                    return;
                }
                long totallength = content.getLength();
                long[] ranges = new long[2];
                ranges[0] = 0;
                ranges[1] = totallength;
                if (!checkRanges(request, response, lastModifiedTime, currentEtag, ranges)) {
                    return;
                }

                long length = ranges[1] - ranges[0];

                if (totallength != length) {
                    response.setHeader("Accept-Ranges", "bytes");
                    response.setDateHeader("Last-Modified", lastModifiedTime);
                    response.setHeader("Content-Range",
                            "bytes " + ranges[0] + "-" + (ranges[1] - 1) + "/" + totallength);
                    response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);

                    LOG.info("Partial Content Sent " + HttpServletResponse.SC_PARTIAL_CONTENT);
                } else {
                    response.setStatus(HttpServletResponse.SC_OK);
                }

                response.setContentLength((int) length);

                out = response.getOutputStream();

                in = content.getStream();
                long loc = in.skip(ranges[0]);
                if (loc != ranges[0]) {
                    throw new RestServiceFaultException(HttpServletResponse.SC_BAD_REQUEST,
                            "Range specified is invalid asked for " + ranges[0] + " got " + loc);
                }
                byte[] b = new byte[10240];
                int nbytes = 0;
                while ((nbytes = in.read(b)) > 0 && length > 0) {
                    if (nbytes < length) {
                        out.write(b, 0, nbytes);
                        length = length - nbytes;
                    } else {
                        out.write(b, 0, (int) length);
                        length = 0;
                    }
                }
            } else {
                boolean handled = handleSmartNode(request, response, rp, n);
                if (!handled) {
                    doDefaultGet(request, response, rp, n);
                }
            }
        }
    } catch (UnauthorizedException ape) {
        // catch any Unauthorized exceptions and send a 401
        response.reset();
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, ape.getMessage());
    } catch (PermissionDeniedException pde) {
        // catch any permission denied exceptions, and send a 403
        response.reset();
        response.sendError(HttpServletResponse.SC_FORBIDDEN, pde.getMessage());

    } catch (SDataException e) {
        LOG.error("Failed  To service Request " + e.getMessage());
        e.printStackTrace();
        sendError(request, response, e);
    } catch (Exception e) {
        LOG.error("Failed  TO service Request ", e);
        sendError(request, response, e);
        snoopRequest(request);
    } finally {

        try {
            out.close();
        } catch (Exception ex) {
        }
        try {
            in.close();
        } catch (Exception ex) {
        }
    }
}

From source file:it.attocchi.jsf2.PageBase.java

protected void downloadPDF(String fileName, String rename) throws IOException {

    // Prepare./*w  w w.  j  a va 2  s  .co  m*/
    FacesContext facesContext = getFacesContext();
    ExternalContext externalContext = facesContext.getExternalContext();
    HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();

    File file = new File(fileName);
    BufferedInputStream input = null;
    BufferedOutputStream output = null;

    try {
        // Open file.
        input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);

        String downloadFileName = file.getName();
        if (rename != null && !rename.equals("")) {
            /*
             * controllo se rename specifica l'estensione, se non la
             * specifica la impostiamo dal nome originale
             */
            String extNuova = FilenameUtils.getExtension(rename);
            String extOrig = FilenameUtils.getExtension(fileName);
            if (StringUtils.isBlank(extNuova))
                if (StringUtils.isNotBlank(extNuova))
                    rename = rename + "." + extOrig;
            downloadFileName = rename;
            // fileName.substring(fileName.lastIndexOf("."));
        }

        // Init servlet response.
        response.reset();
        response.setHeader("Content-Type", "application/octet-stream");
        response.setHeader("Content-Length", String.valueOf(file.length()));
        // response.setHeader("Content-Disposition", "inline; filename=\"" +
        // downloadFileName + "\"");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + downloadFileName + "\"");
        output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);

        // Write file contents to response.
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        int length;
        while ((length = input.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }

        // Finalize task.
        output.flush();
    } finally {
        // Gently close streams.
        close(output);
        close(input);
    }

    // Inform JSF that it doesn't need to handle response.
    // This is very important, otherwise you will get the following
    // exception in the logs:
    // java.lang.IllegalStateException: Cannot forward after response has
    // been committed.
    facesContext.responseComplete();
}

From source file:org.apache.roller.planet.ui.rendering.servlets.PageServlet.java

/**
 * Handle GET requests for weblog feeds.
 */// ww w .j av a 2s  . c  om
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    log.debug("Entering");

    Planet planet = null;
    PlanetGroup group = null;

    PlanetGroupPageRequest pageRequest = null;
    try {
        // parse the incoming request and extract the relevant data
        pageRequest = new PlanetGroupPageRequest(request);

        planet = pageRequest.getPlanet();
        if (planet == null) {
            throw new PlanetException("unable to lookup planet: " + pageRequest.getPlanetHandle());
        }

        group = pageRequest.getGroup();

    } catch (Exception e) {
        // invalid feed request format or weblog doesn't exist
        log.debug("error creating planet page request", e);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // set content type
    response.setContentType("text/html; charset=utf-8");

    // looks like we need to render content
    HashMap model = new HashMap();
    try {
        // populate the rendering model
        Map initData = new HashMap();
        initData.put("planetRequest", pageRequest);

        // Load models for pages
        String pageModels = PlanetConfig.getProperty("rendering.pageModels");
        ModelLoader.loadModels(pageModels, model, initData, true);

    } catch (PlanetException ex) {
        log.error("ERROR loading model for page", ex);

        if (!response.isCommitted())
            response.reset();
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    // lookup Renderer we are going to use
    Renderer renderer = null;
    try {
        log.debug("Looking up renderer");

        // what template are we going to render?
        Template template = null;
        if (group == null) {
            // planet homepage
            template = new StaticTemplate("planet.vm", null, "velocity");
        } else {
            // group homepage
            template = new StaticTemplate("group.vm", null, "velocity");
        }

        // get the Renderer
        renderer = RendererManager.getRenderer(template);

    } catch (Exception e) {
        // nobody wants to render my content :(

        if (!response.isCommitted())
            response.reset();
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // render content
    try {
        log.debug("Doing rendering");
        renderer.render(model, response.getWriter());
    } catch (Exception e) {
        // bummer, error during rendering
        log.error("Error during rendering", e);

        if (!response.isCommitted())
            response.reset();
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // post rendering process

    // flush rendered content to response
    log.debug("Flushing response output");
    //response.setContentLength(rendererOutput.getContent().length);
    //response.getOutputStream().write(rendererOutput.getContent());

    log.debug("Exiting");
}

From source file:org.sakaiproject.sdata.tool.JCRHandler.java

/**
 * Check the ranges requested in the request headers, this conforms to the RFC on the
 * range, if-range headers. On return, it the request is to be processed, true will be
 * returned, and ranges[0] will the the start byte of the response stream and ranges[1]
 * will be the end byte.//  ww w  .jav a 2 s  .c om
 *
 * @param request
 *          the request object from the Servlet Container.
 * @param response
 *          the response object from the servlet container.
 * @param lastModifiedTime
 *          the last modified time from target object
 * @param currentEtag
 *          the Etag
 * @param ranges
 *          ranges setup to contain the start and end byte offsets
 * @return true if the response is to contain data, false if not.
 * @throws IOException
 */
private boolean checkRanges(HttpServletRequest request, HttpServletResponse response, long lastModifiedTime,
        String currentEtag, long[] ranges) throws IOException {

    String range = request.getHeader("range");
    long ifRangeDate = request.getDateHeader("if-range");
    String ifRangeEtag = request.getHeader("if-range");

    if (ifRangeDate != -1 && lastModifiedTime > ifRangeDate) {
        // the entity has been modified, ignore and send the whole lot
        return true;
    }
    if (ifRangeEtag != null && !currentEtag.equals(ifRangeEtag)) {
        // the entity has been modified, ignore and send the whole lot
        return true;
    }

    if (range != null) {
        String[] s = range.split("=");
        if (!"bytes".equals(s[0])) {
            response.reset();
            response.sendError(416, "System only supports single range responses, specified in bytes");
            return false;
        }
        range = s[1];
        String[] r = range.split(",");
        if (r.length > 1) {
            response.reset();
            response.sendError(416, "System only supports single range responses");
            return false;
        }
        range = range.trim();
        if (range.startsWith("-")) {
            ranges[1] = Long.parseLong(range.substring(1));
        } else if (range.endsWith("-")) {
            ranges[0] = Long.parseLong(range.substring(0, range.length() - 1));
        } else {
            r = range.split("-");
            ranges[0] = Long.parseLong(r[0]);
            ranges[1] = Long.parseLong(r[1]);
        }
    }
    return true;
}

From source file:com.wabacus.WabacusServlet.java

public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String contentType = request.getHeader("Content-type");
    if (contentType != null && contentType.startsWith("multipart/")) {
        WabacusFacade.uploadFile(request, response);
    } else {//  w w w  .  ja v a 2 s .  c  om
        String action = Tools.getRequestValue(request, "ACTIONTYPE", "");
        if (action.equalsIgnoreCase("updateconfig")) {
            loadReportConfigFiles();
            PrintWriter out = response.getWriter();
            out.println("??");
        } else if (action.equalsIgnoreCase("invokeServerAction")) {
            String resultStr = WabacusFacade.invokeServerAction(request, response);
            if (resultStr != null && !resultStr.trim().equals("")) {
                PrintWriter out = response.getWriter();
                out.println(resultStr);
            }
        } else if (action.equalsIgnoreCase("ServerValidateOnBlur")) {//?onblur??
            String resultStr = WabacusFacade.doServerValidateOnBlur(request, response);
            if (resultStr != null && !resultStr.trim().equals("")) {
                PrintWriter out = response.getWriter();
                out.println(resultStr);
            }
        } else if (action.equalsIgnoreCase("download")) {
            WabacusFacade.downloadFile(request, response);
        } else if (action.equalsIgnoreCase("GetFilterDataList")) {
            response.reset();
            response.setContentType("text/xml;charset=" + Config.encode);
            StringBuffer sbuffer = new StringBuffer(
                    "<?xml version=\"1.0\" encoding=\"" + Config.encode + "\"?><items>");
            sbuffer.append(WabacusFacade.getFilterDataList(request, response));
            sbuffer.append("</items>");
            PrintWriter out = response.getWriter();
            out.println(sbuffer.toString().trim());
        } else if (action.equalsIgnoreCase("GetTypePromptDataList")) {
            response.reset();
            response.setContentType("text/xml;charset=" + Config.encode);
            StringBuffer sbuffer = new StringBuffer(
                    "<?xml version=\"1.0\" encoding=\"" + Config.encode + "\"?><items>");
            sbuffer.append(WabacusFacade.getTypePromptDataList(request, response));
            sbuffer.append("</items>");
            PrintWriter out = response.getWriter();
            out.println(sbuffer.toString().trim());
        } else if (action.equalsIgnoreCase("GetSelectBoxDataList")) {
            response.reset();
            response.setContentType("text/html;charset=" + Config.encode);
            String resultStr = WabacusFacade.getSelectBoxDataList(request, response);
            PrintWriter out = response.getWriter();
            out.print(resultStr);
        } else if (action.equalsIgnoreCase(Consts.GETAUTOCOMPLETEDATA_ACTION)) {//???
            PrintWriter out = response.getWriter();
            out.print(WabacusFacade.getAutoCompleteColValues(request, response));
        } else if (action.equalsIgnoreCase("ShowUploadFilePage")) {
            PrintWriter out = response.getWriter();
            out.println(
                    "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
            out.println(
                    "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=" + Config.encode + "\">");
            WabacusFacade.showUploadFilePage(request, out);
        } else if (action.equalsIgnoreCase("getChartDataString")) {//??<chart/>?
            response.reset();
            response.setContentType("text/xml;charset=" + Config.encode);
            StringBuffer sbuffer = new StringBuffer(
                    "<?xml version=\"1.0\" encoding=\"" + Config.encode + "\"?>");
            sbuffer.append(WabacusFacade.getChartDataString(request, response));
            PrintWriter out = response.getWriter();
            out.println(sbuffer.toString().trim());
        } else if (action.equalsIgnoreCase("loadChartXmlFile")) {
            response.reset();
            response.setContentType("text/xml;charset=" + Config.encode);
            StringBuffer sbuffer = new StringBuffer(
                    "<?xml version=\"1.0\" encoding=\"" + Config.encode + "\"?>");
            sbuffer.append(WabacusFacade.getChartDataStringFromLocalFile(request, response));
            PrintWriter out = response.getWriter();
            out.println(sbuffer.toString().trim());
        } else {
            int itype = Integer.parseInt(Tools.getRequestValue(request, Consts.DISPLAYTYPE_PARAMNAME,
                    String.valueOf(Consts.DISPLAY_ON_PAGE)));
            if (itype == Consts.DISPLAY_ON_PRINT) {
                WabacusFacade.printComponents(request, response);
            } else if (itype == Consts.DISPLAY_ON_PLAINEXCEL) {//?
                WabacusFacade.exportReportDataOnPlainExcel(request, response);
            } else if (itype == Consts.DISPLAY_ON_RICHEXCEL) {
                WabacusFacade.exportReportDataOnWordRichexcel(request, response, Consts.DISPLAY_ON_RICHEXCEL);
            } else if (itype == Consts.DISPLAY_ON_WORD) {
                WabacusFacade.exportReportDataOnWordRichexcel(request, response, Consts.DISPLAY_ON_WORD);
            } else if (itype == Consts.DISPLAY_ON_PDF) {
                WabacusFacade.exportReportDataOnPDF(request, response, Consts.DISPLAY_ON_PDF);
            } else {
                WabacusFacade.displayReport(request, response);
            }
        }
    }
}

From source file:org.openmeetings.servlet.outputhandler.LangExport.java

@Override
protected void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {

    try {/*from w w w  .  j a  va2  s.  com*/

        if (getUserManagement() == null || getFieldLanguageDaoImpl() == null || getFieldmanagment() == null
                || getSessionManagement() == null) {
            return;
        }

        String sid = httpServletRequest.getParameter("sid");
        if (sid == null) {
            sid = "default";
        }
        log.debug("sid: " + sid);

        String language = httpServletRequest.getParameter("language");
        if (language == null) {
            language = "0";
        }
        Long language_id = Long.valueOf(language).longValue();
        log.debug("language_id: " + language_id);

        Long users_id = getSessionManagement().checkSession(sid);
        Long user_level = getUserManagement().getUserLevelByID(users_id);

        log.debug("users_id: " + users_id);
        log.debug("user_level: " + user_level);

        if (user_level != null && user_level > 0) {
            FieldLanguage fl = getFieldLanguageDaoImpl().getFieldLanguageById(language_id);

            List<Fieldlanguagesvalues> flvList = getFieldmanagment().getMixedFieldValuesList(language_id);

            if (fl != null && flvList != null) {
                Document doc = createDocument(flvList,
                        getFieldmanagment().getUntranslatedFieldValuesList(language_id));

                String requestedFile = fl.getName() + ".xml";

                httpServletResponse.reset();
                httpServletResponse.resetBuffer();
                OutputStream out = httpServletResponse.getOutputStream();
                httpServletResponse.setContentType("APPLICATION/OCTET-STREAM");
                httpServletResponse.setHeader("Content-Disposition",
                        "attachment; filename=\"" + requestedFile + "\"");
                // httpServletResponse.setHeader("Content-Length", ""+
                // rf.length());

                this.serializetoXML(out, "UTF-8", doc);

                out.flush();
                out.close();
            }
        } else {
            log.debug("ERROR LangExport: not authorized FileDownload " + (new Date()));
        }

    } catch (Exception er) {
        log.error("ERROR ", er);
        System.out.println("Error exporting: " + er);
        er.printStackTrace();
    }
}

From source file:fll.web.ajax.DisplayQueryServlet.java

protected void processRequest(final HttpServletRequest request, final HttpServletResponse response,
        final ServletContext application, final HttpSession session) throws IOException, ServletException {
    final String localDisplayPage;
    final String localDisplayURL;
    final String displayName = SessionAttributes.getAttribute(session, "displayName", String.class);
    if (displayName != null) {
        // update last seen time
        DisplayNames.appendDisplayName(application, session, displayName);

        final String myDisplayPage = ApplicationAttributes.getAttribute(application,
                displayName + "_displayPage", String.class);
        final String myDisplayURL = ApplicationAttributes.getAttribute(application, displayName + "_displayURL",
                String.class);

        localDisplayPage = myDisplayPage != null ? myDisplayPage
                : ApplicationAttributes.getAttribute(application, ApplicationAttributes.DISPLAY_PAGE,
                        String.class);

        localDisplayURL = myDisplayURL != null ? myDisplayURL
                : ApplicationAttributes.getAttribute(application, "displayURL", String.class);
    } else {//from   w w w  .j  av  a 2s  .  c  om
        localDisplayPage = ApplicationAttributes.getAttribute(application, ApplicationAttributes.DISPLAY_PAGE,
                String.class);
        localDisplayURL = ApplicationAttributes.getAttribute(application, "displayURL", String.class);
    }

    final String url = pickURL(request, localDisplayPage, localDisplayURL, application, session);
    final DisplayResponse displayResponse = new DisplayResponse(url);

    final ObjectMapper jsonMapper = new ObjectMapper();

    response.reset();
    response.setContentType("application/json");
    final PrintWriter writer = response.getWriter();

    jsonMapper.writeValue(writer, displayResponse);
}

From source file:edu.stanford.muse.webapp.JSPHelper.java

public static void writeFileToResponse(HttpSession session, HttpServletResponse response, String filePath,
        boolean asAttachment) throws IOException {
    // Decode the file name (might contain spaces and on) and prepare file object.
    File file = new File(filePath);

    // Check if file actually exists in filesystem.
    if (!file.exists()) {
        log.warn("Returing 404, serveFile can't find file: " + filePath);

        // Do your thing if the file appears to be non-existing.
        // Throw an exception, or send 404, or show default/warning page, or just ignore it.
        response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
        return;//from www. j av a  2s .c  o m
    }

    // Get content type by filename.

    String contentType = session.getServletContext().getMimeType(file.getName());

    // 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";
    }

    // Init servlet response.
    int DEFAULT_BUFFER_SIZE = 100000;
    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setContentType(contentType);

    // not really sure why this is needed, but we have to ensure that these headers are not present when rendering e.g. xwordImage (directly rendered into web browser, instead of piclens)
    if (asAttachment) {
        response.setHeader("Content-Length", String.valueOf(file.length()));
        response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
    }
    // Prepare streams.
    BufferedInputStream input = null;
    BufferedOutputStream output = null;

    try {
        // Open streams.
        input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);
        output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);

        // Write file contents to response.
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        int length;
        while ((length = input.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }
    } finally {
        // Gently close streams.
        Util.close(output);
        Util.close(input);
    }
}

From source file:cn.edu.pku.lib.dataverse.UsageLogStatisPage.java

public void downloadFileDownloadLog(String type) {
    FacesContext context = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
    File file = null;//  w w  w.j a  v  a2  s  .  c  o m
    switch (type) {
    case "csv":
        file = generateCSVDownloadLogFile();
        break;
    case "xlsx":
        file = generateExcelDownloadLogFile();
        break;
    default:
        file = generateCSVDownloadLogFile();
    }
    if (file == null) {
        try {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } catch (IOException ex) {
            logger.log(Level.SEVERE, null, ex);
        }
        return;
    }
    response.reset();
    response.setContentType("application/octet-stream");
    switch (type) {
    case "csv":
        response.setHeader("Content-Disposition", "attachment;filename=\"download_information.csv\"");
        break;
    case "xlsx":
        response.setHeader("Content-Disposition", "attachment;filename=\"download_information.xlsx\"");
        break;
    default:
        response.setHeader("Content-Disposition", "attachment;filename=\"download_information.csv\"");
    }
    response.setContentLength((int) file.length());
    try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());) {
        byte[] buffer = new byte[1024 * 4];
        int length;
        while ((length = in.read(buffer)) > 0) {
            out.write(buffer, 0, length);
        }
    } catch (IOException ioe) {
        logger.log(Level.SEVERE, null, ioe);
    }
    context.responseComplete();
    if (file.exists())
        file.delete();
}

From source file:org.apache.cocoon.servlet.CocoonServlet.java

protected void manageException(HttpServletRequest req, HttpServletResponse res, Environment env, String uri,
        int errorStatus, String title, String message, String description, Exception e) throws IOException {
    if (this.manageExceptions) {
        if (env != null) {
            env.tryResetResponse();/*  w  ww  .java 2  s  .  co m*/
        } else {
            res.reset();
        }

        String type = Notifying.FATAL_NOTIFICATION;
        HashMap extraDescriptions = null;

        if (errorStatus == HttpServletResponse.SC_NOT_FOUND) {
            type = "resource-not-found";
            // Do not show the exception stacktrace for such common errors.
            e = null;
        } else {
            extraDescriptions = new HashMap(2);
            extraDescriptions.put(Notifying.EXTRA_REQUESTURI, req.getRequestURI());
            if (uri != null) {
                extraDescriptions.put("Request URI", uri);
            }

            // Do not show exception stack trace when log level is WARN or above. Show only message.
            if (!getLogger().isInfoEnabled()) {
                Throwable t = DefaultNotifyingBuilder.getRootCause(e);
                if (t != null)
                    extraDescriptions.put(Notifying.EXTRA_CAUSE, t.getMessage());
                e = null;
            }
        }

        Notifying n = new DefaultNotifyingBuilder().build(this, e, type, title, "Cocoon Servlet", message,
                description, extraDescriptions);

        res.setContentType("text/html");
        res.setStatus(errorStatus);
        Notifier.notify(n, res.getOutputStream(), "text/html");
    } else {
        res.sendError(errorStatus, title);
        res.flushBuffer();
    }
}