Example usage for javax.servlet ServletOutputStream write

List of usage examples for javax.servlet ServletOutputStream write

Introduction

In this page you can find the example usage for javax.servlet ServletOutputStream write.

Prototype

public void write(byte b[], int off, int len) throws IOException 

Source Link

Document

Writes len bytes from the specified byte array starting at offset off to this output stream.

Usage

From source file:org.flowable.ui.modeler.service.FlowableDecisionTableService.java

protected void exportDecisionTable(HttpServletResponse response, AbstractModel decisionTableModel) {
    DecisionTableRepresentation decisionTableRepresentation = getDecisionTableRepresentation(
            decisionTableModel);// ww  w.j  a va  2 s. com

    try {

        JsonNode editorJsonNode = objectMapper.readTree(decisionTableModel.getModelEditorJson());

        // URLEncoder.encode will replace spaces with '+', to keep the actual name replacing '+' to '%20'
        String fileName = URLEncoder.encode(decisionTableRepresentation.getName(), "UTF-8").replaceAll("\\+",
                "%20") + ".dmn";
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fileName);

        ServletOutputStream servletOutputStream = response.getOutputStream();
        response.setContentType("application/xml");

        DmnDefinition dmnDefinition = dmnJsonConverter.convertToDmn(editorJsonNode, decisionTableModel.getId(),
                decisionTableModel.getVersion(), decisionTableModel.getLastUpdated());
        byte[] xmlBytes = dmnXmlConverter.convertToXML(dmnDefinition);

        BufferedInputStream in = new BufferedInputStream(new ByteArrayInputStream(xmlBytes));

        byte[] buffer = new byte[8096];
        while (true) {
            int count = in.read(buffer);
            if (count == -1)
                break;
            servletOutputStream.write(buffer, 0, count);
        }

        // Flush and close stream
        servletOutputStream.flush();
        servletOutputStream.close();

    } catch (Exception e) {
        LOGGER.error("Could not export decision table model", e);
        throw new InternalServerErrorException("Could not export decision table model");
    }
}

From source file:org.opensubsystems.core.util.servlet.WebUtils.java

/**
 * Serve files to the Internet.// w  w w. java  2 s.  c om
 *
 * @param hsrpResponse - the servlet response.
 * @param strRealPath - real path to the file to server
 * @throws IOException - an error has occurred while accessing the file or writing response
 */
public static void serveFile(HttpServletResponse hsrpResponse, String strRealPath) throws IOException {
    // TODO: Improve: Figure out, how we don't have to serve the file, 
    // but the webserver will!!! (cos.jar has a method for it, but the license
    // is to prohibitive to use it. Maybe Jetty has one too) 
    Properties prpSettings;
    int iWebFileBufferSize;

    prpSettings = Config.getInstance().getProperties();

    // Load default size of buffer to serve files 
    iWebFileBufferSize = PropertyUtils.getIntPropertyInRange(prpSettings, WEBUTILS_WEBFILE_BUFFER_SIZE,
            WEBFILE_BUFFER_DEFAULT_SIZE, "Size of a buffer to serve files ",
            // Use some reasonable lower limit
            4096,
            // This should be really limited 
            // by size of available memory
            100000000);

    ServletOutputStream sosOut = hsrpResponse.getOutputStream();
    byte[] arBuffer = new byte[iWebFileBufferSize];
    File flImage = new File(strRealPath);
    FileInputStream fisReader = new FileInputStream(flImage);

    // get extension of the file
    String strExt = strRealPath.substring(strRealPath.lastIndexOf(".") + 1, strRealPath.length());
    // set content type for particular extension
    hsrpResponse.setContentType(MimeTypeConstants.getMimeType(strExt));
    hsrpResponse.setBufferSize(WEBFILE_BUFFER_DEFAULT_SIZE);
    hsrpResponse.setContentLength((int) flImage.length());

    // TODO: Performance: BufferedInputStream allocate additional internal 
    // buffer so we have two buffers for each file of given size, evaluate 
    // if this is faster than non buffered read and if it is not, then get 
    // rid of it. But the preference is to get rid of this method all together,
    BufferedInputStream bisReader = new BufferedInputStream(fisReader, iWebFileBufferSize);
    int iRead;

    try {
        while (true) {
            iRead = bisReader.read(arBuffer);
            if (iRead != -1) {
                sosOut.write(arBuffer, 0, iRead);
            } else {
                break;
            }
        }
    } finally {
        try {
            fisReader.close();
        } finally {
            sosOut.close();
        }
    }
}

