001 // Copyright 2005 The Apache Software Foundation 002 // 003 // Licensed under the Apache License, Version 2.0 (the "License"); 004 // you may not use this file except in compliance with the License. 005 // You may obtain a copy of the License at 006 // 007 // http://www.apache.org/licenses/LICENSE-2.0 008 // 009 // Unless required by applicable law or agreed to in writing, software 010 // distributed under the License is distributed on an "AS IS" BASIS, 011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 012 // See the License for the specific language governing permissions and 013 // limitations under the License. 014 015 package org.apache.tapestry.services.impl; 016 017 import java.io.IOException; 018 import java.io.UnsupportedEncodingException; 019 020 import javax.servlet.ServletException; 021 import javax.servlet.http.HttpServletRequest; 022 import javax.servlet.http.HttpServletResponse; 023 024 import org.apache.hivemind.ApplicationRuntimeException; 025 import org.apache.tapestry.services.ServletRequestServicer; 026 import org.apache.tapestry.services.ServletRequestServicerFilter; 027 028 /** 029 * Analyzes the incoming request to set the correct output encoding. 030 * 031 * @author Howard M. Lewis Ship 032 * @since 4.0 033 */ 034 public class SetupRequestEncoding implements ServletRequestServicerFilter 035 { 036 private boolean _skipSet; 037 038 private String _outputEncoding; 039 040 public void service(HttpServletRequest request, HttpServletResponse response, 041 ServletRequestServicer servicer) throws IOException, ServletException 042 { 043 if (!_skipSet) 044 { 045 String encoding = request.getCharacterEncoding(); 046 047 if (encoding == null) 048 setRequestEncodingToOutputEncoding(request); 049 } 050 051 // Next in chain 052 053 servicer.service(request, response); 054 } 055 056 private void setRequestEncodingToOutputEncoding(HttpServletRequest request) 057 { 058 try 059 { 060 // We compile against the 2.3 API but allow 061 // the code to execute against the 2.2 In the 062 // later case, we can get some interesting errors. 063 064 request.setCharacterEncoding(_outputEncoding); 065 } 066 catch (UnsupportedEncodingException ex) 067 { 068 throw new ApplicationRuntimeException( 069 ImplMessages.invalidEncoding(_outputEncoding, ex), ex); 070 } 071 catch (NoSuchMethodError ex) 072 { 073 _skipSet = true; 074 } 075 catch (AbstractMethodError ex) 076 { 077 _skipSet = true; 078 } 079 } 080 081 public void setOutputEncoding(String outputEncoding) 082 { 083 _outputEncoding = outputEncoding; 084 } 085 }