List of usage examples for javax.servlet.http HttpServletResponse reset
public void reset();
From source file:com.feilong.servlet.http.ResponseDownloadUtil.java
/** * download response header.// w w w . j a v a 2s. c om * * @param saveFileName * the save file name * @param contentLength * the content length * @param contentType * ?,;,? <code>null</code>,,?? {@link #resolverContentType(String, String)} * @param contentDisposition * ?,;,? <code>null</code>,,?? {@link #resolverContentDisposition(String, String)} * @param response * the response */ private static void setDownloadResponseHeader(String saveFileName, Number contentLength, String contentType, String contentDisposition, HttpServletResponse response) { //response //getResponsegetWriter()??,??,?response.resetresetBuffer. //getOutputStream() has already been called for this response //jsp??,response.getOutputStream()??:java.lang.IllegalStateException:getOutputStream() has already been called for this response,Exception response.reset(); //************************************************************************* response.addHeader(HttpHeaders.CONTENT_DISPOSITION, resolverContentDisposition(saveFileName, contentDisposition)); // ===================== Default MIME Type Mappings =================== --> //??,?,????.????,???, response.setContentType(resolverContentType(saveFileName, contentType)); if (isNotNullOrEmpty(contentLength)) { response.setContentLength(contentLength.intValue()); } //************************about buffer*********************************************************** //?:??,?,. //??,?: //JSP?? // //JSPout.flush()response.flushbuffer() //:?,?,???,???. //XXX ?? response.setBufferSize(10240); ^_^ //see org.apache.commons.io.IOUtils.copyLarge(InputStream, OutputStream) javadoc //This method buffers the input internally, so there is no need to use a BufferedInputStream }
From source file:com.aurel.track.exchange.latex.exporter.LaTeXExportBL.java
/** * Serializes the docx content into the response's output stream * @param response/*from w w w . jav a2s. c om*/ * @param wordMLPackage * @return */ public static String prepareReportResponse(HttpServletResponse response, TWorkItemBean workItem, ReportBeans reportBeans, TPersonBean user, Locale locale, String templateDir, String templateFile) { ReportBeansToLaTeXConverter rl = new ReportBeansToLaTeXConverter(); File pdf = rl.generatePdf(workItem, reportBeans.getItems(), true, locale, user, "", "", false, new File(templateFile), new File(templateDir)); String fileName = workItem.getSynopsis() + ".pdf"; String contentType = "application/pdf"; if (pdf.length() < 10) { pdf = new File(pdf.getParent() + "/errors.txt"); fileName = workItem.getSynopsis() + ".txt"; contentType = "text"; } OutputStream outputStream = null; try { response.reset(); response.setHeader("Content-Type", contentType); response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); DownloadUtil.prepareCacheControlHeader(ServletActionContext.getRequest(), response); outputStream = response.getOutputStream(); InputStream is = new FileInputStream(pdf); IOUtils.copy(is, outputStream); is.close(); } catch (FileNotFoundException e) { LOGGER.error(ExceptionUtils.getStackTrace(e)); } catch (IOException e) { LOGGER.error("Getting the output stream failed with " + e.getMessage()); LOGGER.error(ExceptionUtils.getStackTrace(e)); } catch (Exception e) { LOGGER.error(ExceptionUtils.getStackTrace(e)); } // Docx4J.save(wordMLPackage, outputStream, Docx4J.FLAG_NONE); // //wordMLPackage.save(outputStream); // /*SaveToZipFile saver = new SaveToZipFile(wordMLPackage); // saver.save(outputStream);*/ // } catch (Exception e) { // LOGGER.error("Exporting the docx failed with throwable " + e.getMessage()); // LOGGER.debug(ExceptionUtils.getStackTrace(e)); // } return null; }
From source file:org.duracloud.duradmin.util.SpaceUtil.java
public static void streamToResponse(InputStream is, HttpServletResponse response, String mimetype, String contentLength) throws ContentStoreException, IOException { OutputStream outStream = response.getOutputStream(); try {//from w w w.j av a 2 s. c om response.setContentType(mimetype); if (contentLength != null) { response.setContentLengthLong(Long.parseLong(contentLength)); } byte[] buf = new byte[1024]; int read = -1; while ((read = is.read(buf)) > 0) { outStream.write(buf, 0, read); } response.flushBuffer(); } catch (Exception ex) { if (ex.getCause() instanceof ContentStateException) { response.reset(); response.setStatus(HttpStatus.SC_CONFLICT); String message = "The requested content item is currently in long-term storage" + " with limited retrieval capability. Please contact " + "DuraCloud support (https://wiki.duraspace.org/x/6gPNAQ) " + "for assistance in retrieving this content item."; //It is necessary to pad the message in order to force Internet Explorer to //display the server sent text rather than display the browser default error message. //If the message is less than 512 bytes, the browser will ignore the message. //c.f. http://support.microsoft.com/kb/294807 message += StringUtils.repeat(" ", 512); outStream.write(message.getBytes()); } else { throw ex; } } finally { try { outStream.close(); } catch (Exception e) { log.warn("failed to close outputstream ( " + outStream + "): message=" + e.getMessage(), e); } } }
From source file:com.feilong.servlet.http.ResponseUtil.java
/** * download response header.//from w w w . ja va2s . c o m * * @param saveFileName * the save file name * @param contentLength * the content length * @param contentType * the content type * @param contentDisposition * the content disposition * @param response * the response */ private static void setDownloadResponseHeader(String saveFileName, Number contentLength, String contentType, String contentDisposition, HttpServletResponse response) { //********************************************************************************************** // response //getResponsegetWriter()?????response.resetresetBuffer //getOutputStream() has already been called for this response //jsp??,response.getOutputStream()??java.lang.IllegalStateException:getOutputStream() has already been called for this response,Exception response.reset(); // ===================== Default MIME Type Mappings =================== --> //See tomcat web.xml //When serving static resources, Tomcat will automatically generate a "Content-Type" header based on the resource's filename extension, based on these mappings. //Additional mappings can be added here (to apply to all web applications), or in your own application's web.xml deployment descriptor. --> if (Validator.isNullOrEmpty(contentType)) { contentType = MimeTypeUtil.getContentTypeByFileName(saveFileName); if (Validator.isNullOrEmpty(contentType)) { //contentType = "application/force-download";//,phpapplication/force-download,??HTTP ???? //application/x-download //.* ??? application/octet-stream contentType = MimeType.BIN.getMime(); //The HTTP specification recommends setting the Content-Type to application/octet-stream. //Unfortunately, this causes problems with Opera 6 on Windows (which will display the raw bytes for any file whose extension it doesn't recognize) and on Internet Explorer 5.1 on the Mac (which will display inline content that would be downloaded if sent with an unrecognized type). } } //?????????????? if (Validator.isNotNullOrEmpty(contentType)) { response.setContentType(contentType); } //?:??,?,.??? //???????? //response.setBufferSize(10240); //see org.apache.commons.io.IOUtils.copyLarge(InputStream, OutputStream) javadoc //This method buffers the input internally, so there is no need to use a BufferedInputStream //**************************************************************************************************** //Content-Disposition takes one of two values, `inline' and `attachment'. //'Inline' indicates that the entity should be immediately displayed to the user, //whereas `attachment' means that the user should take additional action to view the entity. //The `filename' parameter can be used to suggest a filename for storing the bodypart, if the user wishes to store it in an external file. if (Validator.isNullOrEmpty(contentDisposition)) { // ? contentDisposition = "attachment; filename=" + URIUtil.encode(saveFileName, CharsetType.UTF8); } //TODO ? httpcomponents httpcore org.apache.http.HttpHeaders response.addHeader(HttpHeaders.CONTENT_DISPOSITION, contentDisposition); response.setContentLength(contentLength.intValue()); }
From source file:com.hp.autonomy.frontend.find.core.view.AbstractViewController.java
@ExceptionHandler @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public ModelAndView handleGeneralException(final Exception e, final HttpServletRequest request, final HttpServletResponse response) { response.reset(); final UUID uuid = UUID.randomUUID(); log.error("Unhandled exception with uuid {}", uuid); log.error("Stack trace", e); final Locale locale = Locale.ENGLISH; return buildErrorModelAndView(request, messageSource.getMessage("error.internalServerErrorMain", null, locale), messageSource.getMessage("error.internalServerErrorSub", new Object[] { uuid }, locale)); }
From source file:com.hp.autonomy.frontend.find.hod.view.HodViewController.java
@ExceptionHandler public ModelAndView hodAuthenticationFailedException(final HodAuthenticationFailedException e, final HttpServletRequest request, final HttpServletResponse response) { response.reset(); response.setStatus(HttpServletResponse.SC_FORBIDDEN); log.error("HodAuthenticationFailedException thrown while viewing document", e); return controllerUtils.buildErrorModelAndView(new ErrorModelAndViewInfo.Builder().setRequest(request) .setMainMessageCode(HOD_ERROR_MESSAGE_CODE_MAIN) .setSubMessageCode(HOD_ERROR_MESSAGE_CODE_TOKEN_EXPIRED) .setStatusCode(HttpServletResponse.SC_FORBIDDEN).setAuthError(true).build()); }
From source file:com.sunchenbin.store.feilong.servlet.http.ResponseUtil.java
/** * download response header./*from w ww. j a v a2 s . com*/ * * @param saveFileName * the save file name * @param contentLength * the content length * @param contentType * the content type * @param contentDisposition * the content disposition * @param response * the response */ private static void setDownloadResponseHeader(String saveFileName, Number contentLength, String contentType, String contentDisposition, HttpServletResponse response) { //********************************************************************************************** // response //getResponsegetWriter()?????response.resetresetBuffer //getOutputStream() has already been called for this response //jsp??,response.getOutputStream()??java.lang.IllegalStateException:getOutputStream() has already been called for this response,Exception response.reset(); // ===================== Default MIME Type Mappings =================== --> //See tomcat web.xml //When serving static resources, Tomcat will automatically generate a "Content-Type" header based on the resource's filename extension, based on these mappings. //Additional mappings can be added here (to apply to all web applications), or in your own application's web.xml deployment descriptor. --> if (Validator.isNullOrEmpty(contentType)) { contentType = MimeTypeUtil.getContentTypeByFileName(saveFileName); if (Validator.isNullOrEmpty(contentType)) { //contentType = "application/force-download";//,phpapplication/force-download,??HTTP ???? //application/x-download //.* ??? application/octet-stream contentType = MimeType.BIN.getMime(); //The HTTP specification recommends setting the Content-Type to application/octet-stream. //Unfortunately, this causes problems with Opera 6 on Windows (which will display the raw bytes for any file whose extension it doesn't recognize) and on Internet Explorer 5.1 on the Mac (which will display inline content that would be downloaded if sent with an unrecognized type). } } //?????????????? if (Validator.isNotNullOrEmpty(contentType)) { response.setContentType(contentType); } //?:??,?,.??? //???????? //response.setBufferSize(10240); //see org.apache.commons.io.IOUtils.copyLarge(InputStream, OutputStream) javadoc //This method buffers the input internally, so there is no need to use a BufferedInputStream //**************************************************************************************************** //Content-Disposition takes one of two values, `inline' and `attachment'. //'Inline' indicates that the entity should be immediately displayed to the user, //whereas `attachment' means that the user should take additional action to view the entity. //The `filename' parameter can be used to suggest a filename for storing the bodypart, if the user wishes to store it in an external file. if (Validator.isNullOrEmpty(contentDisposition)) { // ? contentDisposition = "attachment; filename=" + URIUtil.encode(saveFileName, CharsetType.UTF8); } //TODO ? httpcomponents httpcore org.apache.http.HttpHeaders response.addHeader(HttpHeaders.CONTENT_DISPOSITION, contentDisposition); response.setContentLength(contentLength.intValue()); }
From source file:com.zlfun.framework.misc.UploadUtils.java
public static boolean download(HttpServletRequest request, HttpServletResponse response, String uuid) { InputStream bis;/*from w ww . ja va2s . co m*/ boolean ret = false; try { byte[] voiceData = FsUtils.readFromDisk(uuid); if (voiceData != null) { long p = 0L; long toLength = 0L; long contentLength = 0L; int rangeSwitch = 0; // 0,1,?bytes=27000-2,???bytes=27000-39000 long fileLength; String rangBytes = ""; fileLength = voiceData.length; // get file content bis = new ByteArrayInputStream(voiceData); // tell the client to allow accept-ranges response.reset(); response.setHeader("Accept-Ranges", "bytes"); // client requests a file block download start byte String range = request.getHeader("Range"); if (range != null && range.trim().length() > 0 && !"null".equals(range)) { response.setStatus(javax.servlet.http.HttpServletResponse.SC_PARTIAL_CONTENT); rangBytes = range.replaceAll("bytes=", ""); if (rangBytes.endsWith("-")) { // bytes=270000- rangeSwitch = 1; p = Long.parseLong(rangBytes.substring(0, rangBytes.indexOf("-"))); contentLength = fileLength - p; // 270000?bytes270000 } else { // bytes=270000-320000 rangeSwitch = 2; String temp1 = rangBytes.substring(0, rangBytes.indexOf("-")); String temp2 = rangBytes.substring(rangBytes.indexOf("-") + 1, rangBytes.length()); p = Long.parseLong(temp1); toLength = Long.parseLong(temp2); contentLength = toLength - p + 1; // // 270000-320000 // } } else { contentLength = fileLength; } // Content-Length????? // Content-Length: [?] - [?] response.setHeader("Content-Length", new Long(contentLength).toString()); // // ??: // Content-Range: bytes [?]-[? - 1]/[?] if (rangeSwitch == 1) { String contentRange = new StringBuffer("bytes ").append(new Long(p).toString()).append("-") .append(new Long(fileLength - 1).toString()).append("/") .append(new Long(fileLength).toString()).toString(); response.setHeader("Content-Range", contentRange); bis.skip(p); } else if (rangeSwitch == 2) { String contentRange = range.replace("=", " ") + "/" + new Long(fileLength).toString(); response.setHeader("Content-Range", contentRange); bis.skip(p); } else { String contentRange = new StringBuffer("bytes ").append("0-").append(fileLength - 1).append("/") .append(fileLength).toString(); response.setHeader("Content-Range", contentRange); } response.setContentType("application/octet-stream"); response.addHeader("Content-Disposition", getContentDisposition(request, uuid)); OutputStream out = response.getOutputStream(); int n = 0; long readLength = 0; int bsize = 1024; byte[] bytes = new byte[bsize]; if (rangeSwitch == 2) { // bytes=27000-39000 27000? while (readLength <= contentLength - bsize) { n = bis.read(bytes); readLength += n; out.write(bytes, 0, n); } if (readLength <= contentLength) { n = bis.read(bytes, 0, (int) (contentLength - readLength)); out.write(bytes, 0, n); } } else { while ((n = bis.read(bytes)) != -1) { out.write(bytes, 0, n); } } out.flush(); out.close(); bis.close(); return true; } else { return false; } } catch (IOException ex) { // ClientAbortException Logger.getLogger(UploadUtils.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (Exception ex) { Logger.getLogger(UploadUtils.class.getName()).log(Level.SEVERE, null, ex); return false; } }
From source file:com.hp.autonomy.frontend.find.hod.view.HodViewController.java
@ExceptionHandler public ModelAndView handleHodErrorException(final HodErrorException e, final HttpServletRequest request, final HttpServletResponse response) { response.reset(); log.error("HodErrorException thrown while viewing document", e); final String errorKey = HOD_ERROR_MESSAGE_CODE_PREFIX + e.getErrorCode(); String hodErrorMessage;/* w ww . j a v a2s. c o m*/ try { hodErrorMessage = controllerUtils.getMessage(errorKey, null); } catch (final NoSuchMessageException ignored) { // we don't have a key in the bundle for this error code hodErrorMessage = controllerUtils.getMessage(HOD_ERROR_MESSAGE_CODE_UNKNOWN, null); } final int errorCode = e.isServerError() ? HttpServletResponse.SC_INTERNAL_SERVER_ERROR : HttpServletResponse.SC_BAD_REQUEST; final String subMessageCode; final Object[] subMessageArgs; if (hodErrorMessage != null) { subMessageCode = HOD_ERROR_MESSAGE_CODE_SUB; subMessageArgs = new String[] { hodErrorMessage }; } else { subMessageCode = HOD_ERROR_MESSAGE_CODE_SUB_NULL; subMessageArgs = null; } response.setStatus(errorCode); return controllerUtils.buildErrorModelAndView(new ErrorModelAndViewInfo.Builder().setRequest(request) .setMainMessageCode(HOD_ERROR_MESSAGE_CODE_MAIN).setSubMessageCode(subMessageCode) .setSubMessageArguments(subMessageArgs).setStatusCode(errorCode).setContactSupport(true) .setException(e).build()); }
From source file:com.aurel.track.exchange.docx.exporter.DocxExportBL.java
/** * Serializes the docx content into the response's output stream * @param response// w w w . j a v a2 s. c o m * @param wordMLPackage * @return */ static String prepareReportResponse(HttpServletResponse response, String baseFileName, WordprocessingMLPackage wordMLPackage) { if (baseFileName == null) { baseFileName = "TrackReport"; } else { baseFileName = StringEscapeUtils.unescapeHtml4(baseFileName); StringBuffer sb = new StringBuffer(baseFileName.replaceAll("[^a-zA-Z0-9_]", "_")); Pattern regex = Pattern.compile("(_[a-z])"); Matcher regexMatcher = regex.matcher(sb); StringBuffer sb2 = new StringBuffer(); try { while (regexMatcher.find()) { regexMatcher.appendReplacement(sb2, regexMatcher.group(1).toUpperCase()); } regexMatcher.appendTail(sb2); } catch (Exception e) { LOGGER.error(e.getMessage()); } baseFileName = sb2.toString().replaceAll("_", ""); } response.reset(); response.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"); response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".docx\""); DownloadUtil.prepareCacheControlHeader(ServletActionContext.getRequest(), response); OutputStream outputStream = null; try { outputStream = response.getOutputStream(); } catch (IOException e) { LOGGER.error("Getting the output stream failed with " + e.getMessage()); LOGGER.error(ExceptionUtils.getStackTrace(e)); } try { Docx4J.save(wordMLPackage, outputStream, Docx4J.FLAG_NONE); /*SaveToZipFile saver = new SaveToZipFile(wordMLPackage); saver.save(outputStream);*/ } catch (Exception e) { LOGGER.error("Exporting the docx failed with throwable " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } return null; }