Example usage for javax.servlet.http HttpServletResponse flushBuffer

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

Introduction

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

Prototype

public void flushBuffer() throws IOException;

Source Link

Document

Forces any content in the buffer to be written to the client.

Usage

From source file:org.alfresco.web.site.servlet.SSOAuthenticationFilter.java

/**
 * Process a type 1 NTLM message//from  w  w w. j  av  a 2  s  . c  o  m
 * 
 * @param type1Msg Type1NTLMMessage
 * @param req HttpServletRequest
 * @param res HttpServletResponse
 * @param session HttpSession
 * 
 * @exception IOException
 */
private void processType1(Type1NTLMMessage type1Msg, HttpServletRequest req, HttpServletResponse res,
        HttpSession session) throws IOException {
    if (logger.isDebugEnabled())
        logger.debug("Received type1 " + type1Msg);

    // Get the existing NTLM details
    NTLMLogonDetails ntlmDetails = (NTLMLogonDetails) session.getAttribute(NTLM_AUTH_DETAILS);

    // Check if cached logon details are available
    if (ntlmDetails != null && ntlmDetails.hasType2Message()) {
        // Get the authentication server type2 response
        Type2NTLMMessage cachedType2 = ntlmDetails.getType2Message();

        byte[] type2Bytes = cachedType2.getBytes();
        String ntlmBlob = "NTLM " + new String(Base64.encodeBytes(type2Bytes, Base64.DONT_BREAK_LINES));

        if (logger.isDebugEnabled())
            logger.debug("Sending cached NTLM type2 to client - " + cachedType2);

        // Send back a request for NTLM authentication
        res.setHeader(HEADER_WWWAUTHENTICATE, ntlmBlob);
        res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        res.flushBuffer();
    } else {
        // Clear any cached logon details
        session.removeAttribute(NTLM_AUTH_DETAILS);

        try {
            Connector conn = this.connectorService.getConnector(this.endpoint, session);
            ConnectorContext ctx = new ConnectorContext(null, getConnectionHeaders(conn));
            Response remoteRes = conn.call("/touch", ctx, req, null);
            if (Status.STATUS_UNAUTHORIZED == remoteRes.getStatus().getCode()) {
                String authHdr = remoteRes.getStatus().getHeaders().get(HEADER_WWWAUTHENTICATE);
                if (authHdr.startsWith(AUTH_NTLM) && authHdr.length() > 4) {
                    // Decode the received NTLM blob and validate
                    final byte[] authHdrByts = authHdr.substring(5).getBytes();
                    final byte[] ntlmByts = Base64.decode(authHdrByts);
                    int ntlmType = NTLMMessage.isNTLMType(ntlmByts);
                    if (ntlmType == NTLM.Type2) {
                        // Retrieve the type2 NTLM message
                        Type2NTLMMessage type2Msg = new Type2NTLMMessage(ntlmByts);

                        // Store the NTLM logon details, cache the type2 message, and token if using passthru
                        ntlmDetails = new NTLMLogonDetails();
                        ntlmDetails.setType2Message(type2Msg);
                        session.setAttribute(NTLM_AUTH_DETAILS, ntlmDetails);

                        if (logger.isDebugEnabled())
                            logger.debug("Sending NTLM type2 to client - " + type2Msg);

                        // Send back a request for NTLM authentication
                        byte[] type2Bytes = type2Msg.getBytes();
                        String ntlmBlob = "NTLM "
                                + new String(Base64.encodeBytes(type2Bytes, Base64.DONT_BREAK_LINES));

                        res.setHeader(HEADER_WWWAUTHENTICATE, ntlmBlob);
                        res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                        res.flushBuffer();
                    } else {
                        if (logger.isDebugEnabled())
                            logger.debug("Unexpected NTLM message type from repository: NTLMType" + ntlmType);
                        redirectToLoginPage(req, res);
                    }
                } else {
                    if (logger.isDebugEnabled())
                        logger.debug("Unexpected response from repository: WWW-Authenticate:" + authHdr);
                    redirectToLoginPage(req, res);
                }
            } else {
                if (logger.isDebugEnabled())
                    logger.debug("Unexpected response from repository: " + remoteRes.getStatus().getMessage());
                redirectToLoginPage(req, res);
            }
        } catch (ConnectorServiceException cse) {
            throw new PlatformRuntimeException("Incorrectly configured endpoint ID: " + this.endpoint);
        }
    }
}

From source file:com.adaptris.core.http.jetty.ResponseProducer.java

