Example usage for javax.servlet.http HttpServletResponse getOutputStream

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

Introduction

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

Prototype

public ServletOutputStream getOutputStream() throws IOException;

Source Link

Document

Returns a ServletOutputStream suitable for writing binary data in the response.

Usage

From source file:org.openmrs.module.omodexport.util.OmodExportUtil.java

/**
 * Utility method for exporting a module with its dependencies
 * //from ww w  . j ava  2 s  .c om
 * @param module -The module to export. It will be exported with all its dependencies and
 *            compressed in a file called "modules.zip"
 * @param response
 * @throws IOException
 */
public static void exportModuleWithDependecies(Module module, HttpServletResponse response) throws IOException {
    List<File> files = new ArrayList<File>();
    List<String> dependecies = module.getRequiredModules();
    for (String name : dependecies) {
        Module m = ModuleFactory.getModuleByPackage(name);
        files.add(m.getFile());
    }
    files.add(module.getFile());

    response.setContentType("application/zip");
    response.setHeader("Content-Disposition", "attachment; filename=\"modules.ZIP\"");

    ZipOutputStream out = new ZipOutputStream(response.getOutputStream());

    zipFiles(files, out);
}

From source file:com.iyonger.apm.web.util.FileDownloadUtils.java

/**
 * Download the given file to the given {@link HttpServletResponse}.
 *
 * @param response {@link HttpServletResponse}
 * @param file     file path/*from  w w  w .ja v  a  2  s  .  c  om*/
 * @return true if succeeded
 */
public static boolean downloadFile(HttpServletResponse response, File file) {
    if (file == null || !file.exists()) {
        return false;
    }
    boolean result = true;
    response.reset();
    response.addHeader("Content-Disposition", "attachment;filename=" + file.getName());
    response.setContentType("application/octet-stream");
    response.addHeader("Content-Length", "" + file.length());
    InputStream fis = null;
    byte[] buffer = new byte[FILE_DOWNLOAD_BUFFER_SIZE];
    OutputStream toClient = null;
    try {
        fis = new BufferedInputStream(new FileInputStream(file));
        toClient = new BufferedOutputStream(response.getOutputStream());
        int readLength;
        while (((readLength = fis.read(buffer)) != -1)) {
            toClient.write(buffer, 0, readLength);
        }
        toClient.flush();
    } catch (FileNotFoundException e) {
        LOGGER.error("file not found:" + file.getAbsolutePath(), e);
        result = false;
    } catch (IOException e) {
        LOGGER.error("read file error:" + file.getAbsolutePath(), e);
        result = false;
    } finally {
        IOUtils.closeQuietly(fis);
        IOUtils.closeQuietly(toClient);
    }
    return result;
}

From source file:com.invbf.sistemagestionmercadeo.reportes.ReportCreator.java

