001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.dbutils;
018
019
020import java.beans.PropertyDescriptor;
021import java.sql.ResultSetMetaData;
022import java.sql.SQLException;
023import java.util.Arrays;
024
025
026/**
027 * Provides generous name matching (e.g. underscore-aware) from DB
028 * columns to Java Bean properties.
029 *
030 * @since 1.6
031 */
032public class GenerousBeanProcessor extends BeanProcessor {
033
034    /**
035     * Default constructor.
036     */
037    public GenerousBeanProcessor() {
038        super();
039    }
040
041    @Override
042    protected int[] mapColumnsToProperties(final ResultSetMetaData rsmd,
043            final PropertyDescriptor[] props) throws SQLException {
044
045        final int cols = rsmd.getColumnCount();
046        final int[] columnToProperty = new int[cols + 1];
047        Arrays.fill(columnToProperty, PROPERTY_NOT_FOUND);
048
049        for (int col = 1; col <= cols; col++) {
050            String columnName = rsmd.getColumnLabel(col);
051
052            if (null == columnName || 0 == columnName.length()) {
053                columnName = rsmd.getColumnName(col);
054            }
055
056            final String generousColumnName = columnName.replace("_", "");
057
058            for (int i = 0; i < props.length; i++) {
059                final String propName = props[i].getName();
060
061                // see if either the column name, or the generous one matches
062                if (columnName.equalsIgnoreCase(propName) ||
063                        generousColumnName.equalsIgnoreCase(propName)) {
064                    columnToProperty[col] = i;
065                    break;
066                }
067            }
068        }
069
070        return columnToProperty;
071    }
072
073}