List of usage examples for javax.servlet.http HttpServletResponse getCharacterEncoding
public String getCharacterEncoding();
From source file:com.technologicaloddity.saha.util.AjaxPageRendererImpl.java
public String render(ModelAndView modelAndView, HttpServletRequest request, HttpServletResponse response) { String result = null;/* w ww . j a v a2 s. co m*/ StringWriter sout = new StringWriter(); StringBuffer buffer = sout.getBuffer(); HttpServletResponse fakeResponse = new SwallowingHttpServletResponse(response, sout, response.getCharacterEncoding()); Locale locale = this.localeResolver.resolveLocale(request); fakeResponse.setLocale(locale); request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, this.localeResolver); try { View view = viewResolver.resolveViewName(modelAndView.getViewName(), locale); view.render(modelAndView.getModel(), request, fakeResponse); result = buffer.toString(); } catch (Exception e) { result = "Ajax render error:" + e.getMessage(); } return result; }
From source file:org.cerberus.servlet.publi.ExecuteNextInQueue.java
/** * Executes the next test case represented by the given * {@link TestCaseExecutionInQueue}//from w ww. ja v a2 s. c o m * * @param lastInQueue * @param req * @param resp * @throws IOException */ private void executeNext(TestCaseExecutionInQueue lastInQueue, HttpServletRequest req, HttpServletResponse resp) throws IOException { String charset = resp.getCharacterEncoding(); String query = ""; try { ParamRequestMaker paramRequestMaker = makeParamRequestfromLastInQueue(lastInQueue); // TODO : Prefer use mkString(charset) instead of mkString(). // However the RunTestCase servlet does not decode parameters, // then we have to mkString() without using charset query = paramRequestMaker.mkString(); } catch (UnsupportedEncodingException uee) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, uee.getMessage()); return; } catch (IllegalArgumentException iae) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, iae.getMessage()); return; } catch (IllegalStateException ise) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, ise.getMessage()); return; } CloseableHttpClient httpclient = null; HttpGet httpget = null; try { httpclient = HttpClients.createDefault(); URI uri = new URIBuilder().setScheme(req.getScheme()).setHost(req.getServerName()) .setPort(req.getServerPort()).setPath(req.getContextPath() + RunTestCase.SERVLET_URL) .setCustomQuery(query).build(); httpget = new HttpGet(uri); } catch (URISyntaxException use) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, use.getMessage()); return; } CloseableHttpResponse response = null; try { response = httpclient.execute(httpget); if (response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) { resp.sendError(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); } } catch (ClientProtocolException cpe) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, cpe.getMessage()); } finally { if (response != null) { response.close(); } } }
From source file:org.springframework.cloud.netflix.zuul.filters.post.SendResponseFilter.java
private void writeResponse() throws Exception { RequestContext context = RequestContext.getCurrentContext(); // there is no body to send if (context.getResponseBody() == null && context.getResponseDataStream() == null) { return;//from w w w . j a v a 2s.c o m } HttpServletResponse servletResponse = context.getResponse(); if (servletResponse.getCharacterEncoding() == null) { // only set if not set servletResponse.setCharacterEncoding("UTF-8"); } OutputStream outStream = servletResponse.getOutputStream(); InputStream is = null; try { if (RequestContext.getCurrentContext().getResponseBody() != null) { String body = RequestContext.getCurrentContext().getResponseBody(); writeResponse(new ByteArrayInputStream(body.getBytes(servletResponse.getCharacterEncoding())), outStream); return; } boolean isGzipRequested = false; final String requestEncoding = context.getRequest().getHeader(ZuulHeaders.ACCEPT_ENCODING); if (requestEncoding != null && HTTPRequestUtils.getInstance().isGzipped(requestEncoding)) { isGzipRequested = true; } is = context.getResponseDataStream(); InputStream inputStream = is; if (is != null) { if (context.sendZuulResponse()) { // if origin response is gzipped, and client has not requested gzip, // decompress stream // before sending to client // else, stream gzip directly to client if (context.getResponseGZipped() && !isGzipRequested) { // If origin tell it's GZipped but the content is ZERO bytes, // don't try to uncompress final Long len = context.getOriginContentLength(); if (len == null || len > 0) { try { inputStream = new GZIPInputStream(is); } catch (java.util.zip.ZipException ex) { log.debug("gzip expected but not " + "received assuming unencoded response " + RequestContext.getCurrentContext().getRequest().getRequestURL() .toString()); inputStream = is; } } else { // Already done : inputStream = is; } } else if (context.getResponseGZipped() && isGzipRequested) { servletResponse.setHeader(ZuulHeaders.CONTENT_ENCODING, "gzip"); } writeResponse(inputStream, outStream); } } } finally { /** * Closing the wrapping InputStream itself has no effect on closing the underlying tcp connection since it's a wrapped stream. I guess for http * keep-alive. When closing the wrapping stream it tries to reach the end of the current request, which is impossible for infinite http streams. So * instead of closing the InputStream we close the HTTP response. * * @author Johannes Edmeier */ try { Object zuulResponse = RequestContext.getCurrentContext().get("zuulResponse"); if (zuulResponse instanceof Closeable) { ((Closeable) zuulResponse).close(); } outStream.flush(); // The container will close the stream for us } catch (IOException ex) { log.warn("Error while sending response to client: " + ex.getMessage()); } } }
From source file:codes.thischwa.c5c.requestcycle.response.GenericResponse.java
/** * Write the response to the {@link HttpServletResponse} (The character encoding of the {@link HttpServletResponse} will * be used. Inherited object could overwrite this to write * special content or headers./* w w w . j a v a 2s.c o m*/ * * @param resp * the resp * @throws IOException * Signals that an I/O exception has occurred. */ @JsonIgnore public void write(HttpServletResponse resp) throws IOException { if (mode != null && mode.getContentType() != null) resp.setContentType(mode.getContentType()); OutputStream out = resp.getOutputStream(); String json = toString(); IOUtils.write(json, out, resp.getCharacterEncoding()); IOUtils.closeQuietly(out); }
From source file:cn.guoyukun.spring.web.filter.DebugRequestAndResponseFilter.java
private void debugResponse(HttpServletResponse response) { log.debug("=====================response begin=========================="); log.debug("status:{}", response.getStatus(), response.getContentType()); log.debug("contentType:{}, characterEncoding:{}", response.getContentType(), response.getCharacterEncoding()); log.debug("===header begin============================================"); Collection<String> headerNames = response.getHeaderNames(); for (String name : headerNames) { String value = StringUtils.join(response.getHeaders(name), "||"); log.debug("{}={}", name, value); }/*from w ww.j a v a 2 s . com*/ log.debug("===header end============================================"); log.debug("=====================response end=========================="); }
From source file:org.brutusin.rpc.http.RpcServlet.java
/** * * @param req/*from w w w. j ava2 s. c o m*/ * @param resp * @throws IOException */ private static void addContentLocation(HttpServletRequest req, HttpServletResponse resp) throws IOException { StringBuffer requestURL = req.getRequestURL(); Map<String, String[]> parameterMap = getParameterMap(req); boolean first = true; for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) { String name = entry.getKey(); String[] value = entry.getValue(); for (int i = 0; i < value.length; i++) { if (first) { first = false; requestURL.append("?"); } else { requestURL.append("&"); } try { requestURL.append(name).append("=") .append(URLEncoder.encode(value[i], resp.getCharacterEncoding())); } catch (UnsupportedEncodingException ex) { throw new AssertionError(); } } } resp.addHeader("Content-Location", resp.encodeRedirectURL(requestURL.toString())); }
From source file:fr.mby.portal.coreimpl.message.AbstractMimeReply.java
/** * @param backingOutputStream/*from w w w. j a v a2 s . c o m*/ * @param backingStream * */ public AbstractMimeReply(final HttpServletResponse response, final OutputStream backingOutputStream) { super(); this.contentType = response.getContentType(); this.characterEncoding = response.getCharacterEncoding(); this.backingStream = backingOutputStream; }
From source file:org.jasig.portlet.cms.controller.DownloadPostAttachmentController.java
@RequestMapping protected void handleRequest(final HttpServletRequest request, final HttpServletResponse response) throws Exception { final HttpSession session = request.getSession(); final Attachment attachment = (Attachment) session.getAttribute("attachment"); logDebug("Attempting to download attachment: " + attachment); response.setContentType("application/x-download"); logDebug("Set content type to: " + response.getContentType()); final String encoding = response.getCharacterEncoding(); logDebug("Encoded file name based on: " + encoding); final String fileName = URLEncoder.encode(attachment.getFileName(), encoding); response.setHeader("Content-Disposition", "attachment; filename=" + fileName); logDebug("Downloading file: " + fileName); final OutputStream out = response.getOutputStream(); out.write(attachment.getContents()); out.flush();//from ww w . ja va 2 s . c om logDebug("Clearing session attribute"); session.setAttribute("attachment", null); }
From source file:net.ymate.framework.core.util.WebUtils.java
/** * @param request HttpServletRequest * @param response HttpServletResponse * @param jspFile JSP/*from ww w . ja v a2s . c o m*/ * @param charsetEncoding ? * @return JSPHTML?? * @throws ServletException ? * @throws IOException ? */ public static String includeJSP(HttpServletRequest request, HttpServletResponse response, String jspFile, String charsetEncoding) throws ServletException, IOException { final OutputStream _output = new ByteArrayOutputStream(); final PrintWriter _writer = new PrintWriter(new OutputStreamWriter(_output)); final ServletOutputStream _servletOutput = new ServletOutputStream() { @Override public void write(int b) throws IOException { _output.write(b); } @Override public void write(byte[] b, int off, int len) throws IOException { _output.write(b, off, len); } }; HttpServletResponse _response = new HttpServletResponseWrapper(response) { @Override public ServletOutputStream getOutputStream() { return _servletOutput; } @Override public PrintWriter getWriter() { return _writer; } }; charsetEncoding = StringUtils.defaultIfEmpty(charsetEncoding, response.getCharacterEncoding()); _response.setCharacterEncoding(StringUtils.defaultIfEmpty(charsetEncoding, WebMVC.get().getModuleCfg().getDefaultCharsetEncoding())); request.getRequestDispatcher(jspFile).include(request, _response); _writer.flush(); return _output.toString(); }
From source file:edu.wisc.my.portlets.dmp.web.CachingXsltView.java
@SuppressWarnings("unchecked") @Override//from w w w.j a v a 2 s . c o m protected void doTransform(Map model, Source source, HttpServletRequest request, HttpServletResponse response) throws Exception { final Map parameters = getParameters(model, request); final Serializable cacheKey = this.getCacheKey(model, source, parameters); String cachedData; synchronized (this.xsltResultCache) { cachedData = this.xsltResultCache.get(cacheKey); if (cachedData == null) { final StringWriter writer = new StringWriter(); final String encoding = response.getCharacterEncoding(); this.doTransform(source, parameters, new StreamResult(writer), encoding); cachedData = writer.getBuffer().toString(); this.xsltResultCache.put(cacheKey, cachedData); } } if (useWriter()) { final PrintWriter writer = response.getWriter(); writer.write(cachedData); writer.flush(); } else { final OutputStream outputStream = new BufferedOutputStream(response.getOutputStream()); outputStream.write(cachedData.getBytes()); outputStream.flush(); } }