001 /*
002 @license.text@
003 */
004 package biz.hammurapi.config;
005
006 import java.lang.reflect.Field;
007 import java.lang.reflect.InvocationTargetException;
008 import java.lang.reflect.Method;
009
010 import biz.hammurapi.convert.CompositeConverter;
011
012 /**
013 * Populates a bean with parameters from HttpRequest.
014 * @author Pavel Vlasov
015 *
016 * @version $Revision: 1.2 $
017 */
018 public class Bean2ContextConfigurableAdapter implements ContextConfigurable {
019 private Object bean;
020
021 public Bean2ContextConfigurableAdapter(Object bean) {
022 super();
023 this.bean=bean;
024 }
025
026 public void configure(Context context, CompositeConverter converter) throws ConfigurationException {
027 Method[] ma=bean.getClass().getMethods();
028 for (int i=0; i<ma.length; i++) {
029 String mname = ma[i].getName();
030 if (mname.startsWith("set") && mname.length()>=4 && ma[i].getParameterTypes().length==1 && ma[i].getReturnType().equals(void.class)) {
031 String pName = mname.length()==4 ? mname.toLowerCase().substring(3) : mname.substring(3, 4).toLowerCase() + mname.substring(4);
032 Object value=context.get(pName);
033 if (value!=null) {
034 try {
035 ma[i].invoke(bean, new Object[] {converter.convert(value, ma[i].getParameterTypes()[0], false)});
036 } catch (IllegalAccessException e) {
037 throw new ConfigurationException("Cannot invoke method "+ma[i]+" to set parameter value "+value, e);
038 } catch (InvocationTargetException e) {
039 throw new ConfigurationException("Cannot invoke method "+ma[i]+" to set parameter value "+value, e);
040 }
041 }
042 }
043 }
044
045 Field[] fa=bean.getClass().getFields();
046 for (int i=0; i<fa.length; i++) {
047 Object value=context.get(fa[i].getName());
048 if (value!=null) {
049 try {
050 fa[i].set(bean, converter.convert(value, fa[i].getType(), false));
051 } catch (IllegalAccessException e) {
052 throw new ConfigurationException("Cannot set field "+fa[i]+" to value "+value, e);
053 }
054 }
055 }
056 }
057 }