Example usage for javax.servlet.http HttpServletResponse getCharacterEncoding

List of usage examples for javax.servlet.http HttpServletResponse getCharacterEncoding

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse getCharacterEncoding.

Prototype

public String getCharacterEncoding();

Source Link

Document

Returns the name of the character encoding (MIME charset) used for the body sent in this response.

Usage

From source file:com.easyjf.web.core.FrameworkEngine.java

/**
 * Writer/*from ww  w. jav a2  s  .c  o  m*/
 * 
 * @param response
 * @return 
 * @throws UnsupportedEncodingException
 * @throws IOException
 */
public static Writer getResponseWriter(HttpServletResponse response)
        throws UnsupportedEncodingException, IOException {
    Writer writer = null;
    try {
        writer = response.getWriter();
    } catch (IllegalStateException e) {
        String encoding = response.getCharacterEncoding();
        if (encoding == null) {
            encoding = DEFAULT_OUTPUT_ENCODING;
        }
        writer = new OutputStreamWriter(response.getOutputStream(), encoding);
    }
    return writer;
}

From source file:com.act.web.includeservletasstring.IncludeServletAsString.java

static public String invokeServletAndReturnAsString(String url, HttpServletRequest servletRequest,
        HttpServletResponse servletResponse) throws IOException, ServletException {

    if (log.isDebugEnabled()) {
        log.debug("Including url \"" + url + "\"...");
    }//from w  w  w  . j a  va2 s.com

    RequestDispatcher requestDispatcher = servletRequest.getRequestDispatcher(url);

    if (requestDispatcher == null) {
        IllegalArgumentException iae = new IllegalArgumentException(
                "Failed to get RequestDispatcher for url: " + url);
        log.error(iae.getMessage(), iae);
        throw iae;
    }

    BufferedResponse bufferedResponse = new BufferedResponse(servletResponse);

    requestDispatcher.include(servletRequest, bufferedResponse);

    byte[] buffer = bufferedResponse.getBufferAsByteArray();
    if (log.isDebugEnabled()) {
        log.debug("Buffer returned with " + buffer.length + " bytes.");
    }

    String bufferString = new String(buffer, servletResponse.getCharacterEncoding());

    return bufferString;
}

From source file:org.olat.core.gui.media.ServletUtil.java

public static void serveStringResource(HttpServletResponse response, StringOutput result) {
    setStringResourceHeaders(response);// ww  w .j  ava  2 s.  c om
    // log the response headers prior to sending the output
    boolean isDebug = log.isDebug();
    if (isDebug) {
        log.debug(
                "\nResponse headers (some)\ncontent type:" + response.getContentType() + "\ncharacterencoding:"
                        + response.getCharacterEncoding() + "\nlocale:" + response.getLocale());
    }

    try {
        long rstart = 0;
        if (isDebug || true) {
            rstart = System.currentTimeMillis();
        }
        // make a ByteArrayOutputStream to be able to determine the length.
        // buffer size: assume average length of a char in bytes is max 2
        int encLen = result.length();
        Reader reader = result.getReader();
        //response.setContentLength(encLen); set the number of characters, must be number of bytes

        PrintWriter os = response.getWriter();
        IOUtils.copy(reader, os);
        os.close();

        if (isDebug) {
            log.debug("time to serve inline-resource " + result.length() + " chars / " + encLen + " bytes: "
                    + (System.currentTimeMillis() - rstart));
        }
    } catch (IOException e) {
        if (isDebug) {
            log.warn("client browser abort when serving inline", e);
        }
    }
}

From source file:org.olat.core.gui.media.ServletUtil.java

/**
 * @param response//from w ww.j  ava2 s.  co m
 * @param result
 */
