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 /** 018 * An object that translates selected ASCII characters into equivalent strings. 019 * 020 * @author mb 021 * @since 4.0 022 */ 023 public class AsciiCharacterTranslator implements ICharacterTranslator 024 { 025 026 private String[] _charMap; 027 028 /** 029 * Creates and initializes a new translator that translates the provided 030 * ASCII characters into strings. All other characters will be translated to 031 * null. 032 * 033 * @param characterMap 034 * an array of pairs of strings. Each pair consists of a key that 035 * must be a single ASCII character, and a value that is its 036 * equivalent string. 037 */ 038 public AsciiCharacterTranslator(String[][] characterMap) 039 { 040 _charMap = new String[128]; 041 042 int pairCount = characterMap.length; 043 for(int i = 0; i < pairCount; i++) 044 { 045 String[] pair = characterMap[i]; 046 if (pair.length != 2) continue; 047 String key = pair[0]; 048 String value = pair[1]; 049 if (key.length() != 1) continue; 050 char ch = key.charAt(0); 051 if (ch >= 128) continue; 052 053 _charMap[ch] = value; 054 } 055 } 056 057 /** 058 * @see org.apache.tapestry.util.text.ICharacterTranslator#translate(char) . 059 */ 060 public String translate(char ch) 061 { 062 if (ch >= 128) return null; 063 return _charMap[ch]; 064 } 065 }