From source file:com.aaasec.sigserv.csspserver.SpServlet.java

/**
 * Processes requests for both HTTP/*  ww  w  .j  a v  a2  s.  com*/
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");

    SpSession session = getSession(request, response);

    RequestModel req = reqFactory.getRequestModel(request, session);
    AuthData authdata = req.getAuthData();

    // Supporting devmode login
    if (SpModel.isDevmode()) {
        authdata = TestIdentities.getTestID(request, req);
        req.setAuthData(authdata);
        if (authdata.getAuthType().length() == 0) {
            authdata.setAuthType("devlogin");
        }
        session.setIdpEntityId(authdata.getIdpEntityID());
        session.setSignerAttribute(RequestModelFactory.getAttrOidString(authdata.getIdAttribute()));
        session.setSignerId(authdata.getId());
    }

    //Terminate if no valid request data
    if (req == null) {
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        response.getWriter().write("");
        return;
    }

    // Handle form post from web page
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        response.getWriter().write(SpServerLogic.processFileUpload(request, response, req));
        return;
    }

    // Handle auth data request 
    if (req.getAction().equals("authdata")) {
        response.setContentType("application/json");
        response.setHeader("Cache-Control", "no-cache");
        response.getWriter().write(gson.toJson(authdata));
        return;
    }

    // Get list of serverstored xml documents
    if (req.getAction().equals("doclist")) {
        response.setContentType("application/json");
        response.getWriter().write(SpServerLogic.getDocList());
        return;
    }

    // Provide info about the session for logout handling
    if (req.getAction().equals("logout")) {
        response.setContentType("application/json");
        Logout lo = new Logout();
        lo.authType = (request.getAuthType() == null) ? "" : request.getAuthType();
        lo.devmode = String.valueOf(SpModel.isDevmode());
        response.getWriter().write(gson.toJson(lo));
        return;
    }

    // Respons to a client alive check to test if the server session is alive
    if (req.getAction().equals("alive")) {
        response.setContentType("application/json");
        response.getWriter().write("[]");
        return;
    }

    // Handle sign request and return Xhtml form with post data to the signature server
    if (req.getAction().equals("sign")) {
        boolean addSignMessage = (req.getParameter().equals("message"));
        String xhtml = SpServerLogic.prepareSignRedirect(req, addSignMessage);
        response.getWriter().write(xhtml);
        return;
    }

    // Get status data about the current session
    if (req.getAction().equals("status")) {
        response.setContentType("application/json");
        response.getWriter().write(gson.toJson(session.getStatus()));
        return;
    }

    // Handle a declined sign request
    if (req.getAction().equals("declined")) {
        if (SpModel.isDevmode()) {
            response.sendRedirect("index.jsp?declined=true");
            return;
        }
        response.sendRedirect("https://eid2cssp.3xasecurity.com/sign/index.jsp?declined=true");
        return;
    }

    // Return Request and response data as a file.
    if (req.getAction().equalsIgnoreCase("getReqRes")) {
        response.setContentType("text/xml;charset=UTF-8");
        byte[] data = TestCases.getRawData(req);
        BufferedInputStream fis = new BufferedInputStream(new ByteArrayInputStream(data));
        ServletOutputStream output = response.getOutputStream();
        if (req.getParameter().equalsIgnoreCase("download")) {
            response.setHeader("Content-Disposition", "attachment; filename=" + req.getId() + ".xml");
        }

        int readBytes = 0;
        byte[] buffer = new byte[10000];
        while ((readBytes = fis.read(buffer, 0, 10000)) != -1) {
            output.write(buffer, 0, readBytes);
        }
        output.flush();
        output.close();
        fis.close();
        return;
    }

    // Return the signed document
    if (req.getAction().equalsIgnoreCase("getSignedDoc")
            || req.getAction().equalsIgnoreCase("getUnsignedDoc")) {
        // If the request if for a plaintext document, or only if the document has a valid signature
        if (session.getStatus().signedDocValid || req.getAction().equalsIgnoreCase("getUnsignedDoc")) {
            response.setContentType(session.getDocumentType().getMimeType());
            switch (session.getDocumentType()) {
            case XML:
                response.getWriter().write(new String(session.getSignedDoc(), Charset.forName("UTF-8")));
                return;
            case PDF:
                File docFile = session.getDocumentFile();
                if (req.getAction().equalsIgnoreCase("getSignedDoc") && session.getStatus().signedDocValid) {
                    docFile = session.getSigFile();
                }
                FileInputStream fis = new FileInputStream(docFile);
                ServletOutputStream output = response.getOutputStream();
                if (req.getParameter().equalsIgnoreCase("download")) {
                    response.setHeader("Content-Disposition", "attachment; filename=" + "signedPdf.pdf");
                }

                int readBytes = 0;
                byte[] buffer = new byte[10000];
                while ((readBytes = fis.read(buffer, 0, 10000)) != -1) {
                    output.write(buffer, 0, readBytes);
                }
                output.flush();
                output.close();
                fis.close();
                return;
            }
            return;
        } else {
            if (SpModel.isDevmode()) {
                response.sendRedirect("index.jsp");
                return;
            }
            response.sendRedirect("https://eid2cssp.3xasecurity.com/sign/index.jsp");
            return;
        }
    }

    // Process a sign response from the signature server
    if (req.getSigResponse().length() > 0) {
        try {
            byte[] sigResponse = Base64Coder.decode(req.getSigResponse().trim());

            // Handle response
            SpServerLogic.completeSignedDoc(sigResponse, req);

        } catch (Exception ex) {
        }
        if (SpModel.isDevmode()) {
            response.sendRedirect("index.jsp");
            return;
        }
        response.sendRedirect("https://eid2cssp.3xasecurity.com/sign/index.jsp");
        return;
    }

    // Handle testcases
    if (req.getAction().equals("test")) {
        boolean addSignMessage = (req.getParameter().equals("message"));
        String xhtml = TestCases.prepareTestRedirect(request, response, req, addSignMessage);
        respond(response, xhtml);
        return;
    }

    // Get test data for display such as request data, response data, certificates etc.
    if (req.getAction().equals("info")) {
        switch (session.getDocumentType()) {
        case PDF:
            File returnFile = null;
            if (req.getId().equalsIgnoreCase("document")) {
                respond(response, getDocIframe("getUnsignedDoc", needPdfDownloadButton(request)));
            }
            if (req.getId().equalsIgnoreCase("formSigDoc")) {
                respond(response, getDocIframe("getSignedDoc", needPdfDownloadButton(request)));
            }
            respond(response, TestCases.getTestData(req));
            return;
        default:
            respond(response, TestCases.getTestData(req));
            return;
        }
    }

    if (req.getAction().equals("verify")) {
        response.setContentType("text/xml;charset=UTF-8");
        String sigVerifyReport = TestCases.getTestData(req);
        if (sigVerifyReport != null) {
            respond(response, sigVerifyReport);
            return;
        }
    }

    nullResponse(response);
}

