/* ======================================================================
The Bodington System Software License, Version 1.0
  
Copyright (c) 2001 The University of Leeds.  All rights reserved.
  
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

1.  Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.

2.  Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

3.  The end-user documentation included with the redistribution, if any,
must include the following acknowledgement:  "This product includes
software developed by the University of Leeds
(http://www.bodington.org/)."  Alternately, this acknowledgement may
appear in the software itself, if and wherever such third-party
acknowledgements normally appear.

4.  The names "Bodington", "Nathan Bodington", "Bodington System",
"Bodington Open Source Project", and "The University of Leeds" must not be
used to endorse or promote products derived from this software without
prior written permission. For written permission, please contact
d.gardner@leeds.ac.uk.

5.  The name "Bodington" may not appear in the name of products derived
from this software without prior written permission of the University of
Leeds.

THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO,  TITLE,  THE IMPLIED WARRANTIES 
OF QUALITY  AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO 
EVENT SHALL THE UNIVERSITY OF LEEDS OR ITS CONTRIBUTORS BE LIABLE FOR 
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE 
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
=========================================================

This software was originally created by the University of Leeds and may contain voluntary 
contributions from others.  For more information on the Bodington Open Source Project, please 
see http://bodington.org/

====================================================================== */
package org.bodington.util;

import java.io.UnsupportedEncodingException;

public class URLDecoder
{
    
    /**
     * Decodes a &quot;x-www-form-urlencoded&quot;
     * to a <tt>String</tt>.
     * @param s the <code>String</code> to decode
     * @return the newly decoded <code>String</code>
     */
    public static String decode( String s, String encoding )
    throws UnsupportedEncodingException
    {
	if ( "bodington_underscore".equalsIgnoreCase( encoding ) )
	    return decodeFromBodURL_2_1( s );
	if ( "bodington_escape".equalsIgnoreCase( encoding ) )
	    return decodeFromBodURL_2_0( s );
	return java.net.URLDecoder.decode( s, encoding );
    }
    
    
    private static String decodeFromBodURL_2_1( String url )
    {
	try
	{
	    // URLDecode then find four digit hexadecimal coded
	    // UTF16 characters escaped by 0x1b
	    String utf16escaped = URLDecoder.decode( url, "US-ASCII" );
	    
	    // if it doesn't have underscore at start then it's a normal
	    // url.
	    
	    if ( !utf16escaped.startsWith( "_" ) )
		return utf16escaped;
	    
	    StringBuffer name = new StringBuffer( utf16escaped.length() );
	    int c, i, j;
	    String hex;
	    
	    // Find four digit hexadecimal coded
	    // UTF16 characters escaped by underscore
	    for ( i=1; i< utf16escaped.length(); i++ )
	    {
		c=utf16escaped.charAt( i );
		
		if ( c == '_' )
		{
		    // followed immediately by another underscore this is an
		    // escaped underscore.
		    if ( (i+1) < utf16escaped.length() && utf16escaped.charAt( i+1 ) == '_' )
		    {
			name.append( "_" );
			i++;
		    }
		    // otherwise it is an escaped 16 bit character
		    else
		    {
			//find first invalid digit, up to four digits
			for ( j=0; j<4 && (i+j+1)<utf16escaped.length(); j++ )
			{
			    c = utf16escaped.charAt( i+j+1 );
			    if ( c<'0' || (c>'9' && c<'A') || (c>'F' && c<'a') || c>'f' )
				break;
			}
			
			hex = utf16escaped.substring( i+1, i+j+1 );
			// guaranteed to be a valid number now
			if ( hex.length()>0 )
			{
			    try
			    {
				c = Integer.parseInt( hex, 16 );
			    }
			    catch ( NumberFormatException nfex )
			    {
				c = '?';  //should never happen!
			    }
			    name.append( (char)c );
			}
			i+=j;
		    }
		}
		else
		    name.append( (char)c );
	    }
	    
	    return name.toString();
	}
	catch ( UnsupportedEncodingException e )
	{
	    // can never happen with US_ASCII?
	    return null;
	}
    }
    
    
    private static String decodeFromBodURL_2_0( String url )
    {
	try
	{
	    // URLDecode then find four digit hexadecimal coded
	    // UTF16 characters escaped by 0x1b
	    String utf16escaped = URLDecoder.decode( url, "US-ASCII" );
	    StringBuffer name = new StringBuffer( utf16escaped.length() );
	    int c, i, j;
	    String hex;
	    
	    for ( i=0; i< utf16escaped.length(); i++ )
	    {
		c=utf16escaped.charAt( i );
		
		if ( c == 0x1b )
		{
		    //find first invalid digit, up to four digits
		    for ( j=0; j<4 && (i+j+1)<utf16escaped.length(); j++ )
		    {
			c = utf16escaped.charAt( i+j+1 );
			if ( c<'0' || (c>'9' && c<'A') || (c>'F' && c<'a') || c>'f' )
			    break;
		    }
		    
		    hex = utf16escaped.substring( i+1, i+j+1 );
		    // guaranteed to be a valid number now
		    if ( hex.length()>0 )
		    {
			try
			{
			    c = Integer.parseInt( hex, 16 );
			}
			catch ( NumberFormatException nfex )
			{
			    c = '?';  //should never happen!
			}
			name.append( (char)c );
		    }
		    i+=j;
		}
		else
		    name.append( (char)c );
	    }
	    
	    return name.toString();
	}
	catch ( UnsupportedEncodingException e )
	{
	    // can never happen with US_ASCII?
	    return null;
	}
    }
    
}
