/*
 * $Id: BeanAnnotLocatorFactory.java,v 1.1 2005/11/11 08:39:51 ivaynberg Exp $
 * $Revision: 1.1 $
 * $Date: 2005/11/11 08:39:51 $
 * 
 * ==============================================================================
 * 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 wicket.contrib.spring.injection;

import java.lang.reflect.Field;

import org.apache.commons.attributes.Attributes;
import org.apache.commons.attributes.MultipleAttributesError;

import wicket.contrib.proxy.IObjectLocator;
import wicket.contrib.proxy.IObjectLocatorFactory;

/**
 * Factory that produces object locators for fields marked with a SpringBean4. It uses apache commons attributes
 * instead of JDK5 attributes. So that the injection can also be used with JDK1.4
 * annotation.
 * 
 * @see SpringBean
 * @see BeanLocator
 * 
 * @author Christian Essl
 * 
 */
public class CommonsAttributesBeanLocatorFactory implements IObjectLocatorFactory
{
	private ISpringContextLocator locator;

	/**
	 * @param locator
	 *            spring context locator
	 */
	public CommonsAttributesBeanLocatorFactory(ISpringContextLocator locator)
	{
		if (locator == null)
		{
			throw new IllegalArgumentException("[locator] argument cannot be null");
		}
		this.locator = locator;
	}

	/**
	 * @see wicket.contrib.proxy.IObjectLocatorFactory#createLocator(java.lang.Object,
	 *      java.lang.reflect.Field)
	 */
	public IObjectLocator createLocator(Object fieldOwner, Field field)
	{
		if(Attributes.hasAttributeType(field, SpringBean4.class)){
			try{
				SpringBean4 attribute = (SpringBean4) Attributes.getAttribute(field, SpringBean4.class);
				return new BeanLocator(attribute.getBeanName(),field.getType(),locator);
			}catch(MultipleAttributesError e){
				throw new IllegalStateException("There is more than one SpringBean4 attribute defined on the field: "+field.toString());
			}
		}else{
			return null;
		}
		
	}

}