From source file:fr.insalyon.creatis.vip.query.server.rpc.FileDownload.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    User user = (User) req.getSession().getAttribute(CoreConstants.SESSION_USER);
    String queryId = req.getParameter("queryid");
    String path = req.getParameter("path");
    String queryName = req.getParameter("name");
    String tab[] = path.split("/");

    if (user != null && queryId != null && !queryId.isEmpty()) {

        try {//from   w  ww. j a  v a2 s.  com

            String k = new String();

            int l = tab.length;
            for (int i = 0; i < l - 1; i++) {
                k += "//" + tab[i];
            }
            File file = new File(k);
            logger.info("that" + k);
            if (file.isDirectory()) {

                file = new File(k + "/" + tab[l - 1]);

            }
            int length = 0;
            ServletOutputStream op = resp.getOutputStream();
            ServletContext context = getServletConfig().getServletContext();
            String mimetype = context.getMimeType(file.getName());

            logger.info("(" + user.getEmail() + ") Downloading '" + file.getAbsolutePath() + "'.");

            resp.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
            resp.setContentLength((int) file.length());
            //name of the file in servlet download
            resp.setHeader("Content-Disposition", "attachment; filename=\"" + queryName + "_"
                    + getCurrentTimeStamp().toString().replaceAll(" ", "_") + ".txt" + "\"");

            byte[] bbuf = new byte[4096];
            DataInputStream in = new DataInputStream(new FileInputStream(file));

            while ((in != null) && ((length = in.read(bbuf)) != -1)) {
                op.write(bbuf, 0, length);
            }

            in.close();
            op.flush();
            op.close();
        } catch (Exception ex) {
            logger.error(ex);
        }

    }
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.harvester.FileHarvestController.java

