Example usage for javax.servlet ServletResponse getCharacterEncoding

List of usage examples for javax.servlet ServletResponse getCharacterEncoding

Introduction

In this page you can find the example usage for javax.servlet ServletResponse 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.flexive.war.filter.FxRequestUtils.java

/**
 * Set the request and response character encodings to UTF-8 if they are not so already.
 * Either of the parameters may be set to null, in this case no action is performed.
 *
 * @param request   the servlet request//from w  w  w  .  j a  v a  2s  .  com
 * @param response  the servlet response
 */
public static void setCharacterEncoding(ServletRequest request, ServletResponse response) {
    if (request != null && !"UTF-8".equals(request.getCharacterEncoding())) {
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new IllegalArgumentException(e);
        }
    }
    if (response != null && !"UTF-8".equals(response.getCharacterEncoding())) {
        response.setCharacterEncoding("UTF-8");
    }
}

From source file:com.ethercamp.harmony.web.filter.JsonRpcUsageFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if ((request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) {
        final HttpServletRequest httpRequest = (HttpServletRequest) request;
        final HttpServletResponse httpResponse = (HttpServletResponse) response;

        // don't count alias as it redirects here
        final boolean isJsonRpcUrl = AppConst.JSON_RPC_PATH.equals(httpRequest.getRequestURI());

        if (isJsonRpcUrl && httpRequest.getMethod().equalsIgnoreCase("POST")) {

            try {
                final ResettableStreamHttpServletRequest wrappedRequest = new ResettableStreamHttpServletRequest(
                        httpRequest);//from w ww  . j  a v  a 2s. com

                final String body = IOUtils.toString(wrappedRequest.getReader());

                wrappedRequest.resetInputStream();

                if (response.getCharacterEncoding() == null) {
                    response.setCharacterEncoding("UTF-8");
                }
                final HttpServletResponseCopier responseCopier = new HttpServletResponseCopier(httpResponse);

                try {
                    chain.doFilter(wrappedRequest, responseCopier);
                    responseCopier.flushBuffer();
                } finally {
                    // read response for stats and log
                    final byte[] copy = responseCopier.getCopy();
                    final String responseText = new String(copy, response.getCharacterEncoding());

                    final JsonNode json = mapper.readTree(body);
                    final JsonNode responseJson = mapper.readTree(responseText);

                    if (json.isArray()) {
                        for (int i = 0; i < json.size(); i++) {
                            notifyInvocation(json.get(i), responseJson.get(i));
                        }
                    } else {
                        notifyInvocation(json, responseJson);
                    }

                    // According to spec, JSON-RPC 2 should return status 200 in case of error
                    if (httpResponse.getStatus() == 500) {
                        httpResponse.setStatus(200);
                    }
                }

            } catch (IOException e) {
                log.error("Error parsing JSON-RPC request", e);
            }
        } else {
            chain.doFilter(request, response);
        }
    } else {
        throw new RuntimeException("JsonRpcUsageFilter supports only HTTP requests.");
    }
}

From source file:com.redhat.rhn.frontend.servlets.DumpFilter.java

/** {@inheritDoc} */
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
        throws IOException, ServletException {

    if (log.isDebugEnabled()) {
        // handle request
        HttpServletRequest request = (HttpServletRequest) req;
        log.debug("Entered doFilter() ===================================");
        log.debug("AuthType: " + request.getAuthType());
        log.debug("Method: " + request.getMethod());
        log.debug("PathInfo: " + request.getPathInfo());
        log.debug("Translated path: " + request.getPathTranslated());
        log.debug("ContextPath: " + request.getContextPath());
        log.debug("Query String: " + request.getQueryString());
        log.debug("Remote User: " + request.getRemoteUser());
        log.debug("Remote Host: " + request.getRemoteHost());
        log.debug("Remote Addr: " + request.getRemoteAddr());
        log.debug("SessionId: " + request.getRequestedSessionId());
        log.debug("uri: " + request.getRequestURI());
        log.debug("url: " + request.getRequestURL().toString());
        log.debug("Servlet path: " + request.getServletPath());
        log.debug("Server Name: " + request.getServerName());
        log.debug("Server Port: " + request.getServerPort());
        log.debug("RESPONSE encoding: " + resp.getCharacterEncoding());
        log.debug("REQUEST encoding: " + request.getCharacterEncoding());
        log.debug("JVM encoding: " + System.getProperty("file.encoding"));
        logSession(request.getSession());
        logHeaders(request);/*w  w  w .j av a  2  s  .  c  o  m*/
        logCookies(request.getCookies());
        logParameters(request);
        logAttributes(request);
        log.debug("Calling chain.doFilter() -----------------------------");
    }

    chain.doFilter(req, resp);

    if (log.isDebugEnabled()) {
        log.debug("Returned from chain.doFilter() -----------------------");
        log.debug("Handle Response, not much to print");
        log.debug("Response: " + resp.toString());
        log.debug("Leaving doFilter() ===================================");
    }
}

