Example usage for javax.servlet ServletRequest getCharacterEncoding

List of usage examples for javax.servlet ServletRequest getCharacterEncoding

Introduction

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

Prototype

public String getCharacterEncoding();

Source Link

Document

Returns the name of the character encoding used in the body of this request.

Usage

From source file:org.apache.roller.weblogger.ui.core.filters.CharEncodingFilter.java

/**
 * Set the character encoding and sync up Struts and JSTL locales.  This filter should normally be first (and last)
 * in the chain.// ww  w.j  av a2 s.c o  m
 */
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    if (mLogger.isDebugEnabled())
        mLogger.debug("Processing CharEncodingFilter");
    try {
        if (!"UTF-8".equals(req.getCharacterEncoding())) {
            // only set encoding if not already UTF-8
            // despite the fact that this is the first filter in the chain, on Glassfish it 
            // is already too late to set request encoding without getting a WARN level log message
            req.setCharacterEncoding("UTF-8");
        }
        if (mLogger.isDebugEnabled())
            mLogger.debug("Set request character encoding to UTF-8");

    } catch (UnsupportedEncodingException e) {
        // This should never happen since UTF-8 is a Java-specified required encoding.
        throw new ServletException("Can't set incoming encoding to UTF-8");
    }

    chain.doFilter(req, res);
}

From source file:org.apache.shale.tiles.TilesViewHandler.java

/**
 * <p>Render a view according to the algorithm described in this class's
 * description: Based on the view Id of the <code>viewToRender</code>,
 * this method either renders a tile or delegates rendering to the default
 * view handler, which takes care of business as usual.</p>
 *
 * @param facesContext The faces context object for this request
 * @param viewToRender The view that we're rendering
 *
 * Modified to do the same thing as SunRI wjb Oct 2006 courtesy sdoglesby
 *
 * March 2007 significantly rewritten /*from   ww  w . j av a2s.  co m*/
 * @author wbossons
 */
public void renderView(FacesContext facesContext, UIViewRoot viewToRender) throws IOException, FacesException {
    String viewId = viewToRender.getViewId();
    String tileName = getTileName(viewId);
    ComponentDefinition tile = getTile(tileName);
    //DEBUG: Significant rewrite.
    if (!viewToRender.isRendered()) {
        return;
    }

    if (tile != null) {
        ExternalContext extContext = facesContext.getExternalContext();

        dispatchToTile(extContext, tile);

        ServletRequest request = (ServletRequest) extContext.getRequest();
        ServletResponse response = (ServletResponse) extContext.getResponse();

        try {
            if (executePageToBuildView(facesContext, viewToRender, tile)) {
                response.flushBuffer();
                ApplicationAssociate applicationassociate = ApplicationAssociate.getInstance(extContext);
                this.responseRendered();
                return;
            }
        } catch (IOException e) {
            throw new FacesException(e);
        }
        if (logger.isLoggable(Level.WARNING)) { //default was fine
            logger.log(Level.FINE, "Completed building view for : \n" + viewToRender.getViewId());
        }
        if (logger.isLoggable(Level.INFO)) { // default was finest
            logger.log(Level.FINEST,
                    "+=+=+=+=+=+= Printout for " + viewToRender.getViewId() + " about to render.");
            DebugUtil.printTree(viewToRender, logger, Level.FINEST);
        }

        // set up the ResponseWriter

        RenderKitFactory renderFactory = (RenderKitFactory) FactoryFinder
                .getFactory(FactoryFinder.RENDER_KIT_FACTORY);
        RenderKit renderKit = renderFactory.getRenderKit(facesContext, viewToRender.getRenderKitId());

        ResponseWriter oldWriter = facesContext.getResponseWriter();

        if (bufSize == -1) {
            WebConfiguration webConfig = WebConfiguration.getInstance(facesContext.getExternalContext());
            try {
                bufSize = Integer.parseInt(
                        webConfig.getContextInitParameter(WebContextInitParameter.ResponseBufferSize));
            } catch (NumberFormatException nfe) {
                bufSize = Integer.parseInt(WebContextInitParameter.ResponseBufferSize.getDefaultValue());
            }
        }
        WriteBehindStringWriter strWriter = new WriteBehindStringWriter(facesContext, bufSize);
        ResponseWriter newWriter;
        if (null != oldWriter) {
            newWriter = oldWriter.cloneWithWriter(strWriter);
        } else {
            newWriter = renderKit.createResponseWriter(strWriter, null, request.getCharacterEncoding());
        }
        facesContext.setResponseWriter(newWriter);

        newWriter.startDocument();

        doRenderView(facesContext, viewToRender);

        newWriter.endDocument();

        // replace markers in the body content and write it to response.

        ResponseWriter responseWriter;
        if (null != oldWriter) {
            responseWriter = oldWriter.cloneWithWriter(response.getWriter());
        } else {
            responseWriter = newWriter.cloneWithWriter(response.getWriter());
        }
        facesContext.setResponseWriter(responseWriter);

        strWriter.flushToWriter(responseWriter);

        if (null != oldWriter) {
            facesContext.setResponseWriter(oldWriter);
        }

        // write any AFTER_VIEW_CONTENT to the response
        writeAfterViewContent(extContext, response);
    } else { // no tile, use default viewhandler
        if (logger.isLoggable(Level.WARNING)) //default was fine
            logger.log(Level.WARNING, "tiles.dispatchingToViewHandler");
        if (logger.isLoggable(Level.INFO)) { // default was finest
            logger.log(Level.FINEST,
                    "+=+=+=+=+=+= Printout for " + viewToRender.getViewId() + " about to render.");
            DebugUtil.printTree(viewToRender, logger, Level.INFO);
        }
        getWrapped().renderView(facesContext, viewToRender);
    }
}

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 {//from  www  .  ja  v  a 2 s.  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);
    }
}