private void doDownloadTemplatePost(HttpServletRequest request, HttpServletResponse response) {

    VitroRequest vreq = new VitroRequest(request);
    FileHarvestJob job = getJob(vreq, vreq.getParameter(PARAMETER_JOB));
    File fileToSend = new File(job.getTemplateFilePath());

    response.setContentType("application/octet-stream");
    response.setContentLength((int) (fileToSend.length()));
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileToSend.getName() + "\"");

    try {//from  ww w.ja v a2s.  co  m
        byte[] byteBuffer = new byte[(int) (fileToSend.length())];
        DataInputStream inStream = new DataInputStream(new FileInputStream(fileToSend));

        ServletOutputStream outputStream = response.getOutputStream();
        for (int length = inStream.read(byteBuffer); length != -1; length = inStream.read(byteBuffer)) {
            outputStream.write(byteBuffer, 0, length);
        }

        inStream.close();
        outputStream.flush();
        outputStream.close();
    } catch (IOException e) {
        log.error(e, e);
    }
}

From source file:jp.co.opentone.bsol.framework.web.view.util.ViewHelper.java

protected void doDownload(HttpServletResponse response, InputStream in) throws IOException {
    ServletOutputStream o = getServletOutputStream(response);
    try {//from  w  ww  .j a  va2  s  .  c o m
        final int bufLength = 4096;
        byte[] buf = new byte[bufLength];
        int i = 0;
        while ((i = in.read(buf, 0, buf.length)) != -1) {
            o.write(buf, 0, i);
        }

        o.flush();
        o.close();
    } catch (IOException e) {
        if (isDownloadCanceled(e)) {
            log.warn("Download canceled.");
        } else {
            throw e;
        }
    }
}

From source file:org.agnitas.web.ExportWizardAction.java