From source file:org.apache.myfaces.application.jsp.JspViewHandlerImpl.java

public void renderView(FacesContext facesContext, UIViewRoot viewToRender) throws IOException, FacesException {
    if (viewToRender == null) {
        log.fatal("viewToRender must not be null");
        throw new NullPointerException("viewToRender must not be null");
    }//from  w  ww  .ja v  a 2 s  . com

    ExternalContext externalContext = facesContext.getExternalContext();

    String viewId = facesContext.getViewRoot().getViewId();

    if (PortletUtil.isPortletRequest(facesContext)) {
        externalContext.dispatch(viewId);
        return;
    }

    ServletMapping servletMapping = getServletMapping(externalContext);

    if (servletMapping != null && servletMapping.isExtensionMapping()) {
        String defaultSuffix = externalContext.getInitParameter(ViewHandler.DEFAULT_SUFFIX_PARAM_NAME);
        String suffix = defaultSuffix != null ? defaultSuffix : ViewHandler.DEFAULT_SUFFIX;
        DebugUtils.assertError(suffix.charAt(0) == '.', log, "Default suffix must start with a dot!");
        if (!viewId.endsWith(suffix)) {
            int dot = viewId.lastIndexOf('.');
            if (dot == -1) {
                if (log.isTraceEnabled())
                    log.trace("Current viewId has no extension, appending default suffix " + suffix);
                viewId = viewId + suffix;
            } else {
                if (log.isTraceEnabled())
                    log.trace("Replacing extension of current viewId by suffix " + suffix);
                viewId = viewId.substring(0, dot) + suffix;
            }
            facesContext.getViewRoot().setViewId(viewId);
        }
    }

    if (log.isTraceEnabled())
        log.trace("Dispatching to " + viewId);

    // handle character encoding as of section 2.5.2.2 of JSF 1.1
    if (externalContext.getResponse() instanceof ServletResponse) {
        ServletResponse response = (ServletResponse) externalContext.getResponse();
        response.setLocale(viewToRender.getLocale());
    }

    // TODO: 2.5.2.2 for Portlet?  What do I do?

    externalContext.dispatch(viewId);

    // handle character encoding as of section 2.5.2.2 of JSF 1.1
    if (externalContext.getRequest() instanceof HttpServletRequest) {
        HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
        HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
        HttpSession session = request.getSession(false);

        if (session != null) {
            session.setAttribute(ViewHandler.CHARACTER_ENCODING_KEY, response.getCharacterEncoding());
        }
    }

}

From source file:org.apache.myfaces.custom.ajax.api.AjaxDecodePhaseListener.java

private void encodeAjax(UIComponent component, FacesContext context) {
    ServletResponse response = (ServletResponse) context.getExternalContext().getResponse();
    ServletRequest request = (ServletRequest) context.getExternalContext().getRequest();
    UIViewRoot viewRoot = context.getViewRoot();
    Map requestMap = context.getExternalContext().getRequestParameterMap();

    String charset = (String) requestMap.get("charset");

    /* Handle character encoding as of section 2.5.2.2 of JSF 1.1:
     * At the beginning of the render-response phase, the ViewHandler must ensure
     * that the response Locale is set to that of the UIViewRoot, for exampe by
     * calling ServletResponse.setLocale() when running in the servlet environment.
     * Setting the response Locale may affect the response character encoding.
     */*  w  w w  .  java2s  .  c  o  m*/
     * Since there is no 'Render Response' phase for AJAX requests, we have to handle
     * this manually.
     */
    response.setLocale(viewRoot.getLocale());

    if (component instanceof DeprecatedAjaxComponent) {
        try {
            String contentType = getContentType("text/xml", charset);
            response.setContentType(contentType);

            StringBuffer buff = new StringBuffer();
            buff.append("<?xml version=\"1.0\"?>\n");
            buff.append("<response>\n");

            PrintWriter out = response.getWriter();
            out.print(buff);

            // imario@apache.org: setup response writer, otherwise the component will fail with an NPE. I dont know why this worked before.
            context.setResponseWriter(
                    new HtmlResponseWriterImpl(out, contentType, request.getCharacterEncoding()));

            if (component instanceof HtmlCommandButtonAjax) {
                buff = new StringBuffer();
                buff.append("<triggerComponent id=\"");
                buff.append(component.getClientId(context));
                buff.append("\" />\n");
                out.print(buff);

                // special treatment for this one, it will try to update the entire form
                // 1. get surrounding form
                //String elname = (String) requestMap.get("elname");
                FormInfo fi = RendererUtils.findNestingForm(component, context);
                UIComponent form = fi.getForm();
                //System.out.println("FOUND FORM: " + form);
                if (form != null) {
                    // special case, add responses from all components in form
                    encodeChildren(form, context, requestMap);
                }
            } else if (component instanceof AjaxComponent) {
                // let component render xml response
                // NOTE: probably don't need an encodeAjax in each component, but leaving it in until that's for sure
                ((AjaxComponent) component).encodeAjax(context);
            } else {
                // just get latest value
                AjaxRendererUtils.encodeAjax(context, component);
            }
            // end response
            out.print("</response>");
            out.flush();
        } catch (IOException e) {
            log.error("Exception while rendering ajax-response", e);
        }
    } else if (component instanceof AjaxComponent) {
        try {
            if (context.getResponseWriter() == null) {
                String contentType = getContentType("text/html", charset);
                response.setContentType(contentType);
                PrintWriter writer = response.getWriter();
                context.setResponseWriter(
                        new HtmlResponseWriterImpl(writer, contentType, response.getCharacterEncoding()));
            }

            ((AjaxComponent) component).encodeAjax(context);
        } catch (IOException e) {
            log.error("Exception while rendering ajax-response", e);
        }
    }

}

