1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17 package org.apache.commons.dbutils.handlers;
18
19 import java.sql.ResultSet;
20 import java.sql.SQLException;
21
22 import org.apache.commons.dbutils.BasicRowProcessor;
23 import org.apache.commons.dbutils.ResultSetHandler;
24 import org.apache.commons.dbutils.RowProcessor;
25
26 /**
27 * {@code ResultSetHandler} implementation that converts a
28 * {@code ResultSet} into an {@code Object[]}. This class is
29 * thread safe.
30 *
31 * @see org.apache.commons.dbutils.ResultSetHandler
32 */
33 public class ArrayHandler implements ResultSetHandler<Object[]> {
34
35 /**
36 * Singleton processor instance that handlers share to save memory. Notice
37 * the default scoping to allow only classes in this package to use this
38 * instance.
39 */
40 static final RowProcessor ROW_PROCESSOR = new BasicRowProcessor();
41
42 /**
43 * An empty array to return when no more rows are available in the ResultSet.
44 */
45 private static final Object[] EMPTY_ARRAY = {};
46
47 /**
48 * The RowProcessor implementation to use when converting rows
49 * into arrays.
50 */
51 private final RowProcessor convert;
52
53 /**
54 * Creates a new instance of ArrayHandler using a
55 * {@code BasicRowProcessor} for conversion.
56 */
57 public ArrayHandler() {
58 this(ROW_PROCESSOR);
59 }
60
61 /**
62 * Creates a new instance of ArrayHandler.
63 *
64 * @param convert The {@code RowProcessor} implementation
65 * to use when converting rows into arrays.
66 */
67 public ArrayHandler(final RowProcessor convert) {
68 this.convert = convert;
69 }
70
71 /**
72 * Places the column values from the first row in an {@code Object[]}.
73 * @param resultSet {@code ResultSet} to process.
74 * @return An Object[]. If there are no rows in the {@code ResultSet}
75 * an empty array will be returned.
76 *
77 * @throws SQLException if a database access error occurs
78 * @see org.apache.commons.dbutils.ResultSetHandler#handle(java.sql.ResultSet)
79 */
80 @Override
81 public Object[] handle(final ResultSet resultSet) throws SQLException {
82 return resultSet.next() ? this.convert.toArray(resultSet) : EMPTY_ARRAY;
83 }
84
85 }