/**
 * Process the specified HTTP request, and create the corresponding HTTP
 * response (or forward to another web component that will create it).
 * Return an <code>ActionForward</code> instance describing where and how
 * control should be forwarded, or <code>null</code> if the response has
 * already been completed.//  ww w  . j  av a 2s  . c  o m
 * <br>
* ACTION_LIST: forwards to predefined export definition list page.
* <br><br>
* ACTION_QUERY: loads chosen predefined export definition data into form or, if there was "Back" button pressed,<br>
 *     clears form data; loads lists of target group and mailing lists into form; <br>
 *     forwards to predefined export definition query page.
* <br><br>
 * ACTION_COLLECT_DATA: proceeds exporting recipients from database according to the export definition;<br>
 *     provides storing the export result in temporary zip file, stores name of the temporary file in form;
 *     forwards to export view page.
 * <br><br>
 * ACTION_VIEW_STATUS_WINDOW: forwards to export view page.
 * <br><br>
 * ACTION_DOWNLOAD: provides downloading prepared zip file with list of recipients for export; sends notification <br>
 *     email with export report for admin if the current admin have this option.
* <br><br>
 * ACTION_SAVE_QUESTION: forwards to page for edit export definition name and description.
* <br><br>
 * ACTION_SAVE: checks the name of export definition:<br>
 *     if it is not filled or its length is less than 3 chars - forwards to page for editing export definition
 *     name and description and shows validation error message<br>
 *     if the name is valid, checks the export definition id value. If id of export definition is 0, inserts new
 *     export definition db entry, otherwise updates db entry with given id.<br>
 *     Forwards to export definition list page.
 * <br><br>
* ACTION_CONFIRM_DELETE: checks if an ID of export definition is given and loads the export definition data;<br>
 *     forwards to jsp with question to confirm deletion.
* <br><br>
* ACTION_DELETE: marks the chosen predefined export definition as deleted and saves the changes in database;<br>
 *     forwards to predefined export definition list page.
* <br><br>
* Any other ACTION_* would cause a forward to "query"
 * <br><br>
 * @param form ActionForm object, data for the action filled by the jsp
 * @param req HTTP request
 * @param res HTTP response
 * @param mapping The ActionMapping used to select this instance
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet exception occurs
 * @return destination specified in struts-config.xml to forward to next jsp
 */
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest req,
        HttpServletResponse res) throws IOException, ServletException {

    // Validate the request parameters specified by the user
    ExportWizardForm aForm = null;
    ActionMessages errors = new ActionMessages();
    ActionForward destination = null;
    ApplicationContext aContext = this.getWebApplicationContext();

    if (!AgnUtils.isUserLoggedIn(req)) {
        return mapping.findForward("logon");
    }

    if (form != null) {
        aForm = (ExportWizardForm) form;
    } else {
        aForm = new ExportWizardForm();
    }

    AgnUtils.userlogger().info("Action: " + aForm.getAction());

    if (!allowed("wizard.export", req)) {
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.permissionDenied"));
        saveErrors(req, errors);
        return null;
    }
    try {
        switch (aForm.getAction()) {

        case ExportWizardAction.ACTION_LIST:
            destination = mapping.findForward("list");
            break;

        case ExportWizardAction.ACTION_QUERY:
            if (req.getParameter("exportPredefID").toString().compareTo("0") != 0) {
                loadPredefExportFromDB(aForm, aContext, req);
            } else {
                // clear form data if the "back" button has not been pressed:
                if (!AgnUtils.parameterNotEmpty(req, "exp_back.x")) {
                    aForm.clearData();
                }
            }

            int companyID = AgnUtils.getCompanyID(req);
            aForm.setTargetGroups(targetDao.getTargets(companyID, false));
            aForm.setMailinglistObjects(mailinglistDao.getMailinglists(companyID));

            aForm.setAction(ExportWizardAction.ACTION_COLLECT_DATA);
            destination = mapping.findForward("query");
            break;

        case ExportWizardAction.ACTION_COLLECT_DATA:
            if (aForm.tryCollectingData()) {
                aForm.setAction(ExportWizardAction.ACTION_VIEW_STATUS);
                //                        RequestDispatcher dp=req.getRequestDispatcher(mapping.findForward("view").getPath());
                //                        dp.forward(req, res);
                //                        res.flushBuffer();
                //                        destination=null;
                destination = mapping.findForward("view");
                collectContent(aForm, aContext, req);
                aForm.resetCollectingData();
                AgnUtils.userlogger().info(AgnUtils.getAdmin(req).getUsername() + ": do export "
                        + aForm.getLinesOK() + " recipients");
            } else {
                errors.add("global", new ActionMessage("error.export.already_exporting"));
            }
            break;

        case ExportWizardAction.ACTION_VIEW_STATUS_WINDOW:
            destination = mapping.findForward("view_status");
            break;

        case ExportWizardAction.ACTION_DOWNLOAD:
            byte bytes[] = new byte[16384];
            int len = 0;
            File outfile = aForm.getCsvFile();

            if (outfile != null && aForm.tryCollectingData()) {
                if (req.getSession().getAttribute("notify_email") != null) {
                    String to_email = (String) req.getSession().getAttribute("notify_email");
                    if (to_email.trim().length() > 0) {
                        AgnUtils.sendEmail("openemm@localhost", to_email, "EMM Data-Export",
                                this.generateReportText(aForm, req), null, 0, "iso-8859-1");
                    }
                }

                aForm.resetCollectingData();
                FileInputStream instream = new FileInputStream(outfile);
                res.setContentType("application/zip");
                res.setHeader("Content-Disposition", "attachment; filename=\"" + outfile.getName() + "\";");
                res.setContentLength((int) outfile.length());
                ServletOutputStream ostream = res.getOutputStream();
                while ((len = instream.read(bytes)) != -1) {
                    ostream.write(bytes, 0, len);
                }
                destination = null;
            } else {
                errors.add("global", new ActionMessage("error.export.file_not_ready"));
            }
            break;

        case ExportWizardAction.ACTION_SAVE_QUESTION:
            aForm.setAction(ExportWizardAction.ACTION_SAVE);
            destination = mapping.findForward("savemask");
            break;

        case ExportWizardAction.ACTION_SAVE:
            if (aForm.getShortname() == null || aForm.getShortname().length() < 3) {
                errors.add("shortname", new ActionMessage("error.nameToShort"));
                //aForm.setAction(ExportWizardAction.ACTION_SAVE);
                destination = mapping.findForward("savemask");
            } else if (aForm.getExportPredefID() != 0) {
                saveExport(aForm, aContext, req);
                destination = mapping.findForward("list");
            } else {
                insertExport(aForm, aContext, req);
                destination = mapping.findForward("list");
            }
            break;

        case ExportWizardAction.ACTION_CONFIRM_DELETE:
            if (!"0".equals(req.getParameter("exportPredefID"))) {
                loadPredefExportFromDB(aForm, aContext, req);
            }
            aForm.setAction(ExportWizardAction.ACTION_DELETE);
            destination = mapping.findForward("delete_question");
            break;

        case ExportWizardAction.ACTION_DELETE:
            if (!req.getParameter("exportPredefID").equals("0")) {
                markExportDeletedInDB(aForm, aContext, req);
            }
            destination = mapping.findForward("list");
            break;

        default:
            aForm.setAction(ExportWizardAction.ACTION_QUERY);
            destination = mapping.findForward("query");
        }

        List<ExportPredef> exports = exportPredefDao
                .getAllByCompany(AgnUtils.getAdmin(req).getCompany().getId());
        aForm.setExportPredefList(exports);
        aForm.setExportPredefCount(exports.size());

    } catch (Exception e) {
        AgnUtils.userlogger().error("execute: " + e + "\n" + AgnUtils.getStackTrace(e));
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.exception"));
    }

    // Report any errors we have discovered back to the original form
    if (!errors.isEmpty()) {
        saveErrors(req, errors);
        if (destination == null)
            return new ActionForward(mapping.getInput());
    }

    return destination;
}

