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
015package org.apache.tapestry.markup;
016
017import java.io.PrintWriter;
018
019import org.apache.tapestry.util.text.ICharacterTranslator;
020
021/**
022 * For the meantime, implemenatations of {@link org.apache.tapestry.markup.MarkupFilter} are
023 * wrappers around {@link org.apache.tapestry.util.text.ICharacterTranslator}. This class provides
024 * handy methods for doing the grunt work.
025 * 
026 * @author Howard M. Lewis Ship
027 * @since 4.0
028 */
029public class MarkupFilterUtils
030{
031    public static void print(PrintWriter writer, char[] data, int offset, int length,
032            boolean escapeQuotes, ICharacterTranslator translator)
033    {
034        StringBuffer buffer = new StringBuffer(length);
035
036        for (int i = 0; i < length; i++)
037        {
038            char ch = data[offset + i];
039
040            if (ch == '"' && !escapeQuotes)
041            {
042                buffer.append(ch);
043                continue;
044            }
045
046            String translated = translator.translate(ch);
047
048            if (translated == null)
049            {
050                buffer.append(ch);
051                continue;
052            }
053
054            buffer.append(translated);
055        }
056
057        // We'll have to see if building up a buffer and then printing it in one go is the
058        // most efficient route. It's hard to predict what will give the best performance,
059        // but there's almost certainly a buffered writer between this code and the
060        // character set encoder.
061
062        writer.print(buffer.toString());
063    }
064}