1   package com.atlassian.core.filters.encoding;
2   
3   import org.apache.commons.lang.StringUtils;
4   
5   import javax.servlet.http.HttpServletResponse;
6   import javax.servlet.http.HttpServletResponseWrapper;
7   
8   /**
9    * Prevents the encoding of the response being changed with {@link #setContentType(String)}. If
10   * that method is called with "text/html; charset=...", it ignores the change.
11   * <p/>
12   * This is meant to ensure that the encoding of the response can't be changed after an encoding
13   * filter sets it.
14   *
15   * @see AbstractEncodingFilter
16   * @since 4.0
17   */
18  public final class FixedHtmlEncodingResponseWrapper extends HttpServletResponseWrapper
19  {
20      public FixedHtmlEncodingResponseWrapper(HttpServletResponse response)
21      {
22          super(response);
23      }
24  
25      public final void setContentType(String contentType)
26      {
27          // If something tries to change the content type of the response by setting a content type of
28          // "text/html; charset=...", just ignore it. This happens in Tomcat and Jetty JSPs.
29          if (StringUtils.startsWith(contentType, "text/html") && contentType.length() > "text/html".length())
30          {
31              return;
32          }
33  
34          // Ensure that the charset parameter is appended if we're called with just "text/html".
35          // This happens on WebLogic.
36          if (StringUtils.trimToEmpty(contentType).equals("text/html"))
37          {
38              super.setContentType(contentType + ";charset=" + getResponse().getCharacterEncoding());
39              return;
40          }
41  
42          // for all other content types, just set the value
43          super.setContentType(contentType);
44      }
45  }