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    }
039
040    @Override
041    protected int[] mapColumnsToProperties(final ResultSetMetaData rsmd,
042            final PropertyDescriptor[] props) throws SQLException {
043
044        final int cols = rsmd.getColumnCount();
045        final int[] columnToProperty = new int[cols + 1];
046        Arrays.fill(columnToProperty, PROPERTY_NOT_FOUND);
047
048        for (int col = 1; col <= cols; col++) {
049            String columnName = rsmd.getColumnLabel(col);
050
051            if (null == columnName || 0 == columnName.length()) {
052                columnName = rsmd.getColumnName(col);
053            }
054
055            final String generousColumnName = columnName
056                    .replace("_", "")   // more idiomatic to Java
057                    .replace(" ", "");  // can't have spaces in property names
058
059            for (int i = 0; i < props.length; i++) {
060                final String propName = props[i].getName();
061
062                // see if either the column name, or the generous one matches
063                if (columnName.equalsIgnoreCase(propName) ||
064                        generousColumnName.equalsIgnoreCase(propName)) {
065                    columnToProperty[col] = i;
066                    break;
067                }
068            }
069        }
070
071        return columnToProperty;
072    }
073
074}