View Javadoc

1   /*
2    * Copyright 2002-2006 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.gageot.excel.beans;
18  
19  import java.beans.PropertyDescriptor;
20  import java.text.NumberFormat;
21  
22  import org.springframework.beans.BeanWrapper;
23  import org.springframework.beans.BeanWrapperImpl;
24  import org.springframework.beans.BeansException;
25  import org.springframework.beans.propertyeditors.CustomNumberEditor;
26  
27  /***
28   * Simple BeanSetter implementation based on BeanWrapperImpl Spring class.
29   *
30   * @author David Gageot
31   * @see BeanCellCallbackHandler
32   * @see ExcelTemplate#read(String,CellCallbackHandler)
33   */
34  public class BeanSetterImpl implements BeanSetter {
35  	private BeanWrapper currentWrapper;
36  	private Object currentBean;
37  	
38  	public BeanSetterImpl() {
39  	}
40  	
41  	protected BeanWrapper getWrapper (Object bean) {
42  		if (bean != currentBean) {
43  			currentBean = bean;
44  			currentWrapper = new BeanWrapperImpl (true);
45  			currentWrapper.setWrappedInstance (currentBean);
46  			
47  			// To make sure that Double values can be converted into an int.
48  			//
49  			currentWrapper.registerCustomEditor (int.class,
50  					new CustomNumberEditor (Integer.class, NumberFormat.getInstance(), false));
51  		}
52  		
53  		return currentWrapper;
54  	}
55  	
56  	/***
57  	 * Set the value of a property on the current bean.
58  	 * 
59  	 * @param bean bean instance to populate
60  	 * @param propertyName the name of the property (case insensitive)
61  	 * @param propertyValue the value of the property
62  	 */
63  	public void setProperty (Object bean, String propertyName, Object propertyValue) throws BeansException {
64  		BeanWrapper wrapper = getWrapper (bean);
65  
66  		PropertyDescriptor[] propertyDescriptors = wrapper.getPropertyDescriptors();
67  
68  		// Find a bean property by its name ignoring case.
69  		// this way, we can accept any type of case in the spreadsheet file
70  		//
71  		for (int i = 0; i < propertyDescriptors.length; i++) {
72  			if (propertyDescriptors[i].getName().equalsIgnoreCase (propertyName)) {
73  				wrapper.setPropertyValue (propertyDescriptors[i].getName(), propertyValue.toString());
74  				break;
75  			}
76  		}
77  	}
78  }