/** 
 * 
 * Copyright 2004 Protique Ltd
 * 
 * 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.codehaus.activemq.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.lang.reflect.Method;
import java.util.Map;

/**
 * Some bean utility methods
 *
 * @version $Revision: 1.1 $
 */
public class BeanUtils {
    private static final Log log = LogFactory.getLog(BeanUtils.class);

    protected static final String NAME = "org.apache.commons.beanutils.BeanUtils";
    protected static final Class[] PARAMETER_TYPES = new Class[]{Object.class, Map.class};

    public static void populate(Object bean, Map properties) {
        // use reflection to avoid runtime dependnecy if this method is never called
        Class beanUtils = null;
        try {
            beanUtils = Thread.currentThread().getContextClassLoader().loadClass(NAME);
        }
        catch (ClassNotFoundException e) {
            try {
                beanUtils = BeanUtils.class.getClassLoader().loadClass(NAME);
            }
            catch (ClassNotFoundException e1) {
                log.trace("Cannot find: " + NAME + ". Reason: " + e, e);
            }
        }
        if (beanUtils == null) {
            log.warn("Could not find class: " + NAME + " so cannot configure bean using introspection: " + bean);
        }
        else {
            Method method = null;
            try {
                method = beanUtils.getMethod("populate", PARAMETER_TYPES);
            }
            catch (NoSuchMethodException e) {
                log.trace("Could not find populate", e);
            }
            if (method == null) {
                log.warn("Could not find populate() method so cannot configure bean using introspection: " + bean);
            }
            else {
                try {
                    method.invoke(null, new Object[]{bean, properties});
                }
                catch (Exception e) {
                    log.warn("Could not populate the bean via introspection: " + bean + ". Reason: " + e, e);
                }
            }
        }
    }
}
