package org.displaytag.util;

import java.lang.reflect.Method;
import java.net.URLEncoder;


/**
 * @author Fabrizio Giustina
 * @version $Revision$ ($Author$)
 */
public class CompatibleUrlEncoder
{

    /**
     * j2se 1.4 encode method, used by reflection if available.
     */
    private static Method encodeMethod14;

    static
    {
        // URLEncoder.encode(String) has been deprecated in J2SE 1.4.
        // Take advantage of the new method URLEncoder.encode(String, enc) if J2SE 1.4 is used.
        try
        {
            Class urlEncoderClass = Class.forName("java.net.URLEncoder");
            encodeMethod14 = urlEncoderClass.getMethod("encode", new Class[]{String.class, String.class});
        }
        catch (Throwable ex)
        {
            // encodeMethod14 will be null if exception
        }
    }

    /**
     * Called encodeUrl using j2se 1.4 version by reflection if available, or backward compatible version.
     * @param url url to be encoded
     * @return encoded url.
     */
    public static String encode(String url, String encoding)
    {
        if (encodeMethod14 != null)
        {
            Object[] methodArgs = new Object[2];
            methodArgs[0] = url;
            methodArgs[1] = encoding;

            try
            {
                return (String) encodeMethod14.invoke(null, methodArgs);
            }
            catch (Exception ex)
            {
                throw new RuntimeException("System error invoking URLEncoder.encode() by reflection.", ex);
            }
        }
        else
        {
            // must use J2SE 1.3 version
            return URLEncoder.encode(url);
        }
    }

}

@@ -164,16 +164,22 @@
 %0Apublic 
+final 
 class Co
@@ -323,16 +323,124 @@
 hod14;%0A%0A
+    /**%0A     * don't instantiate.%0A     */%0A    private CompatibleUrlEncoder()%0A    %7B%0A        // unused%0A    %7D%0A%0A
     stat
@@ -1090,16 +1090,67 @@
 encoded%0A
+     * @param encoding encoding to use for jse 1.4%0A
      * @
@@ -1376,45 +1376,197 @@
 rl;%0A
-            methodArgs%5B1%5D = encoding;
+%0A            if (encoding != null)%0A            %7B%0A                methodArgs%5B1%5D = encoding;%0A            %7D%0A            else%0A            %7B%0A                methodArgs%5B1%5D = %22UTF8%22;%0A            %7D
 %0A%0A  
@@ -1830,39 +1830,95 @@
 tion
-.%22, ex);%0A            %7D%0A
+ with encoding %5B%22%0A                    + encoding%0A                    + %22%5D. %22%0A  
         
 %7D%0A  
@@ -1913,26 +1913,26 @@
         
-%7D%0A
+  
         
 else%0A   
@@ -1915,36 +1915,55 @@
                 
-else
++ ex.getMessage(), ex);
 %0A        %7B%0A     
@@ -1955,30 +1955,41 @@
         
-%7B
+    %7D
 %0A     
+   %7D%0A%0A
        
+ 
 // must 
@@ -2005,28 +2005,24 @@
 1.3 version%0A
-    
         retu
@@ -2048,25 +2048,16 @@
 e(url);%0A
-        %7D
 %0A    %7D%0A%0A

fix for encoding== null (should not happen, but seems to be null in httpunit tests if not explicitely set)