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     */
017    package org.apache.commons.dbutils.handlers;
018    
019    import java.sql.ResultSet;
020    import java.sql.SQLException;
021    
022    import org.apache.commons.dbutils.ResultSetHandler;
023    import org.apache.commons.dbutils.RowProcessor;
024    
025    /**
026     * <code>ResultSetHandler</code> implementation that converts the first
027     * <code>ResultSet</code> row into a <code>Map</code>. This class is thread 
028     * safe.
029     * 
030     * @see org.apache.commons.dbutils.ResultSetHandler
031     */
032    public class MapHandler implements ResultSetHandler {
033    
034        /**
035         * The RowProcessor implementation to use when converting rows 
036         * into Maps.
037         */
038        private final RowProcessor convert;
039    
040        /** 
041         * Creates a new instance of MapHandler using a 
042         * <code>BasicRowProcessor</code> for conversion.
043         */
044        public MapHandler() {
045            this(ArrayHandler.ROW_PROCESSOR);
046        }
047    
048        /** 
049         * Creates a new instance of MapHandler.
050         * 
051         * @param convert The <code>RowProcessor</code> implementation 
052         * to use when converting rows into Maps.
053         */
054        public MapHandler(RowProcessor convert) {
055            super();
056            this.convert = convert;
057        }
058    
059        /**
060         * Converts the first row in the <code>ResultSet</code> into a 
061         * <code>Map</code>.
062         * 
063         * @return A <code>Map</code> with the values from the first row or 
064         * <code>null</code> if there are no rows in the <code>ResultSet</code>. 
065         * 
066         * @throws SQLException if a database access error occurs
067         * 
068         * @see org.apache.commons.dbutils.ResultSetHandler#handle(java.sql.ResultSet)
069         */
070        public Object handle(ResultSet rs) throws SQLException {
071            return rs.next() ? this.convert.toMap(rs) : null;
072        }
073    
074    }