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.wml;
016    
017    import org.apache.tapestry.util.text.AsciiCharacterMatcher;
018    import org.apache.tapestry.util.text.AsciiCharacterTranslator;
019    import org.apache.tapestry.util.text.ICharacterMatcher;
020    import org.apache.tapestry.util.text.ICharacterTranslator;
021    import org.apache.tapestry.util.text.ICharacterTranslatorSource;
022    import org.apache.tapestry.util.text.MarkupCharacterTranslator;
023    
024    /**
025     * The WML implementation of a character translator source. Returns a WML
026     * translator that encodes everything that is non-safe. Some code borrowed from
027     * WMLWriter (by David Solis)
028     * 
029     * @author mb
030     * @since 4.0
031     */
032    public class WMLCharacterTranslatorSource implements ICharacterTranslatorSource
033    {
034    
035        private static final String SAFE_CHARACTERS = "01234567890"
036                + "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
037                + "\t\n\r !\"#%'()*+,-./:;=?@[\\]^_`{|}~";
038    
039        private static final String[][] ENTITIES = { { "\"", """ },
040                { "<", "&lt;" }, { ">", "&gt;" }, { "&", "&amp;" }, { "$", "$$" } };
041    
042        private static final ICharacterMatcher SAFE_MATCHER = new AsciiCharacterMatcher(
043                SAFE_CHARACTERS);
044        private static final ICharacterTranslator ENTITY_TRANSLATOR = new AsciiCharacterTranslator(
045                ENTITIES);
046    
047        private static final ICharacterTranslator WML_TRANSLATOR = new MarkupCharacterTranslator(
048                true, SAFE_MATCHER, ENTITY_TRANSLATOR);
049    
050        /**
051         * @see org.apache.tapestry.util.text.ICharacterTranslatorSource#getDefaultTranslator()
052         */
053        public ICharacterTranslator getDefaultTranslator()
054        {
055            return WML_TRANSLATOR;
056        }
057    
058        /**
059         * @see org.apache.tapestry.util.text.ICharacterTranslatorSource#getTranslator(java.lang.String)
060         */
061        public ICharacterTranslator getTranslator(String encoding)
062        {
063            return getDefaultTranslator();
064        }
065    }