Source code for /src/java/com/coolshare/springapp/web/ReflectDataBinder.java

// =====================================================================//
// Author: Mark Qian <markqian@hotmail.com>                             //
// WWW: http://www.coolshare.com/                                       //
// Copyright (c) 2006, Mark Qian                                        //
//                                                                      //
// You must contact Mark Qian to get a permission of use                //
// in case you want to make any use of the codes except viewing it     //
// on Mark's site.                                                      //
//======================================================================//
package com.coolshare.springapp.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletRequest;

import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyValues;
import org.springframework.validation.DataBinder;
import org.springframework.validation.Errors;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.ServletRequestParameterPropertyValues;
import org.springframework.web.bind.WebDataBinder;

import com.coolshare.springapp.Constant;

public class ReflectDataBinder {

	public ReflectDataBinder() {

	}

	/**
	 * This is a custom bind class. It parse ServletRequest for involved beans,
	 * instantiates them, bind data in parameters onto them and contains them in
	 * the return map.
	 * 
	 * @param request -
	 *            ServletRequest
	 * @return - a map that contains all the beans carried by ServletRequest
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws ClassNotFoundException
	 */
	public Map bind(ServletRequest request) throws InstantiationException,
			IllegalAccessException, ClassNotFoundException {
		Map res = new HashMap();

		Map pMap = request.getParameterMap();
		Map mpvsMap = new HashMap();

		for (Iterator iter = pMap.keySet().iterator(); iter.hasNext();) {
			String key = (String) iter.next();
			int i = key.indexOf(".");

			if (i < 0) {
				continue;
			}
			String bn = key.substring(0, i);
			MutablePropertyValues mpvs = (MutablePropertyValues) mpvsMap
					.get(bn);
			if (mpvs == null) {
				mpvs = new MutablePropertyValues();
				mpvsMap.put(bn, mpvs);
			}
			mpvs.addPropertyValue(key.substring(i + 1), pMap.get(key));
		}

		for (Iterator iterator = mpvsMap.keySet().iterator(); iterator
				.hasNext();) {
			String bn = (String) iterator.next();
			Object o = Class.forName(((TileInfo)Constant.BEAN_MAP.get(bn)).getModelClassName())
					.newInstance();
			res.put(bn, o);
			DataBinder binder = new DataBinder(o);
			binder.bind((PropertyValues) mpvsMap.get(bn));
		}

		return res;
	}

}