@Override
public void produce(AdaptrisMessage msg, ProduceDestination destination) throws ProduceException {
    JettyWrapper wrapper = JettyWrapper.unwrap(msg);
    HttpServletResponse response = wrapper.getResponse();
    InputStream in = null;//w w w. ja va  2  s.  co  m

    try {
        wrapper.lock();
        if (response == null) {
            log.debug("No HttpServletResponse in object metadata, nothing to do");
            return;
        }
        for (Iterator i = additionalHeaders.getKeyValuePairs().iterator(); i.hasNext();) {
            KeyValuePair k = (KeyValuePair) i.next();
            response.addHeader(k.getKey(), k.getValue());
        }

        MetadataCollection metadataSubset = getMetadataFilter().filter(msg);
        for (MetadataElement me : metadataSubset) {
            response.addHeader(me.getKey(), me.getValue());
        }

        if (getContentTypeKey() != null && msg.containsKey(getContentTypeKey())) {
            response.setContentType(msg.getMetadataValue(getContentTypeKey()));
        }
        response.setStatus(getStatus(msg).getCode());
        if (sendPayload()) {
            if (getEncoder() != null) {
                getEncoder().writeMessage(msg, response);
            } else {
                if (msg.getSize() > 0) {
                    in = msg.getInputStream();
                    try {
                        StreamUtil.copyStream(in, response.getOutputStream());
                    } catch (IOException ioe) {
                        // if we catch an IOE here, chances are the connection is down and there isn't much we can do.
                        log.error(
                                "Cannot send the response, the connection appears to be down, either a timeout or the client has closed the connection.");
                        if (forwardConnectionExceptions())
                            throw ioe;
                    }
                }
            }
        } else {
            log.trace("Ignoring Payload");
        }
        if (flushBuffers()) {
            response.flushBuffer();
        }
        wrapper.setResponse(null);
    } catch (Exception e) {
        throw new ProduceException(e);
    } finally {
        IOUtils.closeQuietly(in);
        wrapper.unlock();
    }
}

From source file:pt.ist.applications.admissions.ui.ApplicationsAdmissionsController.java

@RequestMapping(value = "/contest/{contest}/exportContestCandidates", method = RequestMethod.GET)
public String exportContestCandidates(@PathVariable Contest contest, final Model model,
        HttpServletResponse response) throws IOException {
    SpreadsheetBuilder builder = new SpreadsheetBuilder();
    String fileName = messageSource.getMessage("title.applications.admissions", null, I18N.getLocale());
    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-Disposition", "filename=" + fileName + ".xls");

    builder.addSheet(fileName, new SheetData<Candidate>(contest.getCandidateSet()) {
        @Override/*from   ww  w.j a  va 2 s .c  om*/
        protected void makeLine(Candidate candidate) {
            addCell(messageSource.getMessage("label.applications.admissions.candidate.number", null,
                    I18N.getLocale()), candidate.getCandidateNumber());
            addCell(messageSource.getMessage("label.applications.admissions.candidate", null, I18N.getLocale()),
                    candidate.getName());
            addCell(messageSource.getMessage("label.applications.admissions.candidate.email", null,
                    I18N.getLocale()), candidate.getEmail());
            addCell(messageSource.getMessage("label.application.seal.date", null, I18N.getLocale()),
                    candidate.getSealDate());

            final JsonArray candidateDocuments = ClientFactory.configurationDriveClient()
                    .listDirectory(candidate.getDirectoryForCandidateDocuments());
            addCell(messageSource.getMessage("label.applications.admissions.candidate.documents", null,
                    I18N.getLocale()), candidateDocuments.size());
            final JsonArray lettersOfRecomendation = ClientFactory.configurationDriveClient()
                    .listDirectory(candidate.getDirectoryForLettersOfRecomendation());
            addCell(messageSource.getMessage("label.applications.admissions.candidate.lettersOfRecommendation",
                    null, I18N.getLocale()), lettersOfRecomendation.size());
        }
    });

    builder.build(WorkbookExportFormat.TSV, response.getOutputStream());
    response.flushBuffer();
    return null;
}

From source file:org.nuxeo.ecm.platform.ui.web.download.BlobDownloadServlet.java

