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