List of usage examples for javax.servlet.http HttpServletResponse getCharacterEncoding
public String getCharacterEncoding();
From source file:org.apache.velocity.tools.view.VelocityView.java
public Template getTemplate(HttpServletRequest request, HttpServletResponse response) { String path = ServletUtils.getPath(request); if (response == null) { return getTemplate(path); } else {//from w ww .j a v a 2s . co m return getTemplate(path, response.getCharacterEncoding()); } }
From source file:grails.plugin.cache.web.filter.PageFragmentCachingFilter.java
/** * Assembles a response from a cached page include. These responses are never * gzipped The content length should not be set in the response, because it * is a fragment of a page. Don't write any headers at all. *///from www .j a va 2 s .c o m protected void writeResponse(final HttpServletResponse response, final PageInfo pageInfo) throws IOException { byte[] cachedPage = pageInfo.getUngzippedBody(); String page = new String(cachedPage, response.getCharacterEncoding()); String implementationVendor = response.getClass().getPackage().getImplementationVendor(); if (implementationVendor != null && implementationVendor.equals("\"Evermind\"")) { response.getOutputStream().print(page); } else { response.getWriter().write(page); } }
From source file:org.jasig.cas.web.HealthCheckController.java
/** {@inheritDoc} */ protected ModelAndView handleRequestInternal(final HttpServletRequest request, final HttpServletResponse response) throws Exception { final HealthStatus healthStatus = this.healthCheckMonitor.observe(); final StringBuilder sb = new StringBuilder(); sb.append("Health: ").append(healthStatus.getCode()); String name;/*from w w w . j ava2 s. c o m*/ Status status; int i = 0; for (final Map.Entry<String, Status> entry : healthStatus.getDetails().entrySet()) { name = entry.getKey(); status = entry.getValue(); response.addHeader("X-CAS-" + name, String.format("%s;%s", status.getCode(), status.getDescription())); sb.append("\n\n\t").append(++i).append('.').append(name).append(": "); sb.append(status.getCode()); if (status.getDescription() != null) { sb.append(" - ").append(status.getDescription()); } } response.setStatus(healthStatus.getCode().value()); response.setContentType("text/plain"); response.getOutputStream().write(sb.toString().getBytes(response.getCharacterEncoding())); // Return null to signal MVC framework that we handled response directly return null; }
From source file:org.jasig.cas.web.report.HealthCheckController.java
/** * Handle request.// w ww . j a va 2 s . c om * * @param request the request * @param response the response * @return the model and view * @throws Exception the exception */ @RequestMapping(method = RequestMethod.GET) protected ModelAndView handleRequestInternal(final HttpServletRequest request, final HttpServletResponse response) throws Exception { final HealthStatus healthStatus = this.healthCheckMonitor.observe(); final StringBuilder sb = new StringBuilder(); sb.append("Health: ").append(healthStatus.getCode()); String name; Status status; int i = 0; for (final Map.Entry<String, Status> entry : healthStatus.getDetails().entrySet()) { name = entry.getKey(); status = entry.getValue(); response.addHeader("X-CAS-" + name, String.format("%s;%s", status.getCode(), status.getDescription())); sb.append("\n\n\t").append(++i).append('.').append(name).append(": "); sb.append(status.getCode()); if (status.getDescription() != null) { sb.append(" - ").append(status.getDescription()); } } response.setStatus(healthStatus.getCode().value()); response.setContentType("text/plain"); response.getOutputStream().write(sb.toString().getBytes(response.getCharacterEncoding())); // Return null to signal MVC framework that we handled response directly return null; }
From source file:org.smigo.log.LogHandler.java
public String getRequestDump(HttpServletRequest request, HttpServletResponse response, String separator) { StringBuilder s = new StringBuilder("####REQUEST ").append(request.getMethod()).append(" ") .append(request.getRequestURL()).append(separator); s.append("Auth type:").append(request.getAuthType()).append(separator); s.append("Principal:").append(request.getUserPrincipal()).append(separator); s.append(Log.create(request, response).toString()).append(separator); s.append("Headers:").append(separator); Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); s.append(headerName).append("=").append(request.getHeader(headerName)).append(separator); }//from w ww.j ava2 s. co m s.append(separator); s.append("####RESPONSE").append(separator); s.append("Status:").append(response.getStatus()).append(separator); s.append("Char encoding:").append(response.getCharacterEncoding()).append(separator); s.append("Locale:").append(response.getLocale()).append(separator); s.append("Content type:").append(response.getContentType()).append(separator); s.append("Headers:").append(separator); s.append(response.getHeaderNames().stream().map(rh -> rh + "=" + response.getHeader(rh)) .collect(Collectors.joining(separator))); final Long start = (Long) request.getAttribute(RequestLogFilter.REQUEST_TIMER); if (start != null) { final long elapsedTime = System.nanoTime() - start; s.append(separator).append("####Request time elapsed:").append(elapsedTime); s.append("ns which is ").append(elapsedTime / 1000000).append("ms").append(separator); } return s.toString(); }
From source file:net.bull.javamelody.TestMonitoringFilter.java
/** Test. * @throws IOException e *///from w w w.java 2 s . c om @Test public void testFilterServletResponseWrapper() throws IOException { final HttpServletResponse response = createNiceMock(HttpServletResponse.class); expect(response.getOutputStream()).andReturn(new FilterServletOutputStream(new ByteArrayOutputStream())) .anyTimes(); expect(response.getCharacterEncoding()).andReturn("ISO-8859-1").anyTimes(); final CounterServletResponseWrapper wrappedResponse = new CounterServletResponseWrapper(response); replay(response); assertNotNull("getOutputStream", wrappedResponse.getOutputStream()); assertNotNull("getOutputStream bis", wrappedResponse.getOutputStream()); assertNotNull("getOutputStream", wrappedResponse.getCharacterEncoding()); wrappedResponse.close(); verify(response); final HttpServletResponse response2 = createNiceMock(HttpServletResponse.class); expect(response2.getOutputStream()).andReturn(new FilterServletOutputStream(new ByteArrayOutputStream())) .anyTimes(); expect(response2.getCharacterEncoding()).andReturn(null).anyTimes(); final CounterServletResponseWrapper wrappedResponse2 = new CounterServletResponseWrapper(response); replay(response2); assertNotNull("getWriter", wrappedResponse2.getWriter()); assertNotNull("getWriter bis", wrappedResponse2.getWriter()); wrappedResponse2.close(); verify(response2); }
From source file:org.opencms.ade.galleries.CmsPreviewService.java
/** * Renders the preview content for the given resource and locale.<p> * * @param request the current servlet request * @param response the current servlet response * @param cms the cms context// ww w . j a v a2 s . c o m * @param resource the resource * @param locale the content locale * * @return the rendered HTML preview content */ public static String getPreviewContent(HttpServletRequest request, HttpServletResponse response, CmsObject cms, CmsResource resource, Locale locale) { try { if (CmsResourceTypeXmlContent.isXmlContent(resource)) { CmsADEConfigData adeConfig = OpenCms.getADEManager().lookupConfiguration(cms, cms.getRequestContext().getRootUri()); CmsFormatterConfiguration formatters = adeConfig.getFormatters(cms, resource); I_CmsFormatterBean formatter = formatters.getPreviewFormatter(); if (formatter != null) { CmsObject tempCms = OpenCms.initCmsObject(cms); tempCms.getRequestContext().setLocale(locale); CmsResource formatterResource = tempCms.readResource(formatter.getJspStructureId()); request.setAttribute(CmsJspStandardContextBean.ATTRIBUTE_CMS_OBJECT, tempCms); CmsJspStandardContextBean standardContext = CmsJspStandardContextBean.getInstance(request); CmsContainerElementBean element = new CmsContainerElementBean(resource.getStructureId(), formatter.getJspStructureId(), null, false); if ((resource instanceof I_CmsHistoryResource) && (resource instanceof CmsFile)) { element.setHistoryFile((CmsFile) resource); } element.initResource(tempCms); CmsContainerBean containerBean = new CmsContainerBean("PREVIEW", CmsFormatterBean.PREVIEW_TYPE, null, true, 1, Collections.<CmsContainerElementBean>emptyList()); containerBean.setWidth(String.valueOf(CmsFormatterBean.PREVIEW_WIDTH)); standardContext.setContainer(containerBean); standardContext.setElement(element); standardContext.setEdited(true); standardContext.setPage( new CmsContainerPageBean(Collections.<CmsContainerBean>singletonList(containerBean))); String encoding = response.getCharacterEncoding(); return (new String(OpenCms.getResourceManager().getLoader(formatterResource).dump(tempCms, formatterResource, null, locale, request, response), encoding)).trim(); } } } catch (Exception e) { LOG.warn(e.getLocalizedMessage(), e); //TODO: logging } return null; }
From source file:org.apache.velocity.tools.view.servlet.VelocityViewServlet.java
/** * <p>Procure a Writer with correct encoding which can be used * even if HttpServletResponse's <code>getOutputStream()</code> method * has already been called.</p>// www. ja v a 2 s .co m * * <p>This is a transitional method which will be removed in a * future version of Velocity. It is not recommended that you * override this method.</p> * * @param response The response. * @return A <code>Writer</code>, possibly created using the * <code>getOutputStream()</code>. */ protected Writer getResponseWriter(HttpServletResponse response) throws UnsupportedEncodingException, IOException { Writer writer = null; try { writer = response.getWriter(); } catch (IllegalStateException e) { // ASSUMPTION: We already called getOutputStream(), so // calls to getWriter() fail. Use of OutputStreamWriter // assures our desired character set if (this.warnOfOutputStreamDeprecation) { this.warnOfOutputStreamDeprecation = false; velocity.warn("VelocityViewServlet: " + "Use of ServletResponse's getOutputStream() " + "method with VelocityViewServlet is " + "deprecated -- support will be removed in " + "an upcoming release"); } // Assume the encoding has been set via setContentType(). String encoding = response.getCharacterEncoding(); if (encoding == null) { encoding = DEFAULT_OUTPUT_ENCODING; } writer = new OutputStreamWriter(response.getOutputStream(), encoding); } return writer; }
From source file:org.apache.myfaces.renderkit.html.util.DefaultAddResource.java
/** * Add the resources to the <head> of the page. * If the head tag is missing, but the <body> tag is present, the head tag is added. * If both are missing, no resource is added. * <p/>/*from w ww .j a va2 s .c om*/ * The ordering is such that the user header CSS & JS override the MyFaces' ones. */ public void writeWithFullHeader(HttpServletRequest request, HttpServletResponse response) throws IOException { if (!parserCalled) { throw new IOException("Method parseResponse has to be called first"); } boolean addHeaderTags = false; if (headerInsertPosition == -1) { if (beforeBodyPosition != -1) { // The input html has a body start tag, but no head tags. We therefore // need to insert head start/end tags for our content to live in. addHeaderTags = true; headerInsertPosition = beforeBodyPosition; } else { // neither head nor body tags in the input log.warn("Response has no <head> or <body> tag:\n" + originalResponse); } } ResponseWriter writer = new HtmlResponseWriterImpl(response.getWriter(), HtmlRendererUtils.selectContentType(request.getHeader("accept")), response.getCharacterEncoding()); if (afterBodyContentInsertPosition >= 0) { // insert all the items that want to go immediately after the <body> tag. HtmlBufferResponseWriterWrapper writerWrapper = HtmlBufferResponseWriterWrapper.getInstance(writer); for (Iterator i = getBodyEndInfos().iterator(); i.hasNext();) { writerWrapper.write("\n"); PositionedInfo positionedInfo = (PositionedInfo) i.next(); if (!(positionedInfo instanceof WritablePositionedInfo)) throw new IllegalStateException( "positionedInfo of type : " + positionedInfo.getClass().getName()); ((WritablePositionedInfo) positionedInfo).writePositionedInfo(response, writerWrapper); } originalResponse.insert(headerInsertPosition, writerWrapper.toString()); } if (bodyInsertPosition > 0) { StringBuffer buf = new StringBuffer(); Set bodyInfos = getBodyOnloadInfos(); if (bodyInfos.size() > 0) { int i = 0; for (Iterator it = getBodyOnloadInfos().iterator(); it.hasNext();) { AttributeInfo positionedInfo = (AttributeInfo) it.next(); if (i == 0) { buf.append(positionedInfo.getAttributeName()); buf.append("=\""); } buf.append(positionedInfo.getAttributeValue()); i++; } buf.append("\""); originalResponse.insert(bodyInsertPosition - 1, " " + buf.toString()); } } if (headerInsertPosition >= 0) { HtmlBufferResponseWriterWrapper writerWrapper = HtmlBufferResponseWriterWrapper.getInstance(writer); if (addHeaderTags) writerWrapper.write("<head>"); for (Iterator i = getHeaderBeginInfos().iterator(); i.hasNext();) { writerWrapper.write("\n"); PositionedInfo positionedInfo = (PositionedInfo) i.next(); if (!(positionedInfo instanceof WritablePositionedInfo)) throw new IllegalStateException( "positionedInfo of type : " + positionedInfo.getClass().getName()); ((WritablePositionedInfo) positionedInfo).writePositionedInfo(response, writerWrapper); } if (addHeaderTags) writerWrapper.write("</head>"); originalResponse.insert(headerInsertPosition, writerWrapper.toString()); } }
From source file:org.polymap.core.mapeditor.services.SimpleJsonServer.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.info("Accept-Encoding: " + request.getHeader("Accept-Encoding")); log.info("### JSON: about to encode JSON...."); boolean gzip = request.getHeader("Accept-Encoding").toLowerCase().contains("gzip"); // prevent caching response.setHeader("Cache-Control", "no-cache"); // HTTP 1.1 response.setHeader("Pragma", "no-cache"); // HTTP 1.0 response.setDateHeader("Expires", 0); // prevents caching at the proxy response.setCharacterEncoding("UTF-8"); Timer timer = new Timer(); log.debug("SimpleJsonServer Output: "); OutputStream debugOut = /*log.isDebugEnabled() ? new TeeOutputStream( response.getOutputStream(), System.out ) : */response.getOutputStream(); CountingOutputStream out = null, cout2 = null; if (gzip) {/*from w w w . jav a 2 s .com*/ response.setHeader("Content-Encoding", "gzip"); //response.setHeader( "Content-Type", "text/javascript" ); cout2 = new CountingOutputStream(debugOut); out = new CountingOutputStream(new GZIPOutputStream(cout2)); } else { out = new CountingOutputStream(debugOut); } String layerName = StringUtils.substringAfterLast(request.getPathInfo(), "/"); JsonEncoder layer = null; synchronized (layers) { layer = layers.get(layerName); } layer.encode(out, response.getCharacterEncoding()); out.close(); log.info(" JSON bytes: " + out.getCount() + " (" + timer.elapsedTime() + "ms)"); if (cout2 != null) { log.info(" GZIPed bytes written: " + cout2.getCount()); } if (layer.isOneShot()) { removeLayer(layer); log.info(" Layer is oneShot -> removed."); } }