From source file:org.apache.myfaces.tomahawk.application.jsp.JspTilesViewHandlerImpl.java

private void dispatch(ExternalContext externalContext, UIViewRoot viewToRender, String viewId)
        throws IOException {
    if (log.isTraceEnabled())
        log.trace("Dispatching to " + viewId);

    // handle character encoding as of section 2.5.2.2 of JSF 1.1
    if (externalContext.getResponse() instanceof ServletResponse) {
        ServletResponse response = (ServletResponse) externalContext.getResponse();
        response.setLocale(viewToRender.getLocale());
    }/*  w  w w . j ava  2s . co m*/

    externalContext.dispatch(viewId);

    // handle character encoding as of section 2.5.2.2 of JSF 1.1
    if (externalContext.getRequest() instanceof HttpServletRequest) {
        HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
        HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
        HttpSession session = request.getSession(false);

        if (session != null) {
            session.setAttribute(ViewHandler.CHARACTER_ENCODING_KEY, response.getCharacterEncoding());
        }
    }

}

From source file:org.apache.sling.scripting.jsp.taglib.IncludeTagHandler.java

protected void dispatch(RequestDispatcher dispatcher, ServletRequest request, ServletResponse response)
        throws IOException, ServletException {

    // optionally flush
    if (flush && !(pageContext.getOut() instanceof BodyContent)) {
        // might throw an IOException of course
        pageContext.getOut().flush();/*from  w  w  w.  ja  v  a 2 s  .  co m*/
    }
    if (var == null) {
        dispatcher.include(request, response);
    } else {
        String encoding = response.getCharacterEncoding();
        BufferedServletOutputStream bsops = new BufferedServletOutputStream(encoding);
        try {
            CaptureResponseWrapper wrapper = new CaptureResponseWrapper((HttpServletResponse) response, bsops);
            dispatcher.include(request, wrapper);
            if (!wrapper.isBinaryResponse()) {
                wrapper.flushBuffer();
                pageContext.setAttribute(var, bsops.getBuffer(), scope);
            }
        } finally {
            IOUtils.closeQuietly(bsops);
        }
    }
}