From source file:org.commonfarm.web.ECSideFilter.java

public void doEncoding(ServletRequest request, ServletResponse response) throws IOException, ServletException {
    if (useEncoding || (request.getCharacterEncoding() == null)) {
        if (encoding != null) {
            // Set the same character encoding for the request and the
            // response
            request.setCharacterEncoding(encoding);
        } else {/*from   ww  w . jav a  2s . c om*/
            request.setCharacterEncoding(Constant.DEFAULT_ENCODING);
        }
    } else {
        request.setCharacterEncoding(Constant.DEFAULT_ENCODING);
    }
}

From source file:org.deegree.services.csw.CSWController.java

private void sendSoapException(SOAPEnvelope soapDoc, SOAPFactory factory, HttpResponseBuffer response,
        OWSException e, ServletRequest request, SOAPVersion version) throws OMException, ServletException {
    XMLExceptionSerializer serializer = getExceptionSerializer(parseVersion("1.2.0"));
    sendSOAPException(soapDoc.getHeader(), factory, response, e, serializer, null, null,
            request.getServerName(), request.getCharacterEncoding());
}

From source file:org.deegree.services.wfs.WebFeatureService.java

private void sendSoapException(SOAPEnvelope soapDoc, SOAPFactory factory, HttpResponseBuffer response,
        OWSException e, ServletRequest request, Version requestVersion) throws OMException, ServletException {
    XMLExceptionSerializer serializer = getExceptionSerializer(requestVersion);
    sendSOAPException(soapDoc.getHeader(), factory, response, e, serializer, null, null,
            request.getServerName(), request.getCharacterEncoding());
}

From source file:org.ecside.filter.ECSideFilter.java

 public void doEncoding(ServletRequest request, ServletResponse response)
      throws IOException, ServletException {
   if (useEncoding || (request.getCharacterEncoding() == null)) {
      if (encoding != null)
         // Set the same character encoding for the request and the
         // response
         request.setCharacterEncoding(encoding);
      // response.setCharacterEncoding(encoding);
   }/*from ww w  .  java 2s  .c om*/
}

From source file:org.nuxeo.ecm.platform.web.common.encoding.NuxeoEncodingFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (request != null) {
        // NXP-5555: set encoding to UTF-8 in case this method is called
        // before
        // encoding is set to UTF-8 on the request
        if (request.getCharacterEncoding() == null) {
            try {
                request.setCharacterEncoding("UTF-8");
            } catch (UnsupportedEncodingException e) {
                log.error(e, e);//from   w ww  .ja  v a2  s .  c  o  m
            }
        }

        RequestControllerManager rcm = Framework.getLocalService(RequestControllerManager.class);
        for (String headerName : rcm.getResponseHeaders().keySet()) {
            if (response instanceof HttpServletResponse
                    && !((HttpServletResponse) response).containsHeader(headerName)) {
                ((HttpServletResponse) response).addHeader(headerName,
                        rcm.getResponseHeaders().get(headerName));
            }
        }
    }

    chain.doFilter(request, response);
}

