List of usage examples for javax.servlet.http HttpServletResponse setContentLength
public void setContentLength(int len);
From source file:com.struts2ext.json.JSONUtil.java
public static void writeJSONToResponse(SerializationParams serializationParams) throws IOException { StringBuilder stringBuilder = new StringBuilder(); if (StringUtils.isNotBlank(serializationParams.getSerializedJSON())) stringBuilder.append(serializationParams.getSerializedJSON()); if (StringUtils.isNotBlank(serializationParams.getWrapPrefix())) stringBuilder.insert(0, serializationParams.getWrapPrefix()); else if (serializationParams.isWrapWithComments()) { stringBuilder.insert(0, "/* "); stringBuilder.append(" */"); } else if (serializationParams.isPrefix()) stringBuilder.insert(0, "{}&& "); if (StringUtils.isNotBlank(serializationParams.getWrapSuffix())) stringBuilder.append(serializationParams.getWrapSuffix()); String json = stringBuilder.toString(); if (LOG.isDebugEnabled()) { LOG.debug("[JSON]" + json); }/* w w w . ja v a 2 s .c o m*/ HttpServletResponse response = serializationParams.getResponse(); // status or error code if (serializationParams.getStatusCode() > 0) response.setStatus(serializationParams.getStatusCode()); else if (serializationParams.getErrorCode() > 0) response.sendError(serializationParams.getErrorCode()); // content type if (serializationParams.isSmd()) response.setContentType("application/json-rpc;charset=" + serializationParams.getEncoding()); else response.setContentType( serializationParams.getContentType() + ";charset=" + serializationParams.getEncoding()); if (serializationParams.isNoCache()) { response.setHeader("Cache-Control", "no-cache"); response.setHeader("Expires", "0"); response.setHeader("Pragma", "No-cache"); } if (serializationParams.isGzip()) { response.addHeader("Content-Encoding", "gzip"); GZIPOutputStream out = null; InputStream in = null; try { out = new GZIPOutputStream(response.getOutputStream()); in = new ByteArrayInputStream(json.getBytes(serializationParams.getEncoding())); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } finally { if (in != null) in.close(); if (out != null) { out.finish(); out.close(); } } } else { response.setContentLength(json.getBytes(serializationParams.getEncoding()).length); PrintWriter out = response.getWriter(); out.print(json); } }
From source file:it.jugpadova.controllers.BinController.java
/** * Produce a certificate for a participant of an event. */// w ww . ja va 2s. com @RequestMapping public ModelAndView participantCertificate(HttpServletRequest req, HttpServletResponse res) { try { Long id = new Long(req.getParameter("id")); Participant participant = participantBo.retrieveParticipant(id); Event event = participant.getEvent(); eventBo.checkUserAuthorization(event); InputStream jugCertificateTemplate = null; String jugName = null; if (participant.getEvent().getOwner() != null) { JUG jug = participant.getEvent().getOwner().getJug(); jugName = jug.getName(); jugCertificateTemplate = jugBo.retrieveJugCertificateTemplate(jug.getId()); } else { jugName = ""; } byte[] jugCertificate = participantBo.buildCertificate(jugCertificateTemplate, participant.getFirstName() + " " + participant.getLastName(), participant.getEvent().getTitle(), event.getStartDate(), jugName); res.setContentType("application/pdf"); res.setContentLength(jugCertificate.length); res.setHeader("Content-Disposition", "attachment; filename=" + StringUtils.deleteWhitespace(participant.getLastName() + participant.getFirstName()) + "Certificate.pdf"); OutputStream out = new BufferedOutputStream(res.getOutputStream()); out.write(jugCertificate); out.flush(); out.close(); } catch (Exception ex) { logger.error("Error producing the certificate", ex); } return null; }
From source file:sys.core.manager.RecursosManager.java
public void viewArchivo(String archivo) { FacesContext context = FacesContext.getCurrentInstance(); HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse(); response.setContentType("application/force-download"); response.addHeader("Content-Disposition", "attachment; filename=\"" + archivo + "\""); ApplicationMBean applicationMBean = (ApplicationMBean) WebServletContextListener.getApplicationContext() .getBean("applicationMBean"); byte[] buf = new byte[1024]; try {/*from w ww . j a va 2 s . co m*/ File file = new File(applicationMBean.getRutaArchivos() + archivo); long length = file.length(); BufferedInputStream in = new BufferedInputStream(new FileInputStream(file)); ServletOutputStream out = response.getOutputStream(); response.setContentLength((int) length); while ((in != null) && ((length = in.read(buf)) != -1)) { out.write(buf, 0, (int) length); } in.close(); out.close(); } catch (Exception exc) { logger.error(exc); } }
From source file:net.sourceforge.fenixedu.presentationTier.Action.publico.candidacies.GenericCandidaciesDA.java
public ActionForward downloadFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException { final GenericApplication application = getDomainObject(request, "applicationExternalId"); final String confirmationCode = (String) getFromRequest(request, "confirmationCode"); final GenericApplicationFile file = getDomainObject(request, "fileExternalId"); if (application != null && file != null && file.getGenericApplication() == application && ((confirmationCode != null && application.getConfirmationCode() != null && application.getConfirmationCode().equals(confirmationCode)) || application.getGenericApplicationPeriod().isCurrentUserAllowedToMange())) { response.setContentType(file.getContentType()); response.addHeader("Content-Disposition", "attachment; filename=\"" + file.getFilename() + "\""); response.setContentLength(file.getSize().intValue()); final DataOutputStream dos = new DataOutputStream(response.getOutputStream()); dos.write(file.getContent());//from w w w. java2s .c o m dos.close(); } else { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().write(HttpStatus.getStatusText(HttpStatus.SC_BAD_REQUEST)); response.getWriter().close(); } return null; }
From source file:org.wrml.server.WrmlServlet.java
void writeVoid(final HttpServletResponse response) throws IOException { // TODO/*from ww w. j a va2 s . c o m*/ /* * Writing no entity body in the response may be perfectly fine...depending on the intent of the request (method, desired schema, etc), which is expressed in the * intendedResponseDimensions. */ // TODO response.setStatus(HttpServletResponse.SC_OK); response.setContentLength(0); response.flushBuffer(); }
From source file:eionet.gdem.web.struts.remoteapi.ConvertJson2XmlAction.java
/** * The purpose of this action is to execute <code>Json</code> static methods to convert json string or URL to XML format. The * method expects either url or json parameters. *//* ww w. ja va 2 s. c om*/ @Override public ActionForward execute(ActionMapping map, ActionForm actionForm, HttpServletRequest request, HttpServletResponse httpServletResponse) throws ServletException { String jsonParam = null; Map params = request.getParameterMap(); try { // parse request parameters if (params.containsKey(JSON_PARAM_NAME)) { jsonParam = ((String[]) params.get(JSON_PARAM_NAME))[0]; } if (Utils.isNullStr(jsonParam)) { throw new GDEMException("Missing request parameter: " + JSON_PARAM_NAME); } String xml = ""; if (jsonParam.startsWith("http:")) { // append other parameters to service Url if (params.size() > 1) { jsonParam = getJsonServiceUrl(jsonParam, params); } xml = Json.jsonRequest2xmlString(jsonParam); } else { xml = Json.jsonString2xml(jsonParam); } // set response properties httpServletResponse.setContentType("text/xml"); httpServletResponse.setCharacterEncoding("UTF-8"); httpServletResponse.setContentLength(xml.length()); // write data into response httpServletResponse.getOutputStream().write(xml.getBytes()); } catch (GDEMException ge) { ge.printStackTrace(); LOGGER.error("Unable to convert JSON to XML. " + ge.toString()); throw new ServletException(ge); } catch (Exception e) { e.printStackTrace(); LOGGER.error("Unable to convert JSON to XML. "); throw new ServletException(e); } finally { try { httpServletResponse.getOutputStream().close(); httpServletResponse.getOutputStream().flush(); } catch (IOException ioe) { ioe.printStackTrace(); throw new ServletException(ioe); } } // Do nothing, then response is already sent. return null; }
From source file:biz.webgate.dominoext.poi.component.kernel.simpleviewexport.CSVExportProcessor.java
public void process2HTTP(ExportModel expModel, UISimpleViewExport uis, HttpServletResponse hsr, DateTimeHelper dth) {//from w w w . j av a2 s. c o m try { ByteArrayOutputStream csvBAOS = new ByteArrayOutputStream(); OutputStreamWriter csvWriter = new OutputStreamWriter(csvBAOS); CSVPrinter csvPrinter = new CSVPrinter(csvWriter, CSVFormat.DEFAULT); // BUILDING HEADER if (uis.isIncludeHeader()) { for (ExportColumn expColumn : expModel.getColumns()) { csvPrinter.print(expColumn.getColumnName()); } csvPrinter.println(); } // Processing Values for (ExportDataRow expRow : expModel.getRows()) { for (ExportColumn expColumn : expModel.getColumns()) { csvPrinter.print(convertValue(expRow.getValue(expColumn.getPosition()), expColumn, dth)); } csvPrinter.println(); } csvPrinter.flush(); hsr.setContentType("text/csv"); hsr.setHeader("Cache-Control", "no-cache"); hsr.setDateHeader("Expires", -1); hsr.setContentLength(csvBAOS.size()); hsr.addHeader("Content-disposition", "inline; filename=\"" + uis.getDownloadFileName() + "\""); OutputStream os = hsr.getOutputStream(); csvBAOS.writeTo(os); os.close(); } catch (Exception e) { ErrorPageBuilder.getInstance().processError(hsr, "Error during SVE-Generation (CSV Export)", e); } }
From source file:mx.edu.um.mateo.rh.web.JefeRHController.java
private void generaReporte(String tipo, List<Jefe> jefes, HttpServletResponse response) throws JRException, IOException { log.debug("Generando reporte {}", tipo); byte[] archivo = null; switch (tipo) { case "PDF": archivo = generaPdf(jefes);//from w w w . j av a 2 s . com response.setContentType("application/pdf"); response.addHeader("Content-Disposition", "attachment; filename=clavesEmpleado.pdf"); break; case "CSV": archivo = generaCsv(jefes); response.setContentType("text/csv"); response.addHeader("Content-Disposition", "attachment; filename=clavesEmpleado.csv"); break; case "XLS": archivo = generaXls(jefes); response.setContentType("application/vnd.ms-excel"); response.addHeader("Content-Disposition", "attachment; filename=clavesEmpleado.xls"); } if (archivo != null) { response.setContentLength(archivo.length); try (BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) { bos.write(archivo); bos.flush(); } } }
From source file:eu.planets_project.tb.gui.backing.DownloadManager.java
/** * //w w w. j a v a2s . c o m * @return * @throws IOException */ public String downloadExportedExperiment(String expExportID, String downloadName) { FacesContext ctx = FacesContext.getCurrentInstance(); // Decode the file name (might contain spaces and on) and prepare file object. try { expExportID = URLDecoder.decode(expExportID, "UTF-8"); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); return null; } File file = expCache.getExportedFile(expExportID); HttpServletResponse response = (HttpServletResponse) ctx.getExternalContext().getResponse(); // Check if file exists and can be read: if (!file.exists() || !file.isFile() || !file.canRead()) { return "fileNotFound"; } // Get content type by filename. String contentType = new MimetypesFileTypeMap().getContentType(file); // If content type is unknown, then set the default value. // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp if (contentType == null) { contentType = "application/octet-stream"; } // Prepare streams. BufferedInputStream input = null; BufferedOutputStream output = null; try { // Open the file: input = new BufferedInputStream(new FileInputStream(file)); int contentLength = input.available(); // Initialise the servlet response: response.reset(); response.setContentType(contentType); response.setContentLength(contentLength); response.setHeader("Content-disposition", "attachment; filename=\"" + downloadName + ".xml\""); output = new BufferedOutputStream(response.getOutputStream()); // Write file out: for (int data; (data = input.read()) != -1;) { output.write(data); } // Flush the stream: output.flush(); // Tell Faces that we're finished: ctx.responseComplete(); } catch (IOException e) { // Something went wrong? e.printStackTrace(); } finally { // Gently close streams. close(output); close(input); } return "success"; }
From source file:mx.edu.um.mateo.rh.web.DiaFeriadoController.java
private void generaReporte(String tipo, List<DiaFeriado> diaFeriados, HttpServletResponse response) throws JRException, IOException { log.debug("Generando reporte {}", tipo); byte[] archivo = null; switch (tipo) { case "PDF": archivo = generaPdf(diaFeriados); response.setContentType("application/pdf"); response.addHeader("Content-Disposition", "attachment; filename=clavesEmpleado.pdf"); break;//from w w w . j a v a 2 s . c o m case "CSV": archivo = generaCsv(diaFeriados); response.setContentType("text/csv"); response.addHeader("Content-Disposition", "attachment; filename=clavesEmpleado.csv"); break; case "XLS": archivo = generaXls(diaFeriados); response.setContentType("application/vnd.ms-excel"); response.addHeader("Content-Disposition", "attachment; filename=clavesEmpleado.xls"); } if (archivo != null) { response.setContentLength(archivo.length); try (BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) { bos.write(archivo); bos.flush(); } } }