001/*
002 * (C) Copyright 2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Anahide Tchertchian
018 */
019package org.nuxeo.ecm.platform.web.common.encoding;
020
021import java.io.IOException;
022import java.io.UnsupportedEncodingException;
023
024import javax.servlet.Filter;
025import javax.servlet.FilterChain;
026import javax.servlet.FilterConfig;
027import javax.servlet.ServletException;
028import javax.servlet.ServletRequest;
029import javax.servlet.ServletResponse;
030
031import org.apache.commons.logging.Log;
032import org.apache.commons.logging.LogFactory;
033
034/**
035 * Filter that sets encoding to UTF-8, before any other filter tries to parse the request. Also set the X-UA-Compatible
036 * meta for browsers.
037 * <p>
038 * See NXP-5555: the first parsing of the request is cached, so it should be done with the right encoding. See
039 * NXP-12862: we must pass the X-UA-Compatible meta in the header.
040 *
041 * @author Anahide Tchertchian
042 * @since 5.4.2
043 */
044public class NuxeoEncodingFilter implements Filter {
045
046    private static final Log log = LogFactory.getLog(NuxeoEncodingFilter.class);
047
048    @Override
049    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
050            ServletException {
051        if (request != null) {
052            // NXP-5555: set encoding to UTF-8 in case this method is called
053            // before
054            // encoding is set to UTF-8 on the request
055            if (request.getCharacterEncoding() == null) {
056                try {
057                    request.setCharacterEncoding("UTF-8");
058                } catch (UnsupportedEncodingException e) {
059                    log.error(e, e);
060                }
061            }
062        }
063
064        chain.doFilter(request, response);
065    }
066
067    @Override
068    public void destroy() {
069    }
070
071    @Override
072    public void init(FilterConfig filterConfig) throws ServletException {
073    }
074
075}