From source file:br.com.hslife.orcamento.controller.LancamentoContaController.java

@SuppressWarnings("resource")
public void exportarLancamentos() {
    if (listEntity == null || listEntity.isEmpty()) {
        warnMessage("Listagem vazio. Nada a exportar.");
    }/*from ww  w.j av a 2  s.  c  om*/

    try {

        HSSFWorkbook excel = new HSSFWorkbook();
        HSSFSheet planilha = excel.createSheet("lancamentoConta");

        HSSFRow linha = planilha.createRow(0);

        HSSFCell celula = linha.createCell(0);
        celula.setCellValue("Data");
        celula = linha.createCell(1);
        celula.setCellValue("Histrico");
        celula = linha.createCell(2);
        celula.setCellValue("Valor");

        int linhaIndex = 1;
        for (LancamentoConta l : listEntity) {
            linha = planilha.createRow(linhaIndex);

            celula = linha.createCell(0);
            celula.setCellValue(Util.formataDataHora(l.getDataPagamento(), Util.DATA));

            celula = linha.createCell(1);
            celula.setCellValue(l.getDescricao());

            celula = linha.createCell(2);
            celula.setCellValue(l.getValorPago());

            linhaIndex++;
        }

        HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance()
                .getExternalContext().getResponse();
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename=lancamentoConta.xls");
        response.setContentLength(excel.getBytes().length);
        ServletOutputStream output = response.getOutputStream();
        output.write(excel.getBytes(), 0, excel.getBytes().length);
        FacesContext.getCurrentInstance().responseComplete();

    } catch (IOException e) {
        errorMessage(e.getMessage());
    }
}

