View Javadoc

1   package liquibase.util.csv.opencsv.bean;
2   
3   import liquibase.util.csv.opencsv.CSVReader;
4   
5   import java.beans.BeanInfo;
6   import java.beans.IntrospectionException;
7   import java.beans.Introspector;
8   import java.beans.PropertyDescriptor;
9   import java.io.IOException;
10  
11  /**
12   * Copyright 2007 Kyle Miller.
13   * 
14   * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
15   * the License. You may obtain a copy of the License at
16   * 
17   * http://www.apache.org/licenses/LICENSE-2.0
18   * 
19   * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
20   * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
21   * specific language governing permissions and limitations under the License.
22   */
23  
24  public class HeaderColumnNameMappingStrategy implements MappingStrategy {
25      protected String[] header;
26      protected PropertyDescriptor[] descriptors;
27      protected Class type;
28  
29      public void captureHeader(CSVReader reader) throws IOException {
30          header = reader.readNext();
31      }
32  
33      public PropertyDescriptor findDescriptor(int col) throws IntrospectionException {
34          String columnName = getColumnName(col);
35          return (null != columnName && columnName.trim().length() > 0) ? findDescriptor(columnName) : null;
36      }
37  
38      protected String getColumnName(int col) {
39          return (null != header && col < header.length) ? header[col] : null;
40      }
41  
42      protected PropertyDescriptor findDescriptor(String name) throws IntrospectionException {
43          if (null == descriptors)
44              descriptors = loadDescriptors(getType()); // lazy load descriptors
45          for (int i = 0; i < descriptors.length; i++) {
46              PropertyDescriptor desc = descriptors[i];
47              if (matches(name, desc))
48                  return desc;
49          }
50          return null;
51      }
52  
53      protected boolean matches(String name, PropertyDescriptor desc) {
54          return desc.getName().equals(name);
55      }
56  
57      protected PropertyDescriptor[] loadDescriptors(Class cls) throws IntrospectionException {
58          BeanInfo beanInfo = Introspector.getBeanInfo(cls);
59          return beanInfo.getPropertyDescriptors();
60      }
61  
62      public Object createBean() throws InstantiationException, IllegalAccessException {
63          return type.newInstance();
64      }
65  
66      public Class getType() {
67          return type;
68      }
69  
70      public void setType(Class type) {
71          this.type = type;
72      }
73  }