001 // Copyright 2004, 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.util.text;
016
017 import java.util.HashMap;
018 import java.util.Map;
019
020 /**
021 * The default implementation of a character translator source.
022 * Returns a standard HTML translator that encodes everything that is non-safe
023 * or an HTML translator that encodes only non-safe ASCII symbols
024 * if the encoding is a unicode one.
025 *
026 * @author mb
027 * @since 4.0
028 */
029 public class DefaultCharacterTranslatorSource implements ICharacterTranslatorSource
030 {
031 private static final ICharacterTranslator DEFAULT_TRANSLATOR = new MarkupCharacterTranslator();
032 private static final ICharacterTranslator UNICODE_TRANSLATOR = new MarkupCharacterTranslator(false);
033
034 private final static Map _translators;
035
036 static {
037 _translators = new HashMap();
038 _translators.put("UTF-8", UNICODE_TRANSLATOR);
039 _translators.put("UTF-7", UNICODE_TRANSLATOR);
040 _translators.put("UTF-16", UNICODE_TRANSLATOR);
041 _translators.put("UTF-16BE", UNICODE_TRANSLATOR);
042 _translators.put("UTF-16LE", UNICODE_TRANSLATOR);
043 }
044
045 /**
046 * Returns a translator that encodes all non-safe characters into their HTML equivalents.
047 *
048 * @see org.apache.tapestry.util.text.ICharacterTranslatorSource#getDefaultTranslator()
049 */
050 public ICharacterTranslator getDefaultTranslator() {
051 return DEFAULT_TRANSLATOR;
052 }
053
054 /**
055 * If the encoding is a Unicode one, returns a translator that encodes only the
056 * non-safe ASCII characters and leaves the others untouched.
057 * Otherwise, returns the default translator.
058 *
059 * @see org.apache.tapestry.util.text.ICharacterTranslatorSource#getTranslator(java.lang.String)
060 */
061 public ICharacterTranslator getTranslator(String encoding) {
062 ICharacterTranslator translator = (ICharacterTranslator) _translators.get(encoding.toUpperCase());
063 if (translator != null)
064 return translator;
065 return getDefaultTranslator();
066 }
067
068 }