/* ======================================================================
   Parts Copyright 2006 University of Leeds, Oxford University, University of the Highlands and Islands.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

====================================================================== */

package org.bodington.servlet;

import java.io.*;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class EscapedHtmlWriter extends java.io.FilterWriter
{
    private static final Pattern escapeChars = Pattern.compile("[<>\"&]");
    
	public EscapedHtmlWriter(Writer out)
	{
		super(out);
	}

    /**
     * Write a single character replacing characters with HTML versions.
     * Currently &amp;, &gt;, &lt; and &quot; are escaped.
     * @param c The character to write.
     * */
    public void write(int c) throws IOException {
	try {
	    synchronized (lock) {
	        unsyncedWrite(c);
	    }
	}
	catch (InterruptedIOException x) {
	    Thread.currentThread().interrupt();
	}
    }

    /**
     * Write a character through to the underlying Writer, escaping it.
     * This should only be called from a synchronized section.
     * @param c The character to write
     */
    private void unsyncedWrite(int c) throws IOException
    {
        switch ( c )
			{
			case '&':
				out.write( '&' );
				out.write( 'a' );
				out.write( 'm' );
				out.write( 'p' );
				out.write( ';' );
				break;
			case '>':
				out.write( '&' );
				out.write( 'g' );
				out.write( 't' );
				out.write( ';' );
				break;
			case '<':
				out.write( '&' );
				out.write( 'l' );
				out.write( 't' );
				out.write( ';' );
				break;
			case '"':
			    out.write('&');
			    out.write('q');
			    out.write('u');
			    out.write('o');
			    out.write('t');
			    out.write(';');
				break;
			default:
				out.write(c);
			}
    }

    /** 
     * Write a portion of a string.
     */
    public void write(char input[], int off, int len) throws IOException
    {
        try
        {
            synchronized (lock)
            {
                String toWrite = new String (input, off, len);
                // if no difficult characters just pass it on....
                if (shouldEscape( toWrite ))
                {
                    // it's got at least one problem character to output one at
                    // a time
                    for (int i = 0; i < toWrite.length(); i++)
                        unsyncedWrite((int) toWrite.charAt(i));
                }
                else
                    out.write(toWrite, off, len);
            }

        }
        catch (InterruptedIOException x)
        {
            Thread.currentThread().interrupt();
        }
    }

    protected boolean shouldEscape( String toWrite )
    {
        return escapeChars.matcher(toWrite).find();
    }
    
    public void write(String input, int off, int len) throws IOException
    {
        write(input.toCharArray(),off,len);
    }
    
    public void write(char input[]) throws IOException
    {
        write(input, 0, input.length);
    }
 
    public void print(String string)
    {
            try
            {
                write(string);
                flush();
            }
            catch (IOException e)
            {}
    }
    
    /**
     * Utility method that escapes the passed HTML.
     * @param input The string to check and escape.
     * @return The escaped string.
     */
    public static String filter(String input)
    {
        StringWriter output = new StringWriter();
        new EscapedHtmlWriter(output).print(input);
        return output.toString();
    }

}
