List of usage examples for javax.servlet.http HttpServletResponse getCharacterEncoding
public String getCharacterEncoding();
From source file:org.codelabor.system.file.web.spring.controller.FileController.java
@RequestMapping("/view") public void view(@RequestParam("fileId") String fileId, HttpServletResponse response) throws Exception { StringBuilder stringBuilder = null; FileDTO fileDTO;//w w w . j a v a 2s . com fileDTO = fileManager.selectFileByFileId(fileId); logger.debug("fileDTO: {}", fileDTO); String repositoryPath = fileDTO.getRepositoryPath(); String uniqueFilename = fileDTO.getUniqueFilename(); String realFilename = fileDTO.getRealFilename(); InputStream inputStream = null; if (StringUtils.isNotEmpty(repositoryPath)) { // FILE_SYSTEM stringBuilder = new StringBuilder(); stringBuilder.append(repositoryPath); if (!repositoryPath.endsWith(File.separator)) { stringBuilder.append(File.separator); } stringBuilder.append(uniqueFilename); File file = new File(stringBuilder.toString()); inputStream = new FileInputStream(file); } else { // DATABASE byte[] bytes = new byte[] {}; if (fileDTO.getFileSize() > 0) { bytes = fileDTO.getBytes(); } inputStream = new ByteArrayInputStream(bytes); } response.setContentType(fileDTO.getContentType()); // set response contenttype, header String encodedRealFilename = URLEncoder.encode(realFilename, "UTF-8"); logger.debug("realFilename: {}", realFilename); logger.debug("encodedRealFilename: {}", encodedRealFilename); logger.debug("character encoding: {}", response.getCharacterEncoding()); logger.debug("content type: {}", response.getContentType()); logger.debug("bufferSize: {}", response.getBufferSize()); logger.debug("locale: {}", response.getLocale()); BufferedInputStream bufferdInputStream = new BufferedInputStream(inputStream); ServletOutputStream servletOutputStream = response.getOutputStream(); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(servletOutputStream); int bytesRead; byte buffer[] = new byte[2048]; while ((bytesRead = bufferdInputStream.read(buffer)) != -1) { bufferedOutputStream.write(buffer, 0, bytesRead); } // flush stream bufferedOutputStream.flush(); // close stream inputStream.close(); bufferdInputStream.close(); servletOutputStream.close(); bufferedOutputStream.close(); }
From source file:org.exist.http.urlrewrite.XQueryURLRewrite.java
private void flushError(HttpServletResponse response, HttpServletResponse wrappedResponse) throws IOException { if (!response.isCommitted()) { final byte[] data = ((CachingResponseWrapper) wrappedResponse).getData(); if (data != null) { response.setContentType(wrappedResponse.getContentType()); response.setCharacterEncoding(wrappedResponse.getCharacterEncoding()); response.getOutputStream().write(data); response.flushBuffer();//from www . j a va 2 s . com } } }
From source file:com.bstek.dorado.web.resolver.AbstractWebFileResolver.java
protected void outputResourcesWrapper(ResourcesWrapper resourcesWrapper, HttpServletRequest request, HttpServletResponse response) throws Exception { if (resourcesWrapper.getHttpStatus() != 0) { response.setStatus(resourcesWrapper.getHttpStatus()); } else {//from w w w .jav a 2s. com // ?Client??-1 long cachedLastModified = request.getDateHeader(HttpConstants.IF_MODIFIED_SINCE); // ?Server?? long lastModified = resourcesWrapper.getLastModified(); // ?Client if (lastModified != 0 && cachedLastModified != 0 && Math.abs(lastModified - cachedLastModified) < ONE_SECOND) { // ?Server???Client response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } else { String contentType = getContentType(resourcesWrapper); response.setContentType(contentType); // Client?? SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH); dateFormat.setTimeZone(GMT_TIME_ZONE); response.addHeader(HttpConstants.LAST_MODIFIED, dateFormat.format(new Date(lastModified))); Resource[] resources = resourcesWrapper.getResources(); OutputStream out = getOutputStream(request, response, resourcesWrapper); try { for (int i = 0; i < resources.length; i++) { if (i > 0 && contentType.contains("text")) { out.write("\n".getBytes(response.getCharacterEncoding())); } outputFile(out, resources[i]); } } finally { try { out.close(); } catch (IOException e) { // do nothing } } } } }
From source file:com.bst.tags.TableTag.java
/** * Will write the export. The default behavior is to write directly to the response. If the ResponseOverrideFilter * is configured for this request, will instead write the exported content to a map in the Request object. * @param exportView export view/*from w ww . j av a2s . c om*/ * @throws JspException for problem in clearing the response or for invalid export views * @throws IOException exception thrown when writing content to the response */ protected void writeExport(ExportView exportView) throws IOException, JspException { String filename = properties.getExportFileName(this.currentMediaType); HttpServletResponse response = (HttpServletResponse) this.pageContext.getResponse(); HttpServletRequest request = (HttpServletRequest) this.pageContext.getRequest(); Map bean = (Map) request.getAttribute(FILTER_CONTENT_OVERRIDE_BODY); boolean usingFilter = bean != null; String mimeType = exportView.getMimeType(); // original encoding, be sure to add it back after reset() String characterEncoding = response.getCharacterEncoding(); if (usingFilter) { if (!bean.containsKey(TableTagParameters.BEAN_BUFFER)) { // We are running under the export filter, call it log.debug("Exportfilter enabled in unbuffered mode, setting headers"); response.addHeader(TableTagParameters.PARAMETER_EXPORTING, TagConstants.EMPTY_STRING); } else { // We are running under the export filter in buffered mode bean.put(TableTagParameters.BEAN_CONTENTTYPE, mimeType); bean.put(TableTagParameters.BEAN_FILENAME, filename); if (exportView instanceof TextExportView) { StringWriter writer = new StringWriter(); ((TextExportView) exportView).doExport(writer); bean.put(TableTagParameters.BEAN_BODY, writer.toString()); } else if (exportView instanceof BinaryExportView) { ByteArrayOutputStream stream = new ByteArrayOutputStream(); ((BinaryExportView) exportView).doExport(stream); bean.put(TableTagParameters.BEAN_BODY, stream.toByteArray()); } else { throw new JspTagException("Export view " + exportView.getClass().getName() + " must implement TextExportView or BinaryExportView"); } return; } } else { log.debug("Exportfilter NOT enabled"); // response can't be already committed at this time if (response.isCommitted()) { throw new ExportException(getClass()); } try { response.reset(); pageContext.getOut().clearBuffer(); } catch (Exception e) { throw new ExportException(getClass()); } } if (!usingFilter && characterEncoding != null && mimeType.indexOf("charset") == -1) //$NON-NLS-1$ { mimeType += "; charset=" + characterEncoding; //$NON-NLS-1$ } response.setContentType(mimeType); if (StringUtils.isNotEmpty(filename)) { response.setHeader("Content-Disposition", //$NON-NLS-1$ "attachment; filename=\"" + filename + "\""); //$NON-NLS-1$ //$NON-NLS-2$ } if (exportView instanceof TextExportView) { Writer writer; if (usingFilter) { writer = response.getWriter(); } else { writer = pageContext.getOut(); } ((TextExportView) exportView).doExport(writer); } else if (exportView instanceof BinaryExportView) { // dealing with binary content // note that this is not assured to work on any application server if the filter is not enabled. According // to the jsp specs response.getOutputStream() should no be called in jsps. ((BinaryExportView) exportView).doExport(response.getOutputStream()); } else { throw new JspTagException("Export view " + exportView.getClass().getName() + " must implement TextExportView or BinaryExportView"); } log.debug("Export completed"); }
From source file:org.codelabor.system.file.web.spring.controller.FileController.java
@RequestMapping("/download") public void download(@RequestHeader("User-Agent") String userAgent, @RequestParam("fileId") String fileId, HttpServletResponse response) throws Exception { FileDTO fileDTO = fileManager.selectFileByFileId(fileId); logger.debug("fileDTO: {}", fileDTO); String repositoryPath = fileDTO.getRepositoryPath(); String uniqueFilename = fileDTO.getUniqueFilename(); String realFilename = fileDTO.getRealFilename(); InputStream inputStream = null; StringBuilder sb = new StringBuilder(); if (StringUtils.isNotEmpty(repositoryPath)) { // FILE_SYSTEM sb.append(repositoryPath);/*from w w w . j av a 2 s .c om*/ if (!repositoryPath.endsWith(File.separator)) { sb.append(File.separator); } sb.append(uniqueFilename); File file = new File(sb.toString()); inputStream = new FileInputStream(file); } else { // DATABASE byte[] bytes = new byte[] {}; if (fileDTO.getFileSize() > 0) { bytes = fileDTO.getBytes(); } inputStream = new ByteArrayInputStream(bytes); } // set response contenttype, header String encodedRealFilename = URLEncoder.encode(realFilename, "UTF-8"); logger.debug("realFilename: {}", realFilename); logger.debug("encodedRealFilename: {}", encodedRealFilename); response.setContentType(org.codelabor.system.file.FileConstants.CONTENT_TYPE); sb.setLength(0); if (userAgent.indexOf("MSIE5.5") > -1) { sb.append("filename="); } else { sb.append("attachment; filename="); } sb.append(encodedRealFilename); response.setHeader(HttpResponseHeaderConstants.CONTENT_DISPOSITION, sb.toString()); logger.debug("header: {}", sb.toString()); logger.debug("character encoding: {}", response.getCharacterEncoding()); logger.debug("content type: {}", response.getContentType()); logger.debug("bufferSize: {}", response.getBufferSize()); logger.debug("locale: {}", response.getLocale()); BufferedInputStream bufferdInputStream = new BufferedInputStream(inputStream); ServletOutputStream servletOutputStream = response.getOutputStream(); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(servletOutputStream); int bytesRead; byte buffer[] = new byte[2048]; while ((bytesRead = bufferdInputStream.read(buffer)) != -1) { bufferedOutputStream.write(buffer, 0, bytesRead); } // flush stream bufferedOutputStream.flush(); // close stream inputStream.close(); bufferdInputStream.close(); servletOutputStream.close(); bufferedOutputStream.close(); }
From source file:cn.bc.web.util.DebugUtils.java
public static StringBuffer getDebugInfo(HttpServletRequest request, HttpServletResponse response) { @SuppressWarnings("rawtypes") Enumeration e;/* w w w . j a v a 2 s . c o m*/ String name; StringBuffer html = new StringBuffer(); //session HttpSession session = request.getSession(); html.append("<div><b>session:</b></div><ul>"); html.append(createLI("Id", session.getId())); html.append(createLI("CreationTime", new Date(session.getCreationTime()).toString())); html.append(createLI("LastAccessedTime", new Date(session.getLastAccessedTime()).toString())); //session:attributes e = session.getAttributeNames(); html.append("<li>attributes:<ul>\r\n"); while (e.hasMoreElements()) { name = (String) e.nextElement(); html.append(createLI(name, String.valueOf(session.getAttribute(name)))); } html.append("</ul></li>\r\n"); html.append("</ul>\r\n"); //request html.append("<div><b>request:</b></div><ul>"); html.append(createLI("URL", request.getRequestURL().toString())); html.append(createLI("QueryString", request.getQueryString())); html.append(createLI("Method", request.getMethod())); html.append(createLI("CharacterEncoding", request.getCharacterEncoding())); html.append(createLI("ContentType", request.getContentType())); html.append(createLI("Protocol", request.getProtocol())); html.append(createLI("RemoteAddr", request.getRemoteAddr())); html.append(createLI("RemoteHost", request.getRemoteHost())); html.append(createLI("RemotePort", request.getRemotePort() + "")); html.append(createLI("RemoteUser", request.getRemoteUser())); html.append(createLI("ServerName", request.getServerName())); html.append(createLI("ServletPath", request.getServletPath())); html.append(createLI("ServerPort", request.getServerPort() + "")); html.append(createLI("Scheme", request.getScheme())); html.append(createLI("LocalAddr", request.getLocalAddr())); html.append(createLI("LocalName", request.getLocalName())); html.append(createLI("LocalPort", request.getLocalPort() + "")); html.append(createLI("Locale", request.getLocale().toString())); //request:headers e = request.getHeaderNames(); html.append("<li>Headers:<ul>\r\n"); while (e.hasMoreElements()) { name = (String) e.nextElement(); html.append(createLI(name, request.getHeader(name))); } html.append("</ul></li>\r\n"); //request:parameters e = request.getParameterNames(); html.append("<li>Parameters:<ul>\r\n"); while (e.hasMoreElements()) { name = (String) e.nextElement(); html.append(createLI(name, request.getParameter(name))); } html.append("</ul></li>\r\n"); html.append("</ul>\r\n"); //response html.append("<div><b>response:</b></div><ul>"); html.append(createLI("CharacterEncoding", response.getCharacterEncoding())); html.append(createLI("ContentType", response.getContentType())); html.append(createLI("BufferSize", response.getBufferSize() + "")); html.append(createLI("Locale", response.getLocale().toString())); html.append("<ul>\r\n"); return html; }
From source file:org.jasig.portal.portlet.rendering.PortletRendererImpl.java
@Override public void doReset(IPortletWindowId portletWindowId, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { final IPortletWindow portletWindow = this.portletWindowRegistry.getPortletWindow(httpServletRequest, portletWindowId);// www.j a v a2 s . c om if (portletWindow != null) { portletWindow.setPortletMode(PortletMode.VIEW); portletWindow.setRenderParameters(new ParameterMap()); portletWindow.setExpirationCache(null); httpServletRequest = this.setupPortletRequest(httpServletRequest); httpServletResponse = new PortletHttpServletResponseWrapper(httpServletResponse, portletWindow); httpServletRequest.setAttribute(AdministrativeRequestListenerController.DEFAULT_LISTENER_KEY_ATTRIBUTE, "sessionActionListener"); httpServletRequest.setAttribute(PortletSessionAdministrativeRequestListener.ACTION, PortletSessionAdministrativeRequestListener.SessionAction.CLEAR); httpServletRequest.setAttribute(PortletSessionAdministrativeRequestListener.SCOPE, PortletSession.PORTLET_SCOPE); //TODO modify PortletContainer.doAdmin to create a specific "admin" req/res object and context so we don't have to fake it with a render req //These are required for a render request to be created and admin requests use a render request under the hood final String characterEncoding = httpServletResponse.getCharacterEncoding(); httpServletRequest.setAttribute(ATTRIBUTE__PORTLET_OUTPUT_HANDLER, new RenderPortletOutputHandler(characterEncoding)); httpServletRequest.setAttribute(ATTRIBUTE__PORTLET_CACHE_CONTROL, new CacheControlImpl()); try { this.portletContainer.doAdmin(portletWindow.getPlutoPortletWindow(), httpServletRequest, httpServletResponse); } catch (PortletException pe) { throw new PortletDispatchException( "The portlet window '" + portletWindow + "' threw an exception while executing admin command to clear session.", portletWindow, pe); } catch (PortletContainerException pce) { throw new PortletDispatchException( "The portlet container threw an exception while executing admin command to clear session on portlet window '" + portletWindow + "'.", portletWindow, pce); } catch (IOException ioe) { throw new PortletDispatchException( "The portlet window '" + portletWindow + "' threw an exception while executing admin command to clear session.", portletWindow, ioe); } } else { logger.debug( "ignoring doReset as portletWindowRegistry#getPortletWindow returned a null result for portletWindowId " + portletWindowId); } }
From source file:org.codelabor.system.file.web.struts.action.FileUploadAction.java
public ActionForward view(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { WebApplicationContext ctx = WebApplicationContextUtils .getRequiredWebApplicationContext(getServlet().getServletContext()); FileManager fileManager = (FileManager) ctx.getBean("fileManager"); Map<String, Object> paramMap = RequestUtils.getParameterMap(request); logger.debug("paramMap: {}", paramMap.toString()); String fileId = (String) paramMap.get("fileId"); StringBuilder sb = new StringBuilder(); FileDTO fileDTO;// ww w .j a v a 2 s .c om fileDTO = fileManager.selectFileByFileId(fileId); logger.debug("fileDTO: {}", fileDTO); String repositoryPath = fileDTO.getRepositoryPath(); String uniqueFilename = fileDTO.getUniqueFilename(); String realFilename = fileDTO.getRealFilename(); InputStream inputStream = null; if (StringUtils.isNotEmpty(repositoryPath)) { // FILE_SYSTEM sb.setLength(0); sb.append(repositoryPath); if (!repositoryPath.endsWith(File.separator)) { sb.append(File.separator); } sb.append(uniqueFilename); File file = new File(sb.toString()); inputStream = new FileInputStream(file); } else { // DATABASE byte[] bytes = new byte[] {}; if (fileDTO.getFileSize() > 0) { bytes = fileDTO.getBytes(); } inputStream = new ByteArrayInputStream(bytes); } response.setContentType(fileDTO.getContentType()); // set response contenttype, header String encodedRealFilename = URLEncoder.encode(realFilename, "UTF-8"); logger.debug("realFilename: {}", realFilename); logger.debug("encodedRealFilename: {}", encodedRealFilename); logger.debug("character encoding: {}", response.getCharacterEncoding()); logger.debug("content type: {}", response.getContentType()); logger.debug("bufferSize: {}", response.getBufferSize()); logger.debug("locale: {}", response.getLocale()); BufferedInputStream bufferdInputStream = new BufferedInputStream(inputStream); ServletOutputStream servletOutputStream = response.getOutputStream(); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(servletOutputStream); int bytesRead; byte buffer[] = new byte[2048]; while ((bytesRead = bufferdInputStream.read(buffer)) != -1) { bufferedOutputStream.write(buffer, 0, bytesRead); } // flush stream bufferedOutputStream.flush(); // close stream inputStream.close(); bufferdInputStream.close(); servletOutputStream.close(); bufferedOutputStream.close(); return null; }
From source file:org.displaytag.tags.TableTag.java
/** * Will write the export. The default behavior is to write directly to the response. If the ResponseOverrideFilter * is configured for this request, will instead write the exported content to a map in the Request object. * /*from www . j a va2s . com*/ * @param exportView export view * @throws JspException for problem in clearing the response or for invalid export views * @throws IOException exception thrown when writing content to the response */ protected void writeExport(ExportView exportView) throws IOException, JspException { String filename = this.properties.getExportFileName(this.currentMediaType); HttpServletResponse response = (HttpServletResponse) this.pageContext.getResponse(); HttpServletRequest request = (HttpServletRequest) this.pageContext.getRequest(); Map bean = (Map) request.getAttribute(FILTER_CONTENT_OVERRIDE_BODY); boolean usingFilter = bean != null; String mimeType = exportView.getMimeType(); // original encoding, be sure to add it back after reset() String characterEncoding = response.getCharacterEncoding(); if (usingFilter) { if (!bean.containsKey(TableTagParameters.BEAN_BUFFER)) { // We are running under the export filter, call it log.debug("Exportfilter enabled in unbuffered mode, setting headers"); response.addHeader(TableTagParameters.PARAMETER_EXPORTING, TagConstants.EMPTY_STRING); } else { // We are running under the export filter in buffered mode bean.put(TableTagParameters.BEAN_CONTENTTYPE, mimeType); bean.put(TableTagParameters.BEAN_FILENAME, filename); if (exportView instanceof TextExportView) { StringWriter writer = new StringWriter(); ((TextExportView) exportView).doExport(writer); bean.put(TableTagParameters.BEAN_BODY, writer.toString()); } else if (exportView instanceof BinaryExportView) { ByteArrayOutputStream stream = new ByteArrayOutputStream(); ((BinaryExportView) exportView).doExport(stream); bean.put(TableTagParameters.BEAN_BODY, stream.toByteArray()); } else { throw new JspTagException("Export view " + exportView.getClass().getName() + " must implement TextExportView or BinaryExportView"); } return; } } else { log.debug("Exportfilter NOT enabled"); // response can't be already committed at this time if (response.isCommitted()) { throw new ExportException(this.getClass()); } try { response.reset(); this.pageContext.getOut().clearBuffer(); } catch (Exception e) { throw new ExportException(this.getClass()); } } if (!usingFilter && characterEncoding != null && mimeType.indexOf("charset") == -1) //$NON-NLS-1$ { mimeType += "; charset=" + characterEncoding; //$NON-NLS-1$ } response.setContentType(mimeType); if (StringUtils.isNotEmpty(filename)) { response.setHeader("Content-Disposition", //$NON-NLS-1$ "attachment; filename=\"" + filename + "\""); //$NON-NLS-1$ //$NON-NLS-2$ } if (exportView instanceof TextExportView) { Writer writer; if (usingFilter) { writer = response.getWriter(); } else { writer = this.pageContext.getOut(); } ((TextExportView) exportView).doExport(writer); } else if (exportView instanceof BinaryExportView) { // dealing with binary content // note that this is not assured to work on any application server // if the filter is not enabled. According // to the jsp specs response.getOutputStream() should no be called // in jsps. ((BinaryExportView) exportView).doExport(response.getOutputStream()); } else { throw new JspTagException("Export view " + exportView.getClass().getName() + " must implement TextExportView or BinaryExportView"); } log.debug("Export completed"); }
From source file:org.apereo.portal.portlet.rendering.PortletRendererImpl.java
@Override public void doReset(IPortletWindowId portletWindowId, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { // Don't enforce config mode restriction because this is going to snap the portlet window back into view mode. final IPortletWindow portletWindow = this.portletWindowRegistry.getPortletWindow(httpServletRequest, portletWindowId);/* w w w .j ava2s . c o m*/ if (portletWindow != null) { portletWindow.setPortletMode(PortletMode.VIEW); portletWindow.setRenderParameters(new ParameterMap()); portletWindow.setExpirationCache(null); httpServletRequest = this.setupPortletRequest(httpServletRequest); httpServletResponse = new PortletHttpServletResponseWrapper(httpServletResponse, portletWindow); httpServletRequest.setAttribute(AdministrativeRequestListenerController.DEFAULT_LISTENER_KEY_ATTRIBUTE, "sessionActionListener"); httpServletRequest.setAttribute(PortletSessionAdministrativeRequestListener.ACTION, PortletSessionAdministrativeRequestListener.SessionAction.CLEAR); httpServletRequest.setAttribute(PortletSessionAdministrativeRequestListener.SCOPE, PortletSession.PORTLET_SCOPE); //TODO modify PortletContainer.doAdmin to create a specific "admin" req/res object and context so we don't have to fake it with a render req //These are required for a render request to be created and admin requests use a render request under the hood final String characterEncoding = httpServletResponse.getCharacterEncoding(); httpServletRequest.setAttribute(ATTRIBUTE__PORTLET_OUTPUT_HANDLER, new RenderPortletOutputHandler(characterEncoding)); httpServletRequest.setAttribute(ATTRIBUTE__PORTLET_CACHE_CONTROL, new CacheControlImpl()); try { this.portletContainer.doAdmin(portletWindow.getPlutoPortletWindow(), httpServletRequest, httpServletResponse); } catch (PortletException pe) { throw new PortletDispatchException( "The portlet window '" + portletWindow + "' threw an exception while executing admin command to clear session.", portletWindow, pe); } catch (PortletContainerException pce) { throw new PortletDispatchException( "The portlet container threw an exception while executing admin command to clear session on portlet window '" + portletWindow + "'.", portletWindow, pce); } catch (IOException ioe) { throw new PortletDispatchException( "The portlet window '" + portletWindow + "' threw an exception while executing admin command to clear session.", portletWindow, ioe); } } else { logger.debug( "ignoring doReset as portletWindowRegistry#getPortletWindow returned a null result for portletWindowId {}", portletWindowId); } }