/*
* Copyright 2005-2006 the original author or authors.
*
* 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.strecks.injection.factory;
import java.beans.PropertyDescriptor;
import java.lang.annotation.Annotation;
import org.strecks.converter.Converter;
import org.strecks.exceptions.ApplicationConfigurationException;
import org.strecks.exceptions.ApplicationRuntimeException;
import org.strecks.injection.annotation.InjectRequestParameter;
import org.strecks.injection.handler.InjectionHandler;
import org.strecks.injection.handler.RequestParameterInjectionHandler;
import org.strecks.util.ReflectHelper;
/**
* Enables creation of <code>RequestParammeterInjectionHandler</code> for type converting and injecting named
* <code>HttpServletRequest</code> parameter
* @author Phil Zoio
*/
public class RequestParameterFactory implements InjectionHandlerFactory
{
public InjectionHandler createInjectionHandler(Annotation annotation, Class clazz, PropertyDescriptor propertyDescriptor)
{
InjectRequestParameter input = (InjectRequestParameter) annotation;
Class converterClass = input.converter();
Converter converter = RequestParameterFactory.createConverter(propertyDescriptor.getPropertyType(), converterClass);
String parameterName = AnnotationFactoryUtils.getAttributeName(propertyDescriptor.getName(), input.name());
boolean required = input.required();
// make sure that converter has String generic type
boolean ok = ReflectHelper.checkGenericType(converterClass, Converter.class, String.class);
if (!ok)
{
Class sourceType = ReflectHelper.getGenericType(converterClass, Converter.class);
throw new ApplicationConfigurationException("@" + input.annotationType().getSimpleName() + " in "
+ clazz.getName() + " uses converter " + converterClass.getName()
+ " whose conversion source type is " + sourceType.getName() + ", and not "
+ String.class.getName());
}
InjectionHandler handler = new RequestParameterInjectionHandler(parameterName, converter, required);
return handler;
}
/**
* Creates a converter
*/
public static Converter createConverter(Class propertyType, Class converterClass)
{
Converter converter;
try
{
Object newInstance = converterClass.newInstance();
converter = (Converter) newInstance;
converter.setTargetClass(propertyType);
}
catch (Exception e)
{
throw new ApplicationRuntimeException("Could not instantiate class " + converterClass.getName(), e);
}
return converter;
}
}