/*
 * $Revision: 223 $ $Date: 2007-10-14 17:07:40 +0900 $
 * Copyright (C) 2005 SUGIMOTO Ken-ichi
 */

package feat2.xmlcommand;

import java.lang.reflect.InvocationTargetException;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.beanutils.ConvertUtils;

public class Utils {

    public static String urlDecode(String str, String enc) {
        String ret = str;
        try {
            byte[] b = str.getBytes("ISO8859_1");
            int w = 0, r = 0;
            while(r<b.length) {
                if ( b[r] == 0x25 ) {
                    String digit = new String(new byte[] {b[r+1], b[r+2]}, "ISO8859_1");
                    b[w++] = (byte)(Integer.parseInt(digit, 16) & 0xff);
                    r += 3;
                } else {
                    b[w++] = b[r++];
                }
            }
            ret = new String(b, 0, w, enc);
        }
        catch(Exception ex) {}
        return ret;
    }

    /**
     * 例外から根本原因の例外を取り出す。
     * @param t Throwable
     * @return Throwable
     */
    public static Throwable getRootCause(Throwable t) {
        while(t.getCause() != null) {
            t = t.getCause();
        }
        return t;
    }

    public static void setProperty(Object bean, String name, Object value) throws
            IllegalAccessException, NoSuchMethodException,
            InvocationTargetException, IllegalAccessException {
        PropertyUtils.setProperty(bean, name, value);
    }

    /**
     * 文字列をプロパティの型に変換してからbeanにセットする。
     * @param bean Object
     * @param name String
     * @param value String
     */
    public static void setPropertyString(Object bean, String name, String value) throws
            IllegalAccessException, NoSuchMethodException,
            InvocationTargetException, IllegalAccessException {
        Class type = getPropertyType(bean, name);
        PropertyUtils.setProperty(bean, name, ConvertUtils.convert(value, type));
    }

    public static Object getProperty(Object bean, String name) throws
            NoSuchMethodException, InvocationTargetException,
            IllegalAccessException {
        return PropertyUtils.getProperty(bean, name);
    }

    public static Class getPropertyType(Object bean, String name) throws
            NoSuchMethodException, InvocationTargetException,
            IllegalAccessException {
        return PropertyUtils.getPropertyType(bean, name);
    }


}