From source file:com.francelabs.datafari.servlets.URL.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
 *      response)//  w w  w  .jav a 2s . co m
 */
@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {

    request.setCharacterEncoding("UTF-8");

    final String protocol = request.getScheme() + ":";

    final Map<String, String[]> requestMap = new HashMap<>();
    requestMap.putAll(request.getParameterMap());
    final IndexerQuery query = IndexerServerManager.createQuery();
    query.addParams(requestMap);
    // get the AD domain
    String domain = "";
    HashMap<String, String> h;
    try {
        h = RealmLdapConfiguration.getConfig(request);

        if (h.get(RealmLdapConfiguration.ATTR_CONNECTION_NAME) != null) {
            final String userBase = h.get(RealmLdapConfiguration.ATTR_DOMAIN_NAME).toLowerCase();
            final String[] parts = userBase.split(",");
            domain = "";
            for (int i = 0; i < parts.length; i++) {
                if (parts[i].indexOf("dc=") != -1) { // Check if the current
                    // part is a domain
                    // component
                    if (!domain.isEmpty()) {
                        domain += ".";
                    }
                    domain += parts[i].substring(parts[i].indexOf('=') + 1);
                }
            }
        }

        // Add authentication
        if (request.getUserPrincipal() != null) {
            String AuthenticatedUserName = request.getUserPrincipal().getName().replaceAll("[^\\\\]*\\\\", "");
            if (AuthenticatedUserName.contains("@")) {
                AuthenticatedUserName = AuthenticatedUserName.substring(0, AuthenticatedUserName.indexOf("@"));
            }
            if (!domain.equals("")) {
                AuthenticatedUserName += "@" + domain;
            }
            query.setParam("AuthenticatedUserName", AuthenticatedUserName);
        }
    } catch (final Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    StatsPusher.pushDocument(query, protocol);

    // String surl = URLDecoder.decode(request.getParameter("url"),
    // "ISO-8859-1");
    final String surl = request.getParameter("url");

    if (ScriptConfiguration.getProperty("ALLOWLOCALFILEREADING").equals("true")
            && !surl.startsWith("file://///")) {

        final int BUFSIZE = 4096;
        String fileName = null;

        /**
         * File Display/Download --> <!-- Written by Rick Garcia -->
         */
        if (SystemUtils.IS_OS_LINUX) {
            // try to open the file locally
            final String fileNameA[] = surl.split(":");
            fileName = URLDecoder.decode(fileNameA[1], "UTF-8");

        } else if (SystemUtils.IS_OS_WINDOWS) {
            fileName = URLDecoder.decode(surl, "UTF-8").replaceFirst("file:/", "");
        }

        final File file = new File(fileName);
        int length = 0;
        final ServletOutputStream outStream = response.getOutputStream();
        final ServletContext context = getServletConfig().getServletContext();
        String mimetype = context.getMimeType(fileName);

        // sets response content type
        if (mimetype == null) {
            mimetype = "application/octet-stream";

        }
        response.setContentType(mimetype);
        response.setContentLength((int) file.length());

        // sets HTTP header
        response.setHeader("Content-Disposition", "inline; fileName=\"" + fileName + "\"");

        final byte[] byteBuffer = new byte[BUFSIZE];
        final DataInputStream in = new DataInputStream(new FileInputStream(file));

        // reads the file's bytes and writes them to the response stream
        while (in != null && (length = in.read(byteBuffer)) != -1) {
            outStream.write(byteBuffer, 0, length);
        }

        in.close();
        outStream.close();
    } else {

        final RequestDispatcher rd = request.getRequestDispatcher(redirectUrl);
        rd.forward(request, response);
    }
}

From source file:org.freeeed.search.web.controller.CaseFileDownloadController.java

@Override
public ModelAndView execute() {
    HttpSession session = this.request.getSession(true);
    SolrSessionObject solrSession = (SolrSessionObject) session
            .getAttribute(WebConstants.WEB_SESSION_SOLR_OBJECT);

    if (solrSession == null || solrSession.getSelectedCase() == null) {
        return new ModelAndView(WebConstants.CASE_FILE_DOWNLOAD);
    }//from  w ww  . ja v  a2s  .co  m

    Case selectedCase = solrSession.getSelectedCase();

    String action = (String) valueStack.get("action");

    log.debug("Action called: " + action);

    File toDownload = null;
    boolean htmlMode = false;

    String docPath = (String) valueStack.get("docPath");
    String uniqueId = (String) valueStack.get("uniqueId");

    try {
        if ("exportNative".equals(action)) {
            toDownload = caseFileService.getNativeFile(selectedCase.getName(), docPath, uniqueId);

        } else if ("exportImage".equals(action)) {
            toDownload = caseFileService.getImageFile(selectedCase.getName(), docPath, uniqueId);
        } else if ("exportHtml".equals(action)) {
            toDownload = caseFileService.getHtmlFile(selectedCase.getName(), docPath, uniqueId);
            htmlMode = true;
        } else if ("exportHtmlImage".equals(action)) {
            toDownload = caseFileService.getHtmlImageFile(selectedCase.getName(), docPath);
            htmlMode = true;
        } else if ("exportNativeAll".equals(action)) {
            String query = solrSession.buildSearchQuery();
            int rows = solrSession.getTotalDocuments();

            List<SolrDocument> docs = getDocumentPaths(query, 0, rows);

            toDownload = caseFileService.getNativeFiles(selectedCase.getName(), docs);

        } else if ("exportNativeAllFromSource".equals(action)) {
            String query = solrSession.buildSearchQuery();
            int rows = solrSession.getTotalDocuments();

            List<SolrDocument> docs = getDocumentPaths(query, 0, rows);

            String source = (String) valueStack.get("source");
            try {
                source = URLDecoder.decode(source, "UTF-8");
            } catch (UnsupportedEncodingException e) {
            }

            toDownload = caseFileService.getNativeFilesFromSource(source, docs);
        } else if ("exportImageAll".equals(action)) {
            String query = solrSession.buildSearchQuery();
            int rows = solrSession.getTotalDocuments();

            List<SolrDocument> docs = getDocumentPaths(query, 0, rows);
            toDownload = caseFileService.getImageFiles(selectedCase.getName(), docs);
        }
    } catch (Exception e) {
        log.error("Problem sending cotent", e);
        valueStack.put("error", true);
    }

    if (toDownload != null) {
        try {
            int length = 0;
            ServletOutputStream outStream = response.getOutputStream();
            String mimetype = "application/octet-stream";
            if (htmlMode) {
                mimetype = "text/html";
            }

            response.setContentType(mimetype);
            response.setContentLength((int) toDownload.length());
            String fileName = toDownload.getName();

            if (!htmlMode) {
                // sets HTTP header
                response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            }

            byte[] byteBuffer = new byte[1024];
            DataInputStream in = new DataInputStream(new FileInputStream(toDownload));

            // reads the file's bytes and writes them to the response stream
            while ((in != null) && ((length = in.read(byteBuffer)) != -1)) {
                outStream.write(byteBuffer, 0, length);
            }

            in.close();
            outStream.close();
        } catch (Exception e) {
            log.error("Problem sending cotent", e);
            valueStack.put("error", true);
        }
    } else {
        valueStack.put("error", true);
    }

    return new ModelAndView(WebConstants.CASE_FILE_DOWNLOAD);
}