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