From source file:org.apache.wiki.ui.WikiJSPFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws ServletException, IOException {
    WatchDog w = m_engine.getCurrentWatchDog();
    try {//from   w w w .j a v a 2  s .c o  m
        NDC.push(m_engine.getApplicationName() + ":" + ((HttpServletRequest) request).getRequestURI());

        w.enterState("Filtering for URL " + ((HttpServletRequest) request).getRequestURI(), 90);
        HttpServletResponseWrapper responseWrapper;

        if (m_useOutputStream) {
            log.debug("Using ByteArrayResponseWrapper");
            responseWrapper = new ByteArrayResponseWrapper((HttpServletResponse) response, m_wiki_encoding);
        } else {
            log.debug("Using MyServletResponseWrapper");
            responseWrapper = new MyServletResponseWrapper((HttpServletResponse) response, m_wiki_encoding);
        }

        // fire PAGE_REQUESTED event
        String pagename = DefaultURLConstructor.parsePageFromURL((HttpServletRequest) request,
                response.getCharacterEncoding());
        fireEvent(WikiPageEvent.PAGE_REQUESTED, pagename);

        super.doFilter(request, responseWrapper, chain);

        // The response is now complete. Lets replace the markers now.

        // WikiContext is only available after doFilter! (That is after
        //   interpreting the jsp)

        try {
            w.enterState("Delivering response", 30);
            WikiContext wikiContext = getWikiContext(request);
            String r = filter(wikiContext, responseWrapper);

            if (m_useOutputStream) {
                OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream(),
                        response.getCharacterEncoding());
                out.write(r);
                out.flush();
                out.close();
            } else {
                response.getWriter().write(r);
            }

            // Clean up the UI messages and loggers
            if (wikiContext != null) {
                wikiContext.getWikiSession().clearMessages();
            }

            // fire PAGE_DELIVERED event
            fireEvent(WikiPageEvent.PAGE_DELIVERED, pagename);

        } finally {
            w.exitState();
        }
    } finally {
        w.exitState();
        NDC.pop();
        NDC.remove();
    }
}

From source file:org.codehaus.groovy.grails.web.pages.GSPResponseWriter.java

/**
 * Static factory methdirectWritingod to create the writer.
 * @param response// ww w.  j av  a2  s.  co  m
 * @param max
 * @return  A GSPResponseWriter instance
 */
private static GSPResponseWriter getInstance(final ServletResponse response, final int max) {
    final BoundedCharsAsEncodedBytesCounter bytesCounter = new BoundedCharsAsEncodedBytesCounter();

    final StreamCharBuffer streamBuffer = new StreamCharBuffer(max, 0, max);
    streamBuffer.setChunkMinSize(max / 2);
    streamBuffer.setNotifyParentBuffersEnabled(false);

    final StreamCharBuffer.LazyInitializingWriter lazyResponseWriter = new StreamCharBuffer.LazyInitializingWriter() {
        public Writer getWriter() throws IOException {
            return response.getWriter();
        }
    };

    if (!(response instanceof GrailsContentBufferingResponse)) {
        streamBuffer.connectTo(new StreamCharBuffer.LazyInitializingMultipleWriter() {
            public Writer getWriter() throws IOException {
                return null;
            }

            public LazyInitializingWriter[] initializeMultiple(StreamCharBuffer buffer, boolean autoFlush)
                    throws IOException {
                final StreamCharBuffer.LazyInitializingWriter[] lazyWriters;
                if (CONTENT_LENGTH_COUNTING_ENABLED) {
                    lazyWriters = new StreamCharBuffer.LazyInitializingWriter[] {
                            new StreamCharBuffer.LazyInitializingWriter() {
                                public Writer getWriter() throws IOException {
                                    bytesCounter.setCapacity(max * 2);
                                    bytesCounter.setEncoding(response.getCharacterEncoding());
                                    return bytesCounter.getCountingWriter();
                                }
                            }, lazyResponseWriter };
                } else {
                    lazyWriters = new StreamCharBuffer.LazyInitializingWriter[] { lazyResponseWriter };
                }
                return lazyWriters;
            }
        }, AUTOFLUSH_ENABLED);
    } else {
        streamBuffer.connectTo(lazyResponseWriter);
    }

    if (instantiator != null) {
        GSPResponseWriter instance = (GSPResponseWriter) instantiator.newInstance();
        instance.initialize(streamBuffer, response, bytesCounter);
        return instance;
    } else {
        return new GSPResponseWriter(streamBuffer, response, bytesCounter);
    }
}

From source file:org.codelabor.system.web.filter.EncodingFilter.java

@Override
public void preprocessFilterChain(ServletRequest request, ServletResponse response)
        throws IOException, ServletException {
    String requestBeforeEncoding = request.getCharacterEncoding();
    String responseBeforeEncoding = response.getCharacterEncoding();

    if (encoding.equalsIgnoreCase(requestBeforeEncoding)) {
        logger.debug("request character encoding: {}", encoding);
    } else {/*  ww w .j a va2s .  c  o m*/
        request.setCharacterEncoding(encoding);
        String requestAfterEncoding = request.getCharacterEncoding();
        logger.debug("request character encoding: {} -> {}", requestBeforeEncoding, requestAfterEncoding);
    }
    if (encoding.equalsIgnoreCase(responseBeforeEncoding)) {
        logger.debug("response character encoding: {}", encoding);
    } else {
        response.setCharacterEncoding(encoding);
        String responseAfterCharacterEncoding = response.getCharacterEncoding();
        logger.debug("response character encoding: {} -> {}", responseBeforeEncoding,
                responseAfterCharacterEncoding);
    }
}