From source file:org.opencms.gwt.CmsGwtService.java

/**
 * @see javax.servlet.http.HttpServlet#service(javax.servlet.ServletRequest, javax.servlet.ServletResponse)
 *//*from  w ww  .j  av a 2s .com*/
@Override
public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {

    arg1.setCharacterEncoding(arg0.getCharacterEncoding());
    super.service(arg0, arg1);
}

From source file:org.soaplab.clients.spinet.filters.RequestDumperFilter.java

/**
 * Time the processing that is performed by all subsequent filters in the
 * current filter stack, including the ultimately invoked servlet.
 *
 * @param request The servlet request we are processing
 * @param result The servlet response we are creating
 * @param chain The filter chain we are processing
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 *///from   w  w w .  j  a  va 2 s  . co  m
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    if (filterConfig == null)
        return;

    // Render the generic servlet request properties
    StringWriter sw = new StringWriter();
    PrintWriter writer = new PrintWriter(sw);
    writer.println("Request Received at " + (new Timestamp(System.currentTimeMillis())));
    writer.println(" characterEncoding=" + request.getCharacterEncoding());
    writer.println("     contentLength=" + request.getContentLength());
    writer.println("       contentType=" + request.getContentType());
    writer.println("            locale=" + request.getLocale());
    writer.print("           locales=");
    Enumeration locales = request.getLocales();
    boolean first = true;
    while (locales.hasMoreElements()) {
        Locale locale = (Locale) locales.nextElement();
        if (first)
            first = false;
        else
            writer.print(", ");
        writer.print(locale.toString());
    }
    writer.println();
    Enumeration names = request.getParameterNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        writer.print("         parameter=" + name + "=");
        String values[] = request.getParameterValues(name);
        for (int i = 0; i < values.length; i++) {
            if (i > 0)
                writer.print(", ");
            writer.print(values[i]);
        }
        writer.println();
    }
    writer.println("          protocol=" + request.getProtocol());
    writer.println("        remoteAddr=" + request.getRemoteAddr());
    writer.println("        remoteHost=" + request.getRemoteHost());
    writer.println("            scheme=" + request.getScheme());
    writer.println("        serverName=" + request.getServerName());
    writer.println("        serverPort=" + request.getServerPort());
    writer.println("          isSecure=" + request.isSecure());

    // Render the HTTP servlet request properties
    if (request instanceof HttpServletRequest) {
        writer.println("---------------------------------------------");
        HttpServletRequest hrequest = (HttpServletRequest) request;
        writer.println("       contextPath=" + hrequest.getContextPath());
        Cookie cookies[] = hrequest.getCookies();
        if (cookies == null)
            cookies = new Cookie[0];
        for (int i = 0; i < cookies.length; i++) {
            writer.println("            cookie=" + cookies[i].getName() + "=" + cookies[i].getValue());
        }
        names = hrequest.getHeaderNames();
        while (names.hasMoreElements()) {
            String name = (String) names.nextElement();
            String value = hrequest.getHeader(name);
            writer.println("            header=" + name + "=" + value);
        }
        writer.println("            method=" + hrequest.getMethod());
        writer.println("          pathInfo=" + hrequest.getPathInfo());
        writer.println("       queryString=" + hrequest.getQueryString());
        writer.println("        remoteUser=" + hrequest.getRemoteUser());
        writer.println("requestedSessionId=" + hrequest.getRequestedSessionId());
        writer.println("        requestURI=" + hrequest.getRequestURI());
        writer.println("       servletPath=" + hrequest.getServletPath());
    }
    writer.println("=============================================");

    // Log the resulting string
    writer.flush();
    filterConfig.getServletContext().log(sw.getBuffer().toString());
    log.info(sw.getBuffer().toString());

    // Pass control on to the next filter
    chain.doFilter(request, response);

}