public static void serveStringResource(HttpServletRequest httpReq, HttpServletResponse response,
        String result) {
    setStringResourceHeaders(response);

    // log the response headers prior to sending the output
    boolean isDebug = log.isDebug();

    if (isDebug) {
        log.debug(
                "\nResponse headers (some)\ncontent type:" + response.getContentType() + "\ncharacterencoding:"
                        + response.getCharacterEncoding() + "\nlocale:" + response.getLocale());
    }

    try {
        long rstart = 0;
        if (isDebug) {
            rstart = System.currentTimeMillis();
        }
        // make a ByteArrayOutputStream to be able to determine the length.
        // buffer size: assume average length of a char in bytes is max 2
        ByteArrayOutputStream baos = new ByteArrayOutputStream(result.length() * 2);

        // we ignore the accept-charset from the request and always write in
        // utf-8:
        // we have lots of different languages (content) in one application to
        // support, and more importantly,
        // a blend of olat translations and content by authors which can be in
        // different languages.
        OutputStreamWriter osw = new OutputStreamWriter(baos, "utf-8");
        osw.write(result);
        osw.close();
        // the data is now utf-8 encoded in the bytearray -> push it into the outputstream
        int encLen = baos.size();
        response.setContentLength(encLen);

        OutputStream os;
        if (Settings.isDebuging()) {
            SlowBandWidthSimulator sbs = Windows
                    .getWindows(CoreSpringFactory.getImpl(UserSessionManager.class).getUserSession(httpReq))
                    .getSlowBandWidthSimulator();
            os = sbs.wrapOutputStream(response.getOutputStream());
        } else {
            os = response.getOutputStream();
        }
        byte[] bout = baos.toByteArray();
        os.write(bout);
        os.close();

        if (isDebug) {
            long rstop = System.currentTimeMillis();
            log.debug("time to serve inline-resource " + result.length() + " chars / " + encLen + " bytes: "
                    + (rstop - rstart));
        }
    } catch (IOException e) {
        if (isDebug) {
            log.warn("client browser abort when serving inline", e);
        }
    }
}

From source file:net.ymate.platform.webmvc.view.impl.HtmlView.java

protected void __doRenderView() throws Exception {
    HttpServletResponse _response = WebContext.getResponse();
    IOUtils.write(__content, _response.getOutputStream(), _response.getCharacterEncoding());
}

From source file:com.laxser.blitz.web.instruction.TextInstruction.java

@Override
public void doRender(Invocation inv) throws Exception {
    if (StringUtils.isEmpty(text)) {
        return;/*from   ww w. j  a v a 2  s.com*/
    }

    if (logger.isDebugEnabled()) {
        logger.debug("trying to render text:" + text);
    }

    HttpServletResponse response = inv.getResponse();
    String oldEncoding = response.getCharacterEncoding();
    if (StringUtils.isBlank(oldEncoding) || oldEncoding.startsWith("ISO-")) {
        String encoding = inv.getRequest().getCharacterEncoding();
        Assert.isTrue(encoding != null);
        response.setCharacterEncoding(encoding);
        if (logger.isDebugEnabled()) {
            logger.debug("set response.characterEncoding by default:" + response.getCharacterEncoding());
        }
    }

    if (response.getContentType() == null) {
        response.setContentType("text/html");
        if (logger.isDebugEnabled()) {
            logger.debug("set response content-type by default: " + response.getContentType());
        }
    }
    sendResponse(response, text);
}

From source file:org.siphon.servlet.DummyHttpServletResponse.java

public DummyHttpServletResponse(HttpServletResponse response) {
    super(response);
    os = new WriterOutputStream(myout, response.getCharacterEncoding());
}

From source file:net.ymate.platform.webmvc.view.impl.HttpStatusView.java

protected void __doRenderView() throws Exception {
    HttpServletResponse _response = WebContext.getResponse();
    if (StringUtils.isNotBlank(__body)) {
        IOUtils.write(__body, _response.getOutputStream(), _response.getCharacterEncoding());
    }//from www .  j  a  v a 2  s. co  m
    if (StringUtils.isNotBlank(__msg)) {
        _response.sendError(__status, __msg);
    } else {
        if (__error) {
            _response.sendError(__status);
        } else {
            _response.setStatus(__status);
        }
    }
}

From source file:de.codecentric.boot.admin.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;//w w  w  .  j  a va  2  s .c  om
    }
    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 {
        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) {
        }
    }
}