void downloadBlob(HttpServletRequest req, HttpServletResponse resp, Blob blob, String fileName)
        throws IOException, ServletException {
    InputStream in = blob.getStream();
    OutputStream out = resp.getOutputStream();
    try {/*w  w w.ja v  a2  s . co  m*/

        if (fileName == null || fileName.length() == 0) {
            if (blob.getFilename() != null && blob.getFilename().length() > 0) {
                fileName = blob.getFilename();
            } else {
                fileName = "file";
            }
        }

        resp.setHeader("Content-Disposition", ServletHelper.getRFC2231ContentDisposition(req, fileName));
        resp.setContentType(blob.getMimeType());

        long fileSize = blob.getLength();
        if (fileSize > 0) {
            String range = req.getHeader("Range");
            ByteRange byteRange = null;
            if (range != null) {
                try {
                    byteRange = parseRange(range, fileSize);
                } catch (ClientException e) {
                    log.error(e.getMessage(), e);
                }
            }
            if (byteRange != null) {
                resp.setHeader("Accept-Ranges", "bytes");
                resp.setHeader("Content-Range",
                        "bytes " + byteRange.getStart() + "-" + byteRange.getEnd() + "/" + fileSize);
                long length = byteRange.getLength();
                if (length < Integer.MAX_VALUE) {
                    resp.setContentLength((int) length);
                }
                resp.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
                writeStream(in, out, byteRange);
            } else {
                if (fileSize < Integer.MAX_VALUE) {
                    resp.setContentLength((int) fileSize);
                }
                writeStream(in, out, new ByteRange(0, fileSize - 1));
            }
        }

    } catch (IOException ioe) {
        handleClientDisconnect(ioe);
    } catch (Exception e) {
        throw new ServletException(e);
    } finally {
        if (resp != null) {
            try {
                resp.flushBuffer();
            } catch (IOException ioe) {
                handleClientDisconnect(ioe);
            }
        }
        if (in != null) {
            in.close();
        }
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.teacher.onlineTests.TestsManagementAction.java

public ActionForward downloadTestMarks(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws FenixActionException {
    final String distributedTestCode = getStringFromRequest(request, "distributedTestCode");
    String result = null;/*from  w w w.  j a va2  s . co m*/
    try {
        if (distributedTestCode != null) {
            result = ReadDistributedTestMarksToString.runReadDistributedTestMarksToString(
                    getExecutionCourse(request).getExternalId(), distributedTestCode);
        } else {
            result = ReadDistributedTestMarksToString.runReadDistributedTestMarksToString(
                    getExecutionCourse(request).getExternalId(),
                    request.getParameterValues("distributedTestCodes"));
        }
    } catch (FenixServiceException e) {
        throw new FenixActionException(e);
    }
    try {
        ServletOutputStream writer = response.getOutputStream();
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment; filename=pauta.xls");
        writer.print(result);
        writer.flush();
        response.flushBuffer();
    } catch (IOException e) {
        throw new FenixActionException();
    }
    return null;
}

From source file:org.apache.stratos.theme.mgt.ui.servlets.ThemeResourceServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {/*from w  w w .j  ava 2 s.co  m*/
        ThemeMgtServiceClient client = new ThemeMgtServiceClient(servletConfig, request.getSession());
        String path = request.getParameter("path");
        String viewImage = request.getParameter("viewImage");
        if (path == null) {
            String msg = "Could not get the resource content. Path is not specified.";
            log.error(msg);
            response.setStatus(400);
            return;
        }

        ContentDownloadBean bean = client.getContentDownloadBean(path);

        InputStream contentStream = null;
        if (bean.getContent() != null) {
            contentStream = bean.getContent().getInputStream();
        } else {
            String msg = "The resource content was empty.";
            log.error(msg);
            response.setStatus(204);
            return;
        }

        response.setDateHeader("Last-Modified", bean.getLastUpdatedTime().getTime().getTime());
        String ext = "jpg";
        if (path.lastIndexOf(".") < path.length() - 1 && path.lastIndexOf(".") > 0) {
            ext = path.substring(path.lastIndexOf(".") + 1);
        }

        if (viewImage != null && viewImage.equals("1")) {
            response.setContentType("img/" + ext);
        } else {
            if (bean.getMediatype() != null && bean.getMediatype().length() > 0) {
                response.setContentType(bean.getMediatype());
            } else {
                response.setContentType("application/download");
            }

            if (bean.getResourceName() != null) {
                response.setHeader("Content-Disposition",
                        "attachment; filename=\"" + bean.getResourceName() + "\"");
            }
        }

        if (contentStream != null) {

            ServletOutputStream servletOutputStream = null;
            try {
                servletOutputStream = response.getOutputStream();

                byte[] contentChunk = new byte[1024];
                int byteCount;
                while ((byteCount = contentStream.read(contentChunk)) != -1) {
                    servletOutputStream.write(contentChunk, 0, byteCount);
                }

                response.flushBuffer();
                servletOutputStream.flush();

            } finally {
                contentStream.close();

                if (servletOutputStream != null) {
                    servletOutputStream.close();
                }
            }
        }
    } catch (Exception e) {

        String msg = "Failed to get resource content. " + e.getMessage();
        log.error(msg, e);
        response.setStatus(500);
    }
}

From source file:org.openmrs.module.spreadsheetimport.web.controller.SpreadsheetImportImportFormController.java

@RequestMapping(value = "/module/spreadsheetimport/spreadsheetimportImport.form", method = RequestMethod.POST)
public String processSubmit(@ModelAttribute("template") SpreadsheetImportTemplate template, ModelMap model,
        @RequestParam(value = "file", required = true) MultipartFile file,
        @RequestParam(value = "sheet", required = true) String sheet, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    //      Map<UniqueImport, Set<SpreadsheetImportTemplateColumn>> rowDataTemp = template.getMapOfUniqueImportToColumnSetSortedByImportIdx();
    ///*from w  w  w.  j  av a 2s  .  c om*/
    //      for (UniqueImport uniqueImport : rowDataTemp.keySet()) {
    //         Set<SpreadsheetImportTemplateColumn> columnSet = rowDataTemp.get(uniqueImport);
    //         boolean isFirst = true;
    //         for (SpreadsheetImportTemplateColumn column : columnSet) {
    //
    //            if (isFirst) {
    //               // Should be same for all columns in unique import
    //               System.out.println("SpreadsheetImportUtil.importTemplate: column.getColumnPrespecifiedValues(): " + column.getColumnPrespecifiedValues().size());
    //               if (column.getColumnPrespecifiedValues().size() > 0) {
    //                  Set<SpreadsheetImportTemplateColumnPrespecifiedValue> columnPrespecifiedValueSet = column.getColumnPrespecifiedValues();
    //                  for (SpreadsheetImportTemplateColumnPrespecifiedValue columnPrespecifiedValue : columnPrespecifiedValueSet) {
    //                     System.out.println(columnPrespecifiedValue.getPrespecifiedValue().getValue());
    //                  }
    //               }
    //            }
    //         }
    //      }

    List<String> messages = new ArrayList<String>();
    boolean rollbackTransaction = true;
    if (request.getParameter("rollbackTransaction") == null) {
        rollbackTransaction = false;
    }

    File returnedFile = SpreadsheetImportUtil.importTemplate(template, file, sheet, messages,
            rollbackTransaction);
    boolean succeeded = (returnedFile != null);

    String messageString = "";
    for (int i = 0; i < messages.size(); i++) {
        if (i != 0) {
            messageString += "<br />";
        }
        messageString += messages.get(i);
    }
    if (succeeded) {
        messageString += "Success!";
        try {
            InputStream is = new FileInputStream(returnedFile);
            response.setContentType("application/ms-excel");
            response.addHeader("content-disposition", "inline;filename=" + returnedFile.getName());
            IOUtils.copy(is, response.getOutputStream());
            response.flushBuffer();
        } catch (IOException ex) {
            log.info("Error writing file to output stream");
        }
    }

    if (!messageString.isEmpty()) {
        if (succeeded) {
            request.getSession().setAttribute(WebConstants.OPENMRS_MSG_ATTR, messageString);
        } else {
            request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                    "Error processing request, " + messageString);
        }
    }

    return "/module/spreadsheetimport/spreadsheetimportImportForm";
}

From source file:it.attocchi.web.filters.NtmlFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    logger.debug("Filtro Ntlm");

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    HttpSession session = httpRequest.getSession();

    String requestPath = httpRequest.getServletPath();
    logger.debug("requestPath " + requestPath);

    String user_agent = null;/*ww  w . j ava 2s .c om*/
    String auth = null;

    String workstation = null;
    String domain = null;
    String username = null;

    try {
        /*
         * Operatore loggato? SI: prosegue con il flusso normalmente; NO:
         * tentativo di accesso con utente Windows e poi, se fallisce,
         * redirect alla pagina di autenticazione;
         */
        if ((requestPath != null && requestPath.endsWith("index.jspx"))
                || (requestPath != null && requestPath.endsWith("status.jspx"))
                || requestPath != null && requestPath.endsWith("logout.jspx")
                || requestPath != null && requestPath.endsWith("authenticate.jspx")) {
            logger.debug("Richiesta una pagina fra quelle speciali, esco dal filtro");
            // chain.doFilter(request, response);
            // return;
        } else {

            /* COMMENTATO per problemi POST JSF */
            // // <editor-fold defaultstate="collapsed"
            // desc="DETERMINAZIONE UTENTE WINDOWS">

            /*
             * La tecnica utilizzata (settaggio header) per la
             * determinazione dell'utente Windows  funzionante
             * esclusivamente con browser Microsoft Internet Explorer. Se
             * altro browser salta questo step
             */
            user_agent = httpRequest.getHeader("user-agent");
            // if ((user_agent != null) && (user_agent.indexOf("MSIE") >
            // -1)) {
            if ((user_agent != null)) {
                logger.debug("USER-AGENT: " + user_agent);

                auth = httpRequest.getHeader("Authorization");
                if (auth == null) {
                    logger.debug("STEP1: SC_UNAUTHORIZED");

                    httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    httpResponse.setHeader("WWW-Authenticate", "NTLM");
                    httpResponse.flushBuffer();
                    return;
                }

                if (auth.startsWith("NTLM ")) {
                    logger.debug("STEP2: NTLM");

                    byte[] msg = org.apache.commons.codec.binary.Base64.decodeBase64(auth.substring(5));
                    // byte[] msg = new
                    // sun.misc.BASE64Decoder().decodeBuffer(auth.substring(5));
                    int off = 0, length, offset;
                    if (msg[8] == 1) {
                        logger.debug("STEP2a: NTLM");

                        byte z = 0;
                        byte[] msg1 = { (byte) 'N', (byte) 'T', (byte) 'L', (byte) 'M', (byte) 'S', (byte) 'S',
                                (byte) 'P', z, (byte) 2, z, z, z, z, z, z, z, (byte) 40, z, z, z, (byte) 1,
                                (byte) 130, z, z, z, (byte) 2, (byte) 2, (byte) 2, z, z, z, z, z, z, z, z, z, z,
                                z, z };
                        // httpResponse.setHeader("WWW-Authenticate",
                        // "NTLM " + new
                        // sun.misc.BASE64Encoder().encodeBuffer(msg1));
                        httpResponse.setHeader("WWW-Authenticate", "NTLM " + Base64.encodeBase64String(msg1));
                        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                        return;

                    } else if (msg[8] == 3) {
                        logger.debug("STEP2b: read data");

                        off = 30;
                        length = msg[off + 17] * 256 + msg[off + 16];
                        offset = msg[off + 19] * 256 + msg[off + 18];
                        workstation = new String(msg, offset, length);

                        length = msg[off + 1] * 256 + msg[off];
                        offset = msg[off + 3] * 256 + msg[off + 2];
                        domain = new String(msg, offset, length);

                        length = msg[off + 9] * 256 + msg[off + 8];
                        offset = msg[off + 11] * 256 + msg[off + 10];
                        username = new String(msg, offset, length);

                        char a = 0;
                        char b = 32;
                        // logger.debug("Username:" +
                        // username.trim().replace(a, b).replaceAll("",
                        // ""));
                        username = username.trim().replace(a, b).replaceAll(" ", "");
                        workstation = workstation.trim().replace(a, b).replaceAll(" ", "");
                        domain = domain.trim().replace(a, b).replaceAll(" ", "");

                        logger.debug("Username: " + username);
                        logger.debug("RemoteHost: " + workstation);
                        logger.debug("Domain: " + domain);

                        chain.doFilter(request, response);
                    }
                }
            } // if IE
              // </editor-fold>

            /*
             * Mirco 30/09/10: Autentico solo con il nome utente senza il
             * prefisso DOMINIO Questo mi e' utile per i nomi importati da
             * LDAP che hanno specificato solo il nome dell'account
             */
            String winUser = username; // domain + "\\" + username;
            try {
                if (winUser != null) {
                    // utenteDaLoggare =
                    // UtentiDAO.getUtenteByWindowsLogin(winUser);
                }
            } catch (Exception e) {
            }

        }
    } catch (RuntimeException e) {
        logger.error("Errore nel Filtro Autenticazione");
        logger.error(e);
        chain.doFilter(request, response);
    } finally {

    }

    logger.debug("Fine Filtro Ntlm");
}

