List of usage examples for javax.servlet.http HttpServletResponse getOutputStream
public ServletOutputStream getOutputStream() throws IOException;
From source file:com.feilong.servlet.http.ResponseDownloadUtil.java
/** * Down load data.//from w ww . j a v a 2 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 */ private static void downLoadData(String saveFileName, InputStream inputStream, Number contentLength, HttpServletRequest request, HttpServletResponse response) { Date beginDate = new Date(); String length = FileUtil.formatSize(contentLength.longValue()); LOGGER.info("begin download~~,saveFileName:[{}],contentLength:[{}]", saveFileName, length); try { OutputStream outputStream = response.getOutputStream(); IOWriteUtil.write(inputStream, outputStream); if (LOGGER.isInfoEnabled()) { String pattern = "end download,saveFileName:[{}],contentLength:[{}],time use:[{}]"; LOGGER.info(pattern, saveFileName, length, formatDuration(beginDate)); } } catch (IOException e) { /* * ?, ClientAbortException , ?,????, ,. * ??, ?? * ?,???...???, * ?, KILL?, ,?? ClientAbortException. */ //ClientAbortException: java.net.SocketException: Connection reset by peer: socket write error final String exceptionName = e.getClass().getName(); if (StringUtils.contains(exceptionName, "ClientAbortException") || StringUtils.contains(e.getMessage(), "ClientAbortException")) { String pattern = "[ClientAbortException],maybe user use Thunder soft or abort client soft download,exceptionName:[{}],exception message:[{}] ,request User-Agent:[{}]"; LOGGER.warn(pattern, exceptionName, e.getMessage(), RequestUtil.getHeaderUserAgent(request)); } else { LOGGER.error("[download exception],exception name: " + exceptionName, e); throw new UncheckedIOException(e); } } }
From source file:lc.kra.servlet.FileManagerServlet.java
private static void downloadFile(HttpServletResponse response, File file, String name, String contentType) throws IOException { response.setContentType(contentType); response.setHeader("Content-Disposition", "attachment; filename=\"" + name + "\""); copyStream(new FileInputStream(file), response.getOutputStream()); }
From source file:alfio.controller.AdminController.java
private static void downloadTicketsCSV(String eventName, String fileName, String[] header, Principal principal, HttpServletResponse response, EventManager eventManager, Function<Ticket, String[]> ticketMapper) throws IOException { Validate.isTrue(StringUtils.isNotBlank(eventName), "Event name is not valid"); List<Ticket> tickets = eventManager.findAllConfirmedTickets(eventName, principal.getName()); response.setContentType("text/csv;charset=UTF-8"); response.setHeader("Content-Disposition", "attachment; filename=" + eventName + "-" + fileName + ".csv"); try (ServletOutputStream out = response.getOutputStream()) { for (int marker : BOM_MARKERS) {//UGLY-MODE_ON: specify that the file is written in UTF-8 with BOM, thanks to alexr http://stackoverflow.com/a/4192897 out.write(marker);//w ww . j a v a2 s . co m } CSVWriter writer = new CSVWriter(new OutputStreamWriter(out)); writer.writeNext(header); tickets.stream().map(ticketMapper).forEach(writer::writeNext); writer.flush(); out.flush(); } }
From source file:com.zving.platform.SysInfo.java
public static void downloadDB(HttpServletRequest request, HttpServletResponse response) { try {//ww w. ja v a 2s . c om request.setCharacterEncoding(Constant.GlobalCharset); response.reset(); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment; filename=DB_" + DateUtil.getCurrentDate("yyyyMMddHHmmss") + ".dat"); OutputStream os = response.getOutputStream(); String path = Config.getContextRealPath() + "WEB-INF/data/backup/DB_" + DateUtil.getCurrentDate("yyyyMMddHHmmss") + ".dat"; new DBExport().exportDB(path); byte[] buffer = new byte[1024]; int read = -1; FileInputStream fis = null; try { fis = new FileInputStream(path); while ((read = fis.read(buffer)) != -1) if (read > 0) { byte[] chunk = (byte[]) null; if (read == 1024) { chunk = buffer; } else { chunk = new byte[read]; System.arraycopy(buffer, 0, chunk, 0, read); } os.write(chunk); os.flush(); } } finally { if (fis != null) { fis.close(); } } os.flush(); os.close(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.openmrs.module.omodexport.util.OmodExportUtil.java
/** * Utility module for exporting all modules. The exported modules will be in a zip file called * "modules.zip"//w w w. ja va 2 s .co m * * @param response * @throws IOException */ public static void exportAllModules(HttpServletResponse response) throws IOException { Collection<Module> modules = ModuleFactory.getStartedModules(); List<File> files = new ArrayList<File>(); for (Module module : modules) { 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:gov.nih.nci.caarray.web.helper.DownloadHelper.java
/** * Zips the selected files and writes the result to the servlet output stream. Also sets content type and * disposition appropriately.//w ww.ja v a2s . co m * * @param files the files to zip and send * @param baseFilename the filename w/o the suffix to use for the archive file. This filename will be set as the * Content-disposition header * @throws IOException if there is an error writing to the stream */ public static void downloadFiles(Collection<CaArrayFile> files, String baseFilename) throws IOException { final HttpServletResponse response = ServletActionContext.getResponse(); try { final PackagingInfo info = getPreferedPackageInfo(files, baseFilename); response.setContentType(info.getMethod().getMimeType()); response.addHeader("Content-disposition", "filename=\"" + info.getName() + "\""); final List<CaArrayFile> sortedFiles = new ArrayList<CaArrayFile>(files); Collections.sort(sortedFiles, CAARRAYFILE_NAME_COMPARATOR_INSTANCE); final OutputStream sos = response.getOutputStream(); final OutputStream closeShield = new CloseShieldOutputStream(sos); final ArchiveOutputStream arOut = info.getMethod().createArchiveOutputStream(closeShield); try { for (final CaArrayFile f : sortedFiles) { fileAccessUtils.addFileToArchive(f, arOut); } } finally { // note that the caller's stream is shielded from the close(), // but this is the only way to finish and flush the (gzip) stream. try { arOut.close(); } catch (final Exception e) { LOG.error(e); } } } catch (final Exception e) { LOG.error("Error streaming download of files " + files, e); response.sendError(HttpServletResponse.SC_NOT_FOUND); } }
From source file:org.bonitasoft.web.designer.controller.utils.HttpFile.java
/** * Write headers and content in the response *//*w ww . jav a2 s. c om*/ private static void writeFileInResponse(HttpServletResponse response, Path filePath, String mimeType, String contentDispositionType) throws IOException { response.setHeader("Content-Type", mimeType); response.setHeader("Content-Length", String.valueOf(filePath.toFile().length())); response.setHeader("Content-Disposition", new StringBuilder().append(contentDispositionType) .append("; filename=\"").append(filePath.getFileName()).append("\"").toString()); response.setCharacterEncoding(StandardCharsets.UTF_8.toString()); try (OutputStream out = response.getOutputStream()) { Files.copy(filePath, out); } }
From source file:com.invbf.sistemagestionmercadeo.reportes.ReportCreator.java
public static void generadorSolicitudBono(Solicitudentrega elemento) { ServletOutputStream servletOutputStream = null; try {// w w w. j a v a 2 s. c om SolicitudBonoJuego elementoReporte = new SolicitudBonoJuego(); if (elemento.getSolicitante().getUsuariodetalle().getIdcargo() != null) { elementoReporte.setCargo(elemento.getSolicitante().getUsuariodetalle().getIdcargo().getNombre()); } else { elementoReporte.setCargo(""); } elementoReporte.setCasino(elemento.getIdCasino().getNombre()); SimpleDateFormat formateador = new SimpleDateFormat("dd-MMMM-yy", new Locale("es_ES")); elementoReporte.setFecha(formateador.format(elemento.getFecha())); elementoReporte.setJustificacion(elemento.getJustificacion()); elementoReporte.setNombre(elemento.getSolicitante().getNombreUsuario()); elementoReporte.setProposito(elemento.getPropositoEntrega().getNombre()); elementoReporte.setTipobono(elemento.getTipoBono().getNombre()); List<SolicitudBonoJuegoCliente> clientes = new ArrayList<SolicitudBonoJuegoCliente>(); int item = 1; Float total = 0f; for (Solicitudentregacliente sec : elemento.getSolicitudentregaclienteList()) { clientes.add(new SolicitudBonoJuegoCliente((item) + "", sec.getCliente().getNombres() + " " + sec.getCliente().getApellidos(), sec.getValorTotal().toString(), sec.getAreaid().getNombre())); total += sec.getValorTotal(); item++; } elementoReporte.setClientes(clientes); elementoReporte.setTotal(total.toString()); ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext(); InputStream input = externalContext .getResourceAsStream("/resources/reportes/solicitudbonosjuego.jasper"); InputStream subreport = externalContext .getResourceAsStream("/resources/reportes/solicitudbonosjuego_cliente.jasper"); InputStream logo = externalContext.getResourceAsStream("/resources/reportes/LogoMRCNegro.jpeg"); InputStream logoibf = externalContext.getResourceAsStream("/resources/reportes/IBFLogo01jpeg.jpeg"); ImageIcon tlc = new ImageIcon(IOUtils.toByteArray(logo)); ImageIcon ibf = new ImageIcon(IOUtils.toByteArray(logoibf)); elementoReporte.setIbf(ibf.getImage()); elementoReporte.setLogo(tlc.getImage()); List<SolicitudBonoJuego> lista = new ArrayList<SolicitudBonoJuego>(); lista.add(elementoReporte); JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(lista); JasperReport jasperMasterReport = (JasperReport) JRLoader.loadObject(input); JasperReport jasperSubReport = (JasperReport) JRLoader.loadObject(subreport); elementoReporte.setSubreportclientes(jasperSubReport); Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("logo", lista.get(0).getLogo()); parameters.put("ibf", lista.get(0).getIbf()); parameters.put("clientes", lista.get(0).getClientes()); parameters.put("subreportclientes", jasperSubReport); JasperPrint jasperPrint = JasperFillManager.fillReport(jasperMasterReport, parameters, beanColDataSource); HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance() .getExternalContext().getResponse(); httpServletResponse.addHeader("Content-disposition", "attachment; filename=ActaSolicitudBonosJuego" + elemento.getId() + ".pdf"); servletOutputStream = httpServletResponse.getOutputStream(); JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream); } catch (IOException ex) { Logger.getLogger(ReportCreator.class.getName()).log(Level.SEVERE, null, ex); } catch (JRException ex) { Logger.getLogger(ReportCreator.class.getName()).log(Level.SEVERE, null, ex); } finally { try { servletOutputStream.close(); } catch (IOException ex) { Logger.getLogger(ReportCreator.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:net.mindengine.oculus.frontend.web.controllers.display.FileDisplayController.java
public static void showFile(HttpServletResponse response, String path, String fileName, String contentType) throws IOException { File file = new File(path); response.setBufferSize((int) file.length()); response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); response.setContentType(contentType); response.setContentLength((int) file.length()); byte[] bytes = new byte[(int) file.length()]; FileInputStream fis = new FileInputStream(file); fis.read(bytes);//from w w w. j a v a 2 s . c o m fis.close(); FileCopyUtils.copy(bytes, response.getOutputStream()); }
From source file:org.openmrs.module.omodexport.util.OmodExportUtil.java
/** * Utility method for exporting a set of selected modules. The select modules will be exported * in zip file called "modules.zip"/*from ww w . ja v a2 s . co m*/ * * @param moduleId -Dash-separated list of the module Ids * @param response * @throws IOException */ public static void exportSelectedModules(String moduleId, HttpServletResponse response) throws IOException { // Split the id string into an array of id's String[] moduleIds = moduleId.split("-"); List<File> files = new ArrayList<File>(); for (String mId : moduleIds) { Module m = ModuleFactory.getModuleById(mId); files.add(m.getFile()); } response.setContentType("application/zip"); response.setHeader("Content-Disposition", "attachment; filename=\"modules.ZIP\""); ZipOutputStream out = new ZipOutputStream(response.getOutputStream()); zipFiles(files, out); }