/*
 * Copyright (C) 2004 TiongHiang Lee
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not,  write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Email: thlee@onemindsoft.org
 */

package org.onemind.jxp.ant;

import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Map;
import java.util.logging.Logger;
import org.apache.tools.ant.Task;
import org.onemind.commons.java.lang.reflect.ReflectUtils;
public class AntTaskPropertiesSetter
{

    private static final Logger _logger = Logger.getLogger(AntTaskPropertiesSetter.class.getName());

    private AntTaskPropertiesSetter()
    {
    }

    public static void setTaskProperties(Task t, Map env)
    {
        Method[] methods = t.getClass().getMethods();
        String propName = null;
        try
        {
            HashSet doneProp = new HashSet();
            for (int i = 0; i < methods.length; i++)
            {
                String name = methods[i].getName();
                if (name.startsWith("set"))
                {
                    propName = name.substring(3);
                    propName = Character.toLowerCase(propName.charAt(0)) + propName.substring(1);
                    _logger.fine("Checking property " + propName + " of " + t);
                    if (!doneProp.contains(propName))
                    {
                        Object value = env.get(propName);
                        if (value != null)
                        {
                            _logger.fine("Setting property " + propName + " of " + t + " to " + value);
                            Object[] args = new Object[]{value};
                            Method m = ReflectUtils.getMethod(t.getClass(), name, args);
                            m.invoke(t, args);
                            doneProp.add(value);
                        }
                    }
                }
            }
        } catch (Exception e)
        {
            throw new RuntimeException("Cannot set property \"" + propName + "\": " + e.getMessage(), e);
        }
    }
}