001package au.com.bytecode.opencsv.bean; 002import java.beans.BeanInfo; 003import java.beans.IntrospectionException; 004import java.beans.Introspector; 005import java.beans.PropertyDescriptor; 006import java.io.IOException; 007 008import au.com.bytecode.opencsv.CSVReader; 009 010/** 011 Copyright 2007 Kyle Miller. 012 013 Licensed under the Apache License, Version 2.0 (the "License"); 014 you may not use this file except in compliance with the License. 015 You may obtain a copy of the License at 016 017 http://www.apache.org/licenses/LICENSE-2.0 018 019 Unless required by applicable law or agreed to in writing, software 020 distributed under the License is distributed on an "AS IS" BASIS, 021 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 022 See the License for the specific language governing permissions and 023 limitations under the License. 024 */ 025 026public class HeaderColumnNameMappingStrategy implements MappingStrategy { 027 protected String[] header; 028 protected PropertyDescriptor[] descriptors; 029 protected Class type; 030 031 public void captureHeader(CSVReader reader) throws IOException { 032 header = reader.readNext(); 033 } 034 035 public PropertyDescriptor findDescriptor(int col) throws IntrospectionException { 036 String columnName = getColumnName(col); 037 return (null != columnName && columnName.trim().length()>0) ? findDescriptor(columnName) : null; 038 } 039 040 protected String getColumnName(int col) { 041 return (null != header && col < header.length) ? header[col] : null; 042 } 043 protected PropertyDescriptor findDescriptor(String name) throws IntrospectionException { 044 if (null == descriptors) descriptors = loadDescriptors(getType()); //lazy load descriptors 045 for (int i = 0; i < descriptors.length; i++) { 046 PropertyDescriptor desc = descriptors[i]; 047 if (matches(name, desc)) return desc; // TODO: (Kyle) do null/blank check 048 } 049 return null; 050 } 051 protected boolean matches(String name, PropertyDescriptor desc) { 052 return desc.getName().equals(name); 053 } 054 protected PropertyDescriptor[] loadDescriptors(Class cls) throws IntrospectionException { 055 BeanInfo beanInfo = Introspector.getBeanInfo(cls); 056 return beanInfo.getPropertyDescriptors(); 057 } 058 public Object createBean() throws InstantiationException, IllegalAccessException { 059 return type.newInstance(); 060 } 061 public Class getType() { 062 return type; 063 } 064 065 public void setType(Class type) { 066 this.type = type; 067 } 068}