org.snaker.engine.access.jdbc.BeanPropertyHandler.java Source code

Java tutorial

Introduction

Here is the source code for org.snaker.engine.access.jdbc.BeanPropertyHandler.java

Source

/* Copyright 2013-2015 www.snakerflow.com.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.snaker.engine.access.jdbc;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.handlers.AbstractListHandler;
import org.snaker.engine.SnakerException;
import org.snaker.engine.helper.ClassHelper;

/**
 * ???(taskId->task_id)
 * ??Spring JDBCrowmapper?
 * dbutilsBeanHandler?BeanListHandler??bean?
 * BeanPropertyHandler??JdbcHelperrequiredSingleResult??
 * @author yuqs
 * @since 1.0
 * @param <T>
 */
public class BeanPropertyHandler<T> extends AbstractListHandler<T> {
    /**
     * ?beanclass
     */
    private Class<T> mappedClass;
    /**
     * 
     */
    private Map<String, PropertyDescriptor> mappedFields;

    /**
     * ?beanclass?mappedFields
     * @param mappedClass
     */
    public BeanPropertyHandler(Class<T> mappedClass) {
        initialize(mappedClass);
    }

    /**
     * ResultSet?
     */
    protected T handleRow(ResultSet rs) throws SQLException {
        /**
         * ?beanclass
         */
        T mappedObject = ClassHelper.instantiate(mappedClass);
        ResultSetMetaData rsmd = rs.getMetaData();
        int columnCount = rsmd.getColumnCount();
        /**
         * ResultSet
         */
        for (int index = 1; index <= columnCount; index++) {
            /**
             * ?index???
             */
            String column = JdbcHelper.lookupColumnName(rsmd, index);
            /**
             * ??????
             */
            PropertyDescriptor pd = this.mappedFields.get(column.replaceAll(" ", "").toLowerCase());
            if (pd != null) {
                try {
                    /**
                     * ?index?
                     */
                    Object value = JdbcHelper.getResultSetValue(rs, index, pd.getPropertyType());
                    try {
                        /**
                         * apache-beanutils
                         */
                        BeanUtils.setProperty(mappedObject, pd.getName(), value);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
        return mappedObject;
    }

    /**
     * ?beanclass??
     * @param mappedClass
     */
    protected void initialize(Class<T> mappedClass) {
        this.mappedClass = mappedClass;
        this.mappedFields = new HashMap<String, PropertyDescriptor>();
        PropertyDescriptor[] pds = null;
        try {
            /**
             * bean??
             */
            pds = propertyDescriptors(mappedClass);
        } catch (SQLException e) {
            throw new SnakerException(e.getMessage(), e.getCause());
        }
        for (PropertyDescriptor pd : pds) {
            if (pd.getWriteMethod() != null) {
                this.mappedFields.put(pd.getName().toLowerCase(), pd);
                String underscoredName = underscoreName(pd.getName());
                if (!pd.getName().toLowerCase().equals(underscoredName)) {
                    this.mappedFields.put(underscoredName, pd);
                }
            }
        }
    }

    /**
     * ???taskId->task_id
     * @param name
     * @return
     */
    private static String underscoreName(String name) {
        StringBuilder result = new StringBuilder();
        if (name != null && name.length() > 0) {
            result.append(name.substring(0, 1).toLowerCase());
            for (int i = 1; i < name.length(); i++) {
                String s = name.substring(i, i + 1);
                if (s.equals(s.toUpperCase())) {
                    result.append("_");
                    result.append(s.toLowerCase());
                } else {
                    result.append(s);
                }
            }
        }
        return result.toString();
    }

    /**
     * IntrospectorBeanInfo????PropertyDescriptor[]
     * @param c
     * @return PropertyDescriptor[]
     * @throws SQLException
     */
    private PropertyDescriptor[] propertyDescriptors(Class<?> c) throws SQLException {
        BeanInfo beanInfo = null;
        try {
            beanInfo = Introspector.getBeanInfo(c);
        } catch (IntrospectionException e) {
            throw new SQLException("Bean introspection failed: " + e.getMessage());
        }

        return beanInfo.getPropertyDescriptors();
    }
}