From source file:com.highcharts.export.controller.ExportController.java

@RequestMapping(method = RequestMethod.POST)
public void exporter(@RequestParam(value = "svg", required = false) String svg,
        @RequestParam(value = "type", required = false) String type,
        @RequestParam(value = "filename", required = false) String filename,
        @RequestParam(value = "width", required = false) String width,
        @RequestParam(value = "scale", required = false) String scale,
        @RequestParam(value = "options", required = false) String options,
        @RequestParam(value = "constr", required = false) String constructor,
        @RequestParam(value = "callback", required = false) String callback, HttpServletResponse response,
        HttpServletRequest request) throws ServletException, IOException, InterruptedException,
        SVGConverterException, NoSuchElementException, PoolException, TimeoutException {

    long start1 = System.currentTimeMillis();

    MimeType mime = getMime(type);
    filename = getFilename(filename);/*from  w  w  w.j av a  2s.c o  m*/
    Float parsedWidth = widthToFloat(width);
    Float parsedScale = scaleToFloat(scale);
    options = sanitize(options);
    String input;

    boolean convertSvg = false;

    if (options != null) {
        // create a svg file out of the options
        input = options;
        callback = sanitize(callback);
    } else {
        // assume SVG conversion
        if (svg == null) {
            throw new ServletException("The manadatory svg POST parameter is undefined.");
        } else {
            svg = sanitize(svg);
            if (svg == null) {
                throw new ServletException("The manadatory svg POST parameter is undefined.");
            }
            convertSvg = true;
            input = svg;
        }
    }

    ByteArrayOutputStream stream = null;
    if (convertSvg && mime.equals(MimeType.SVG)) {
        // send this to the client, without converting.
        stream = new ByteArrayOutputStream();
        stream.write(input.getBytes());
    } else {
        //stream = SVGCreator.getInstance().convert(input, mime, constructor, callback, parsedWidth, parsedScale);
        stream = converter.convert(input, mime, constructor, callback, parsedWidth, parsedScale);
    }

    if (stream == null) {
        throw new ServletException("Error while converting");
    }

    logger.debug(request.getHeader("referer") + " Total time: " + (System.currentTimeMillis() - start1));

    response.reset();
    response.setCharacterEncoding("utf-8");
    response.setContentLength(stream.size());
    response.setStatus(HttpStatus.OK.value());
    response.setHeader("Content-disposition",
            "attachment; filename=\"" + filename + "." + mime.name().toLowerCase() + "\"");

    IOUtils.write(stream.toByteArray(), response.getOutputStream());
    response.flushBuffer();
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.directiveCouncil.SummariesControlAction.java

/**
 * Method responsible for exporting 'departmentSummaryResume' to excel file
 * //from   w w w  . j av a  2  s  . c  om
 * @param mapping
 * @param actionForm
 * @param request
 * @param response
 * @return
 * @throws IOException
 */
public ActionForward exportInfoToExcel(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    String departmentID = request.getParameter("departmentID");
    String executionSemesterID = request.getParameter("executionSemesterID");
    String categoryControl = request.getParameter("categoryControl");

    final ExecutionSemester executionSemester = FenixFramework.getDomainObject(executionSemesterID);
    final Department department = FenixFramework.getDomainObject(departmentID);
    SummaryControlCategory summaryControlCategory = null;
    String controlCategory = null;
    if (!StringUtils.isEmpty(categoryControl)) {
        summaryControlCategory = SummaryControlCategory.valueOf(categoryControl);
        controlCategory = BundleUtil.getString(Bundle.ENUMERATION, summaryControlCategory.toString());
    } else {
        controlCategory = "0-100";
    }

    DepartmentSummaryElement departmentSummaryResume = getDepartmentSummaryResume(executionSemester,
            department);
    departmentSummaryResume.setSummaryControlCategory(summaryControlCategory);

    if (departmentSummaryResume != null) {
        String sigla = departmentSummaryResume.getDepartment().getAcronym();
        DateTime dt = new DateTime();
        DateTimeFormatter fmt = DateTimeFormat.forPattern("dd-MM-yyyy");
        String date = fmt.print(dt);

        final String filename = BundleUtil.getString(Bundle.APPLICATION, "link.summaries.control")
                .replaceAll(" ", "_") + "_" + controlCategory + "_" + sigla + "_" + date + ".xls";

        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment; filename=" + filename);
        ServletOutputStream writer = response.getOutputStream();
        exportToXls(departmentSummaryResume, departmentSummaryResume.getDepartment(), executionSemester,
                writer);
        writer.flush();
        response.flushBuffer();
    }

    return null;
}