public static void generadorPreorden(Solicitudentregalotesmaestro elemento) {
    try {/*from  ww  w .ja  v  a2 s .co m*/
        ActaREciboCustodiaBonosCajaBean elementoReporte = new ActaREciboCustodiaBonosCajaBean();
        elementoReporte.setActnumber(elemento.getId().toString());
        elementoReporte.setBonosPorDenominacionEntregars(new ArrayList<ListaBonosPorDenominacionEntregar>());
        List<bonosnoincluidos> bonosnoincluidos = new ArrayList<bonosnoincluidos>();
        for (Solicitudentregalote sel : elemento.getSolicitudentregaloteList()) {
            ListaBonosPorDenominacionEntregar lbde = new ListaBonosPorDenominacionEntregar();
            lbde.setCantidad(sel.getCantidad().toString());
            lbde.setDenominacion(getAsString(sel.getLotesBonosid().getDenominacion().getValor() + " "));

            if (sel.getLotesBonosid().getTipoBono().getNombre().equals("PROMOCIONAL")) {
                lbde.setSaladejuego(sel.getLotesBonosid().getIdCasino().getCasinodetalle().getAbreCiudad() + " "
                        + sel.getLotesBonosid().getTipoBono().getNombre());
                lbde.setDel(sel.getLotesBonosid().getIdCasino().getCasinodetalle().getAbreCiudad() + "-"
                        + sel.getDesde());
                lbde.setAl(sel.getLotesBonosid().getIdCasino().getCasinodetalle().getAbreCiudad() + "-"
                        + sel.getHasta());
            } else {
                lbde.setSaladejuego(sel.getLotesBonosid().getIdCasino().getCasinodetalle().getAbrenopromo()
                        + " " + sel.getLotesBonosid().getTipoBono().getNombre());
                lbde.setDel(sel.getLotesBonosid().getIdCasino().getCasinodetalle().getAbrenopromo() + "-"
                        + sel.getDesde());
                lbde.setAl(sel.getLotesBonosid().getIdCasino().getCasinodetalle().getAbrenopromo() + "-"
                        + sel.getHasta());
            }
            elementoReporte.getBonosPorDenominacionEntregars().add(lbde);
            String bonosnoincluidosString = "Bono " + sel.getLotesBonosid().getTipoBono().getNombre() + " "
                    + " / " + sel.getLotesBonosid().getDenominacion().getValor() + " / Faltantes: ";
            if (sel.getBononoincluidoList().isEmpty()) {
                for (Bononoincluido bonosnoincluido : sel.getBononoincluidoList()) {
                    bonosnoincluidosString += " " + bonosnoincluido.getConsecutivo();
                }

                bonosnoincluidos.add(new bonosnoincluidos(bonosnoincluidosString));
            }
        }

        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        InputStream input = externalContext
                .getResourceAsStream("/resources/reportes/OrdenProduccionLoteBono.jasper");
        InputStream subreport = externalContext
                .getResourceAsStream("/resources/reportes/ReciboCustodiaBonosCaja_detalle.jasper");
        InputStream logotexas = externalContext.getResourceAsStream("/resources/reportes/LogoTLCNegro-01.jpeg");
        InputStream logomasters = externalContext.getResourceAsStream("/resources/reportes/IBFLogo01jpeg.jpeg");
        InputStream logoibf = externalContext.getResourceAsStream("/resources/reportes/LogoMRCNegro.jpeg");
        ImageIcon tlc = new ImageIcon(IOUtils.toByteArray(logotexas));
        ImageIcon mrc = new ImageIcon(IOUtils.toByteArray(logomasters));
        ImageIcon ibf = new ImageIcon(IOUtils.toByteArray(logoibf));
        elementoReporte.setIbf(ibf.getImage());
        elementoReporte.setMrc(mrc.getImage());
        elementoReporte.setTlc(tlc.getImage());
        elementoReporte.setBonosnoincluidos(bonosnoincluidos);
        List<ActaREciboCustodiaBonosCajaBean> lista = new ArrayList<ActaREciboCustodiaBonosCajaBean>();
        lista.add(elementoReporte);
        JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(lista);
        JasperReport jasperMasterReport = (JasperReport) JRLoader.loadObject(input);
        JasperReport jasperSubReport = (JasperReport) JRLoader.loadObject(subreport);
        elementoReporte.setSubreportParameter(jasperSubReport);
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("actnumber", lista.get(0).getActnumber());
        parameters.put("tlc", lista.get(0).getTlc());
        parameters.put("ibf", lista.get(0).getIbf());
        parameters.put("mrc", lista.get(0).getMrc());
        parameters.put("subreportParameter", jasperSubReport);

        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperMasterReport, parameters,
                beanColDataSource);
        HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance()
                .getExternalContext().getResponse();
        httpServletResponse.addHeader("Content-disposition",
                "attachment; filename=OrdenProduccionLotesBonos" + elemento.getId() + ".pdf");
        ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
        JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);
    } catch (JRException ex) {
        Logger.getLogger(GeneradorSolicitudLotesBonos.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(GeneradorSolicitudLotesBonos.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.eryansky.common.web.utils.DownloadUtils.java

/**
 * /*from w  ww . ja v a2s  . co m*/
 * @param request
 * @param response
 * @param inputStream ?
 * @param displayName ??
 * @throws IOException
 */
public static void download(HttpServletRequest request, HttpServletResponse response, InputStream inputStream,
        String displayName) throws IOException {
    response.reset();
    WebUtils.setNoCacheHeader(response);

    response.setContentType("application/x-download");
    response.setContentLength((int) inputStream.available());

    //        String displayFilename = displayName.substring(displayName.lastIndexOf("_") + 1);
    //        displayFilename = displayFilename.replace(" ", "_");
    WebUtils.setDownloadableHeader(request, response, displayName);
    BufferedInputStream is = null;
    OutputStream os = null;
    try {

        os = response.getOutputStream();
        is = new BufferedInputStream(inputStream);
        IOUtils.copy(is, os);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:com.invbf.sistemagestionmercadeo.reportes.ReportCreator.java

public static void generadorEntregaBonosCaja(Solicitudentregalotesmaestro elemento) {
    try {/*from   w w  w  .  ja v  a2  s.  c  o m*/
        ActaREciboCustodiaBonosCajaBean elementoReporte = new ActaREciboCustodiaBonosCajaBean();
        elementoReporte.setActnumber(elemento.getId().toString());
        elementoReporte.setBonosPorDenominacionEntregars(new ArrayList<ListaBonosPorDenominacionEntregar>());
        List<bonosnoincluidos> bonosnoincluidos = new ArrayList<bonosnoincluidos>();
        for (Solicitudentregalote sel : elemento.getSolicitudentregaloteList()) {
            ListaBonosPorDenominacionEntregar lbde = new ListaBonosPorDenominacionEntregar();
            lbde.setCantidad(sel.getCantidad().toString());
            lbde.setDenominacion(getAsString(sel.getLotesBonosid().getDenominacion().getValor() + " "));

            if (sel.getLotesBonosid().getTipoBono().getNombre().equals("PROMOCIONAL")) {
                lbde.setSaladejuego(sel.getLotesBonosid().getIdCasino().getCasinodetalle().getAbreCiudad() + " "
                        + sel.getLotesBonosid().getTipoBono().getNombre());
                lbde.setDel(sel.getLotesBonosid().getIdCasino().getCasinodetalle().getAbreCiudad() + "-"
                        + sel.getDesde());
                lbde.setAl(sel.getLotesBonosid().getIdCasino().getCasinodetalle().getAbreCiudad() + "-"
                        + sel.getHasta());
            } else {
                lbde.setSaladejuego(sel.getLotesBonosid().getIdCasino().getCasinodetalle().getAbrenopromo()
                        + " " + sel.getLotesBonosid().getTipoBono().getNombre());
                lbde.setDel(sel.getLotesBonosid().getIdCasino().getCasinodetalle().getAbrenopromo() + "-"
                        + sel.getDesde());
                lbde.setAl(sel.getLotesBonosid().getIdCasino().getCasinodetalle().getAbrenopromo() + "-"
                        + sel.getHasta());
            }
            elementoReporte.getBonosPorDenominacionEntregars().add(lbde);
            String bonosnoincluidosString = "Bono " + sel.getLotesBonosid().getTipoBono().getNombre() + " "
                    + " / " + sel.getLotesBonosid().getDenominacion().getValor() + " / Faltantes: ";
            if (sel.getBononoincluidoList().isEmpty()) {
                for (Bononoincluido bonosnoincluido : sel.getBononoincluidoList()) {
                    bonosnoincluidosString += " " + bonosnoincluido.getConsecutivo();
                }

                bonosnoincluidos.add(new bonosnoincluidos(bonosnoincluidosString));
            }
        }

        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        InputStream input = externalContext
                .getResourceAsStream("/resources/reportes/ReciboCustodiaBonosCaja.jasper");
        InputStream subreport = externalContext
                .getResourceAsStream("/resources/reportes/ReciboCustodiaBonosCaja_detalle.jasper");
        InputStream bonosno = externalContext
                .getResourceAsStream("/resources/reportes/ReciboCustodiaBonosCaja_bonosnoincluidos.jasper");
        InputStream logotexas = externalContext.getResourceAsStream("/resources/reportes/LogoTLCNegro-01.jpeg");
        InputStream logomasters = externalContext.getResourceAsStream("/resources/reportes/IBFLogo01jpeg.jpeg");
        InputStream logoibf = externalContext.getResourceAsStream("/resources/reportes/LogoMRCNegro.jpeg");
        ImageIcon tlc = new ImageIcon(IOUtils.toByteArray(logotexas));
        ImageIcon mrc = new ImageIcon(IOUtils.toByteArray(logomasters));
        ImageIcon ibf = new ImageIcon(IOUtils.toByteArray(logoibf));
        elementoReporte.setIbf(ibf.getImage());
        elementoReporte.setMrc(mrc.getImage());
        elementoReporte.setTlc(tlc.getImage());
        elementoReporte.setBonosnoincluidos(bonosnoincluidos);
        List<ActaREciboCustodiaBonosCajaBean> lista = new ArrayList<ActaREciboCustodiaBonosCajaBean>();
        lista.add(elementoReporte);
        JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(lista);
        JasperReport jasperMasterReport = (JasperReport) JRLoader.loadObject(input);
        JasperReport jasperSubReport = (JasperReport) JRLoader.loadObject(subreport);
        JasperReport bonosnoReport = (JasperReport) JRLoader.loadObject(bonosno);
        elementoReporte.setSubreportParameter(jasperSubReport);
        elementoReporte.setBonosno(bonosnoReport);
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("actnumber", lista.get(0).getActnumber());
        parameters.put("tlc", lista.get(0).getTlc());
        parameters.put("ibf", lista.get(0).getIbf());
        parameters.put("mrc", lista.get(0).getMrc());
        parameters.put("subreportParameter", jasperSubReport);
        parameters.put("bonosno", bonosnoReport);

        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperMasterReport, parameters,
                beanColDataSource);
        HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance()
                .getExternalContext().getResponse();
        httpServletResponse.addHeader("Content-disposition",
                "attachment; filename=ActaReciboCustodiaBonosCaja" + elemento.getId() + ".pdf");
        ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
        JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);
    } catch (JRException ex) {
        Logger.getLogger(GeneradorSolicitudLotesBonos.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(GeneradorSolicitudLotesBonos.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.discovery.darchrow.http.ResponseUtil.java

/**
 * Down load data./*w ww . j  ava2  s .  com*/
 *
 * @param saveFileName
 *            the save file name
 * @param inputStream
 *            the input stream
 * @param contentLength
 *            the content length
 * @param request
 *            the request
 * @param response
 *            the response
 * @throws UncheckedIOException
 *             the unchecked io exception
 */
private static void downLoadData(String saveFileName, InputStream inputStream, Number contentLength,
        HttpServletRequest request, HttpServletResponse response) throws UncheckedIOException {
    Date beginDate = new Date();

    if (log.isInfoEnabled()) {
        log.info("begin download~~,saveFileName:[{}],contentLength:[{}]", saveFileName,
                FileUtil.formatSize(contentLength.longValue()));
    }
    try {
        OutputStream outputStream = response.getOutputStream();

        //? 
        //inputStream.read(buffer);
        //outputStream = new BufferedOutputStream(response.getOutputStream());
        //outputStream.write(buffer);

        IOWriteUtil.write(inputStream, outputStream);
        if (log.isInfoEnabled()) {
            Date endDate = new Date();
            log.info("end download,saveFileName:[{}],contentLength:[{}],time use:[{}]", saveFileName,
                    FileUtil.formatSize(contentLength.longValue()),
                    DateExtensionUtil.getIntervalForView(beginDate, endDate));
        }
    } catch (IOException e) {
        /*
         * ?  ClientAbortException  ????? 
         * ?? ??
         * ???????
         * ? KILL? ?? ClientAbortException
         */
        //ClientAbortException:  java.net.SocketException: Connection reset by peer: socket write error
        final String exceptionName = e.getClass().getName();

        if (StringUtil.isContain(exceptionName, "ClientAbortException")
                || StringUtil.isContain(e.getMessage(), "ClientAbortException")) {
            log.warn(
                    "[ClientAbortException],maybe user use Thunder soft or abort client soft download,exceptionName:[{}],exception message:[{}] ,request User-Agent:[{}]",
                    exceptionName, e.getMessage(), RequestUtil.getHeaderUserAgent(request));
        } else {
            log.error("[download exception],exception name: " + exceptionName, e);
            throw new UncheckedIOException(e);
        }
    }
}

From source file:com.mtt.myapp.common.util.FileDownloadUtil.java

/**
 * Provide file download from the given file path.
 * @param response {@link javax.servlet.http.HttpServletResponse}
 * @param desFile file path//from   w  ww .  java 2 s.  c  o m
 * @return true if succeeded
 */
public static boolean downloadFile(HttpServletResponse response, File desFile) {
    if (desFile == null || !desFile.exists()) {
        return false;
    }
    boolean result = true;
    response.reset();
    response.addHeader("Content-Disposition", "attachment;filename=" + desFile.getName());
    response.setContentType("application/octet-stream");
    response.addHeader("Content-Length", "" + desFile.length());
    InputStream fis = null;
    byte[] buffer = new byte[FILE_DOWNLOAD_BUFFER_SIZE];
    OutputStream toClient = null;
    try {
        fis = new BufferedInputStream(new FileInputStream(desFile));
        toClient = new BufferedOutputStream(response.getOutputStream());
        int readLength;
        while (((readLength = fis.read(buffer)) != -1)) {
            toClient.write(buffer, 0, readLength);
        }
        toClient.flush();
    } catch (FileNotFoundException e) {
        LOGGER.error("file not found:" + desFile.getAbsolutePath(), e);
        result = false;
    } catch (IOException e) {
        LOGGER.error("read file error:" + desFile.getAbsolutePath(), e);
        result = false;
    } finally {
        IOUtils.closeQuietly(fis);
        IOUtils.closeQuietly(toClient);
    }
    return result;
}

From source file:ee.ria.xroad.common.request.DummyCentralServiceHandler.java

private static void sendErrorResponse(HttpServletResponse response, String faultCode, String faultString,
        String faultActor, String faultDetail) throws IOException {
    String soapMessageXml = SoapFault.createFaultXml(faultCode, faultString, faultActor, faultDetail);

    String encoding = StandardCharsets.UTF_8.name();
    byte[] messageBytes = soapMessageXml.getBytes(encoding);

    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType(MimeTypes.TEXT_XML);
    response.setContentLength(messageBytes.length);
    response.setHeader("SOAPAction", "");
    response.setCharacterEncoding(encoding);
    response.getOutputStream().write(messageBytes);
}

From source file:ch.ralscha.extdirectspring.util.ExtDirectSpringUtil.java

/**
 * Checks etag and sends back HTTP status 304 if not modified. If modified sets
 * content type and content length, adds cache headers (
 * {@link #addCacheHeaders(HttpServletResponse, String, Integer)}), writes the data
 * into the {@link HttpServletResponse#getOutputStream()} and flushes it.
 *
 * @param request the HTTP servlet request
 * @param response the HTTP servlet response
 * @param data the response data//from w ww . j  av a  2 s.  c o  m
 * @param contentType the content type of the data (i.e.
 * "application/javascript;charset=UTF-8")
 * @throws IOException
 */
public static void handleCacheableResponse(HttpServletRequest request, HttpServletResponse response,
        byte[] data, String contentType) throws IOException {
    String ifNoneMatch = request.getHeader("If-None-Match");
    String etag = "\"0" + DigestUtils.md5DigestAsHex(data) + "\"";

    if (etag.equals(ifNoneMatch)) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    response.setContentType(contentType);
    response.setContentLength(data.length);

    addCacheHeaders(response, etag, 6);

    @SuppressWarnings("resource")
    ServletOutputStream out = response.getOutputStream();
    out.write(data);
    out.flush();
}

From source file:com.xqdev.jam.MLJAM.java

private static void sendBinaryResponse(HttpServletResponse res, byte[] bytes) throws IOException {
    res.setContentType("application/binary-encoded");
    OutputStream out = res.getOutputStream(); // care to handle errors later?
    out.write(bytes);/*from   w w w .j  a va2s  .  c  o m*/
    out.flush();
}