ResultSets. This class is thread safe.
+ *
+ * @see ResultSetHandler
+ */
+public class AsyncQueryRunner {
+
+ /**
+ * Is {@link ParameterMetaData#getParameterType(int)} broken (have we tried it yet)?
+ */
+ private volatile boolean pmdKnownBroken = false;
+
+ /**
+ * The DataSource to retrieve connections from.
+ */
+ protected final DataSource ds;
+
+ /**
+ * Constructor for QueryRunner.
+ */
+ public AsyncQueryRunner() {
+ this(null, false);
+ }
+
+ /**
+ * Constructor for QueryRunner, allows workaround for Oracle drivers
+ * @param pmdKnownBroken Oracle drivers don't support {@link ParameterMetaData#getParameterType(int) };
+ * if pmdKnownBroken is set to true, we won't even try it; if false, we'll try it,
+ * and if it breaks, we'll remember not to use it again.
+ */
+ public AsyncQueryRunner(boolean pmdKnownBroken) {
+ this(null, pmdKnownBroken);
+ }
+
+ /**
+ * Constructor for QueryRunner, allows workaround for Oracle drivers. Methods that do not take a
+ * Connection parameter will retrieve connections from this
+ * DataSource.
+ *
+ * @param ds The DataSource to retrieve connections from.
+ */
+ public AsyncQueryRunner(DataSource ds) {
+ this(ds, false);
+ }
+
+ /**
+ * Constructor for QueryRunner, allows workaround for Oracle drivers. Methods that do not take a
+ * Connection parameter will retrieve connections from this
+ * DataSource.
+ *
+ * @param ds The DataSource to retrieve connections from.
+ * @param pmdKnownBroken Oracle drivers don't support {@link ParameterMetaData#getParameterType(int) };
+ * if pmdKnownBroken is set to true, we won't even try it; if false, we'll try it,
+ * and if it breaks, we'll remember not to use it again.
+ */
+ public AsyncQueryRunner(DataSource ds, boolean pmdKnownBroken) {
+ this.pmdKnownBroken = pmdKnownBroken;
+ this.ds = ds;
+ }
+
+ protected class BatchCallableStatement implements CallableConnection is retrieved from the DataSource
+ * set in the constructor. This Connection must be in
+ * auto-commit mode or the update will not be saved.
+ *
+ * @param sql The SQL to execute.
+ * @param params An array of query replacement parameters. Each row in
+ * this array is one set of batch replacement values.
+ * @return A RunnableFuture which when completed returns the number of rows updated per statement.
+ * @throws SQLException if a database access error occurs
+ * @since DbUtils 1.1
+ */
+ public RunnableFuturePreparedStatement replacement parameters with
+ * the given objects.
+ * @param stmt PreparedStatement to fill
+ * @param params Query replacement parameters; null is a valid
+ * value to pass in.
+ * @throws SQLException if a database access error occurs
+ */
+ public void fillStatement(PreparedStatement stmt, Object... params) throws SQLException {
+
+ // check the parameter count, if we can
+ ParameterMetaData pmd = null;
+ if (!pmdKnownBroken) {
+ pmd = stmt.getParameterMetaData();
+ int stmtCount = pmd.getParameterCount();
+ int paramsCount = params == null ? 0 : params.length;
+
+ if (stmtCount != paramsCount) {
+ throw new SQLException("Wrong number of parameters: expected "
+ + stmtCount + ", was given " + paramsCount);
+ }
+ }
+
+ // nothing to do here
+ if (params == null) {
+ return;
+ }
+
+ for (int i = 0; i < params.length; i++) {
+ if (params[i] != null) {
+ stmt.setObject(i + 1, params[i]);
+ } else {
+ // VARCHAR works with many drivers regardless
+ // of the actual column type. Oddly, NULL and
+ // OTHER don't work with Oracle's drivers.
+ int sqlType = Types.VARCHAR;
+ if (!pmdKnownBroken) {
+ try {
+ sqlType = pmd.getParameterType(i + 1);
+ } catch (SQLException e) {
+ pmdKnownBroken = true;
+ }
+ }
+ stmt.setNull(i + 1, sqlType);
+ }
+ }
+ }
+
+ /**
+ * Fill the PreparedStatement replacement parameters with the
+ * given object's bean property values.
+ *
+ * @param stmt
+ * PreparedStatement to fill
+ * @param bean
+ * a JavaBean object
+ * @param properties
+ * an ordered array of properties; this gives the order to insert
+ * values in the statement
+ * @throws SQLException
+ * if a database access error occurs
+ */
+ public void fillStatementWithBean(PreparedStatement stmt, Object bean,
+ PropertyDescriptor[] properties) throws SQLException {
+ Object[] params = new Object[properties.length];
+ for (int i = 0; i < properties.length; i++) {
+ PropertyDescriptor property = properties[i];
+ Object value = null;
+ Method method = property.getReadMethod();
+ if (method == null) {
+ throw new RuntimeException("No read method for bean property "
+ + bean.getClass() + " " + property.getName());
+ }
+ try {
+ value = method.invoke(bean, new Object[0]);
+ } catch (InvocationTargetException e) {
+ throw new RuntimeException("Couldn't invoke method: " + method, e);
+ } catch (IllegalArgumentException e) {
+ throw new RuntimeException("Couldn't invoke method with 0 arguments: " + method, e);
+ } catch (IllegalAccessException e) {
+ throw new RuntimeException("Couldn't invoke method: " + method, e);
+ }
+ params[i] = value;
+ }
+ fillStatement(stmt, params);
+ }
+
+ /**
+ * Fill the PreparedStatement replacement parameters with the
+ * given object's bean property values.
+ *
+ * @param stmt PreparedStatement to fill
+ * @param bean A JavaBean object
+ * @param propertyNames An ordered array of property names (these should match the
+ * getters/setters); this gives the order to insert values in the
+ * statement
+ * @throws SQLException If a database access error occurs
+ */
+ public void fillStatementWithBean(PreparedStatement stmt, Object bean, String... propertyNames) throws SQLException {
+ PropertyDescriptor[] descriptors;
+ try {
+ descriptors = Introspector.getBeanInfo(bean.getClass())
+ .getPropertyDescriptors();
+ } catch (IntrospectionException e) {
+ throw new RuntimeException("Couldn't introspect bean " + bean.getClass().toString(), e);
+ }
+ PropertyDescriptor[] sorted = new PropertyDescriptor[propertyNames.length];
+ for (int i = 0; i < propertyNames.length; i++) {
+ String propertyName = propertyNames[i];
+ if (propertyName == null) {
+ throw new NullPointerException("propertyName can't be null: " + i);
+ }
+ boolean found = false;
+ for (int j = 0; j < descriptors.length; j++) {
+ PropertyDescriptor descriptor = descriptors[j];
+ if (propertyName.equals(descriptor.getName())) {
+ sorted[i] = descriptor;
+ found = true;
+ break;
+ }
+ }
+ if (!found) {
+ throw new RuntimeException("Couldn't find bean property: "
+ + bean.getClass() + " " + propertyName);
+ }
+ }
+ fillStatementWithBean(stmt, bean, sorted);
+ }
+
+ /**
+ * Returns the DataSource this runner is using.
+ * QueryRunner methods always call this method to get the
+ * DataSource so subclasses can provide specialized
+ * behavior.
+ *
+ * @return DataSource the runner is using
+ */
+ public DataSource getDataSource() {
+ return this.ds;
+ }
+
+ /**
+ * Factory method that creates and initializes a
+ * PreparedStatement object for the given SQL.
+ * QueryRunner methods always call this method to prepare
+ * statements for them. Subclasses can override this method to provide
+ * special PreparedStatement configuration if needed. This implementation
+ * simply calls conn.prepareStatement(sql).
+ *
+ * @param conn The Connection used to create the
+ * PreparedStatement
+ * @param sql The SQL statement to prepare.
+ * @return An initialized PreparedStatement.
+ * @throws SQLException if a database access error occurs
+ */
+ protected PreparedStatement prepareStatement(Connection conn, String sql)
+ throws SQLException {
+
+ return conn.prepareStatement(sql);
+ }
+
+ /**
+ * Factory method that creates and initializes a
+ * Connection object. QueryRunner methods
+ * always call this method to retrieve connections from its DataSource.
+ * Subclasses can override this method to provide
+ * special Connection configuration if needed. This
+ * implementation simply calls ds.getConnection().
+ *
+ * @return An initialized Connection.
+ * @throws SQLException if a database access error occurs
+ * @since DbUtils 1.1
+ */
+ protected Connection prepareConnection() throws SQLException {
+ if(this.getDataSource() == null) {
+ throw new SQLException("QueryRunner requires a DataSource to be " +
+ "invoked in this way, or a Connection should be passed in");
+ }
+ return this.getDataSource().getConnection();
+ }
+
+ protected class QueryCallableStatementConnection is retrieved from the
+ * DataSource set in the constructor.
+ * @param ResultSet.
+ * @param params Initialize the PreparedStatement's IN parameters with
+ * this array.
+ * @return A RunnableFuture which when completed returns the object generated by the handler.
+ * @throws SQLException if a database access error occurs
+ */
+ public Connection is retrieved from the
+ * DataSource set in the constructor.
+ * @param ResultSet.
+ *
+ * @return A RunnableFuture which when completed returns the object generated by the handler.
+ * @throws SQLException if a database access error occurs
+ */
+ public null is a
+ * valid value to pass in.
+ *
+ * @throws SQLException if a database access error occurs
+ */
+ protected void rethrow(SQLException cause, String sql, Object... params)
+ throws SQLException {
+
+ String causeMessage = cause.getMessage();
+ if (causeMessage == null) {
+ causeMessage = "";
+ }
+ StringBuffer msg = new StringBuffer(causeMessage);
+
+ msg.append(" Query: ");
+ msg.append(sql);
+ msg.append(" Parameters: ");
+
+ if (params == null) {
+ msg.append("[]");
+ } else {
+ msg.append(Arrays.deepToString(params));
+ }
+
+ SQLException e = new SQLException(msg.toString(), cause.getSQLState(),
+ cause.getErrorCode());
+ e.setNextException(cause);
+
+ throw e;
+ }
+
+ protected class UpdateCallableStatement implements CallableConnection is retrieved
+ * from the DataSource set in the constructor. This
+ * Connection must be in auto-commit mode or the update will
+ * not be saved.
+ *
+ * @param sql The SQL statement to execute.
+ * @throws SQLException if a database access error occurs
+ * @return A RunnableFuture which when completed returns the number of rows updated.
+ */
+ public RunnableFutureConnection is
+ * retrieved from the DataSource set in the constructor.
+ * This Connection must be in auto-commit mode or the
+ * update will not be saved.
+ *
+ * @param sql The SQL statement to execute.
+ * @param param The replacement parameter.
+ * @throws SQLException if a database access error occurs
+ * @return A RunnableFuture which when completed returns the number of rows updated.
+ */
+ public RunnableFutureConnection is retrieved from the DataSource
+ * set in the constructor. This Connection must be in
+ * auto-commit mode or the update will not be saved.
+ *
+ * @param sql The SQL statement to execute.
+ * @param params Initializes the PreparedStatement's IN (i.e. '?')
+ * parameters.
+ * @throws SQLException if a database access error occurs
+ * @return A RunnableFuture which when completed returns the number of rows updated.
+ */
+ public RunnableFutureResultSet in a decorator before processing it.
+ * This implementation returns the ResultSet it is given
+ * without any decoration.
+ *
+ * + * Often, the implementation of this method can be done in an anonymous + * inner class like this: + *
+ *
+ * QueryRunner run = new QueryRunner() {
+ * protected ResultSet wrap(ResultSet rs) {
+ * return StringTrimmedResultSet.wrap(rs);
+ * }
+ * };
+ *
+ *
+ * @param rs The ResultSet to decorate; never
+ * null.
+ * @return The ResultSet wrapped in some decorator.
+ */
+ protected ResultSet wrap(ResultSet rs) {
+ return rs;
+ }
+
+ /**
+ * Close a Connection. This implementation avoids closing if
+ * null and does not suppress any exceptions. Subclasses
+ * can override to provide special handling like logging.
+ * @param conn Connection to close
+ * @throws SQLException if a database access error occurs
+ * @since DbUtils 1.1
+ */
+ protected void close(Connection conn) throws SQLException {
+ DbUtils.close(conn);
+ }
+
+ /**
+ * Close a Statement. This implementation avoids closing if
+ * null and does not suppress any exceptions. Subclasses
+ * can override to provide special handling like logging.
+ * @param stmt Statement to close
+ * @throws SQLException if a database access error occurs
+ * @since DbUtils 1.1
+ */
+ protected void close(Statement stmt) throws SQLException {
+ DbUtils.close(stmt);
+ }
+
+ /**
+ * Close a ResultSet. This implementation avoids closing if
+ * null and does not suppress any exceptions. Subclasses
+ * can override to provide special handling like logging.
+ * @param rs ResultSet to close
+ * @throws SQLException if a database access error occurs
+ * @since DbUtils 1.1
+ */
+ protected void close(ResultSet rs) throws SQLException {
+ DbUtils.close(rs);
+ }
+
+}
Propchange: commons/proper/dbutils/trunk/src/java/org/apache/commons/dbutils/AsyncQueryRunner.java
------------------------------------------------------------------------------
svn:eol-style = native
Added: commons/proper/dbutils/trunk/src/test/org/apache/commons/dbutils/AsyncQueryRunnerTest.java
URL: http://svn.apache.org/viewvc/commons/proper/dbutils/trunk/src/test/org/apache/commons/dbutils/AsyncQueryRunnerTest.java?rev=1156964&view=auto
==============================================================================
--- commons/proper/dbutils/trunk/src/test/org/apache/commons/dbutils/AsyncQueryRunnerTest.java (added)
+++ commons/proper/dbutils/trunk/src/test/org/apache/commons/dbutils/AsyncQueryRunnerTest.java Fri Aug 12 04:45:25 2011
@@ -0,0 +1,569 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.apache.commons.dbutils;
+
+import static org.junit.Assert.fail;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.lang.reflect.Method;
+import java.sql.Connection;
+import java.sql.ParameterMetaData;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.RunnableFuture;
+
+import javax.sql.DataSource;
+
+import org.apache.commons.dbutils.handlers.ArrayHandler;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+public class AsyncQueryRunnerTest {
+ AsyncQueryRunner runner;
+ ArrayHandler handler;
+
+ @Mock DataSource dataSource;
+ @Mock Connection conn;
+ @Mock PreparedStatement stmt;
+ @Mock ParameterMetaData meta;
+ @Mock ResultSet results;
+
+ static final Method getParameterCount, getParameterType, getParameterMetaData;
+ static {
+ try {
+ getParameterCount = ParameterMetaData.class.getMethod("getParameterCount", new Class[0]);
+ getParameterType = ParameterMetaData.class.getMethod("getParameterType", new Class[]{int.class});
+ getParameterMetaData = PreparedStatement.class.getMethod("getParameterMetaData", new Class[0]);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Before
+ public void setUp() throws Exception {
+ MockitoAnnotations.initMocks(this); // init the mocks
+
+ when(dataSource.getConnection()).thenReturn(conn);
+ when(conn.prepareStatement(any(String.class))).thenReturn(stmt);
+ when(stmt.getParameterMetaData()).thenReturn(meta);
+ when(stmt.getResultSet()).thenReturn(results);
+ when(stmt.executeQuery()).thenReturn(results);
+ when(results.next()).thenReturn(false);
+
+ handler = new ArrayHandler();
+ runner = new AsyncQueryRunner(dataSource);
+ }
+
+ //
+ // Batch test cases
+ //
+
+ private void callGoodBatch(Connection conn, Object[][] params) throws Exception {
+ when(meta.getParameterCount()).thenReturn(2);
+ RunnableFuture