You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@commons.apache.org by hu...@apache.org on 2002/08/14 19:51:42 UTC
cvs commit: jakarta-commons-sandbox/scaffold/src/java/org/apache/commons/scaffold/sql StorageBeanBase.java Storable.java StatementUtils.java ServletAdaptor.java RowSetUtils.java.text ResultSetUtils.java PoolmanAdaptor.java ConnectionAdaptor.java CommandStore.java AccessBase.java
husted 2002/08/14 10:51:42
Added: scaffold/src/java/org/apache/commons/scaffold/sql
StorageBeanBase.java Storable.java
StatementUtils.java ServletAdaptor.java
RowSetUtils.java.text ResultSetUtils.java
PoolmanAdaptor.java ConnectionAdaptor.java
CommandStore.java AccessBase.java
Log:
[SCAFFOLD] New sandbox component
Revision Changes Path
1.1 jakarta-commons-sandbox/scaffold/src/java/org/apache/commons/scaffold/sql/StorageBeanBase.java
Index: StorageBeanBase.java
===================================================================
/**
before startup,
+ create a properties file for your SQL commands at WEB-INF/classes/resources/command.properties
on startup,
+ load the ConnectionAdaptor for your database connection pool
+ create CommandStore and retain instance in application context under any name (singleton).
- :TODO: permit each subclass to have its own properties (collection of properties, like Actions).
for each storage object,
+ add standard sql commands to properties file (insert,update,retrieve,delete,undelete);
+ + insert and update command should use same columns in same order
+ + standard retrieve,delete,undelete should use primary key
+ add properties to your subclass matching the database columns as needed
+ + Hint: if columns cannot follow property naming conventions, rename column in command
+ + Hint: you can use the same object for more than one table or resultset if you like
+ override getParameters() to return an array of properties as needed by object's insert, update commands.
- :TODO: use reflection to read parameter key and make array from that.
- :TODO: check for key.paramlist then paramlist
+ override primaryKey to reference this object's primary key
+ override constructor to set prefix for this object
+ if more than one bean will share CommandStore, override constructor to set a prefix for each bean.
Include prefix in resource file, but not in Java code.
at runtime
+ call bean.store(parameters) with a Map of the properties needed by your SQL command.
+ the Map entries can be Strings or native types
+ ditto for retrieve, delete, undelete
then
+ Add other speciality methods as needed, using standard methods as guide.
*/
package org.apache.commons.scaffold.sql;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Map;
import java.util.Properties;
// import org.apache.commons.beanutils.BeanUtils; // Struts 1.1
import org.apache.struts.util.BeanUtils; // Struts 1.0.x
import org.apache.commons.scaffold.lang.ParameterException;
import org.apache.commons.scaffold.lang.PopulateException;
import org.apache.commons.scaffold.lang.PropertiesException;
import org.apache.commons.scaffold.lang.ResourceException;
import org.apache.commons.scaffold.lang.Tokens;
import org.apache.commons.scaffold.lucene.SearchUtils;
import org.apache.commons.scaffold.lucene.Engine;
import org.apache.commons.scaffold.sql.StatementUtils;
import org.apache.commons.scaffold.util.ResourceUtils;
import org.apache.commons.scaffold.util.ProcessBeanBase;
import org.apache.commons.scaffold.util.ProcessResult;
import org.apache.commons.scaffold.util.ProcessResultBase;
/**
* Common data access methods.
*
* @author Ted Husted
* @author OK State DEQ
* @version $Revision: 1.1 $ $Date: 2002/08/14 17:51:42 $
*/
public class StorageBeanBase extends ProcessBeanBase implements Storable {
// ----------------------------------------------------------- Commands
/**
* [:TODO: Javadoc]
*/
private final static String dot = ".";
/**
* Our command string properties.
* Can be loaded from an external properties file at startup.
*/
private static Properties commands;
/**
* Retrieve command from <code>commands</code> Properties
*/
private final String getCommand(String key) throws PropertiesException {
if (null==commands) throw new PropertiesException();
String command = null;
String prefix = getPrefix();
if (null!=prefix) {
StringBuffer sb = new StringBuffer(prefix);
sb.append(dot);
sb.append(key);
command = sb.toString();
}
else command = key;
return commands.getProperty(command);
}
/**
* Retrieve command from <code>commands</code> Properties
*/
private final String getCommandRoot(String key) throws PropertiesException {
if (null==commands) throw new PropertiesException();
return commands.getProperty(key);
}
/**
* Configure the data access system.
* <p>
* This method sets up the SQL connection pool adaptor.
* A new adaptor can be used by changing this method.
* This can be called once by main or servlet.init at startup.
*/
public static final void init(Properties _commands) {
if (null==commands) commands = _commands;
}
// --------------------------------------------------------
/**
* [:TODO: Javadoc]
*/
private final static String INSERT = "insert";
/**
* [:TODO: Javadoc]
*/
private final static String UPDATE = "update";
/**
* [:TODO: Javadoc]
*/
private final static String RETRIEVE = "retrieve";
/**
* [:TODO: Javadoc]
*/
private final static String DELETE = "delete";
/**
* [:TODO: Javadoc]
*/
private final static String UNDELETE = "undelete";
/**
* [:TODO: Javadoc]
*/
private final static String TABLE = "table";
/**
* [:TODO: Javadoc]
*/
private String prefix = null;
/**
* [:TODO: Javadoc]
*/
public String getPrefix() {
return prefix;
}
/**
* [:TODO: Javadoc]
*/
public void setPrefix(String prefix) {
this.prefix = prefix;
}
/**
* [:TODO: Javadoc]
*/
private Object[] parameters = null;
/**
* [:TODO: Javadoc]
*/
public Object[] getParameters() {
return parameters;
}
/**
* [:TODO: Javadoc]
*/
public void setParameters(Object[] parameters) {
this.parameters = parameters;
}
/**
* Perform business logic for this instance by obtaining any
* properties from the parameters object.
* The base implementation casts the parameters as a Map,
* populates the bean, and returns execute().
* @exception Subclasses can throw any Exception
*/
public void populate(Map parameters) throws Exception {
if (parameters!=null) {
BeanUtils.populate(this,parameters);
}
} // end populate
// ----------------------------------------------------- Create Methods
/**
* Lookup command and execute "update" query to create a table,
* seed it with data, et cetera.
* <p>
* @param command Name of command to execute
* @exception Resource exception if data access error occurs
* @author Ted Husted
* @version $Revision: 1.1 $ $Date: 2002/08/14 17:51:42 $
*/
protected final void executeUpdate(String command)
throws ResourceException {
try {
int result = StatementUtils.executeUpdate(
null,getCommand(command));
}
catch (SQLException e) {
throw new ResourceException(e);
}
} // end executeUpdate
// -------------------------------------------------- Retrieval Methods
/**
* Retrieve entry from data storage.
* <p>
* @return Collection with record or empty collection
* @exception ResourceException if SQL error occurs
* @param key The primary key of the entry
* @param target Bean to hold copy of entry being retrieved
* @param command The name of the data access command
* collection
*/
protected final boolean findElement(
Object target,
Object key,
String command) throws ResourceException {
boolean found = false;
try {
found = StatementUtils.getElement(null,target,
getCommand(command),key);
}
catch (SQLException e) {
throw new ResourceException(e);
}
return found;
} // end findElement
/**
* Retrieve a collection of beans from data stoarge.
* <p>
* @return Collection with entry or empty collection
* @exception throws PropertiesException, ResourceException
* if data access error occurs
* @param target Object to use as factory when populating
* @param command Name of the data access command
* collection
*/
protected final Collection findCollection(Object target,
String command) throws ResourceException {
try {
return StatementUtils.getCollection(null,
target,getCommand(command));
}
catch (SQLException e) {
throw new ResourceException(e);
}
} // end findCollection
/**
* Retrieve a collection of beans from data stoarge.
* <p>
* @return Collection with entry or empty collection
* @exception throws PropertiesException, ResourceException
* if data access error occurs
* @param target Object to use as factory when populating
* @param command Name of the data access command
* collection
* @param parameters An array of parameters to be used with command
*/
protected final Collection findCollection(Object target,
String command, Object[] parameters) throws ResourceException {
try {
return StatementUtils.getCollection(null,
target,getCommand(command),parameters);
}
catch (SQLException e) {
throw new ResourceException(e);
}
} // end findCollection
/**
* Retrieve a collection of beans from data stoarge.
* <p>
* @return Collection with entry or empty collection
* @exception throws PropertiesException, ResourceException
* if data access error occurs
* @param target Object to use as factory when populating
* @param command Name of the data access command
* collection
* @param parameter A String parameter to be used with command
*/
protected final Collection findCollection(Object target,
String command, Object parameter) throws ResourceException {
try {
return StatementUtils.getCollection(null,
target,getCommand(command),parameter);
}
catch (SQLException e) {
throw new ResourceException(e);
}
} // end findCollection
/**
* Retrieve a collection of beans from data stoarge.
* <p>
* @return Collection with entry or empty collection
* @exception throws PropertiesException, ResourceException
* if data access error occurs
* @param target Object to use as factory when populating
* @param command Name of the data access command
* collection
* @param parameter An int parameter to be used with command
*/
protected final Collection findCollection(Object target,
String command, int parameter) throws ResourceException {
return findCollection(target,command,new Integer(parameter));
} // end findCollection
/**
* Retrieve a collection of beans from data stoarge.
* <p>
* @return Collection with entry or empty collection
* @exception throws PropertiesException, ResourceException
* if data access error occurs
* @param target Object to use as factory when populating
* @param command Name of the data access command
* collection
* @param parameter A String parameter to be used with command
*/
protected final Collection findCollectionLike(Object target,
String command, String parameter) throws ResourceException {
try {
return StatementUtils.getCollectionLike(null,
target,getCommand(command),parameter);
}
catch (SQLException e) {
throw new ResourceException(e);
}
} // end findCollectionLike
/**
* Select entries from data storage by indexed property..
* <p>
* @return Collection with record or empty Collection
* @param value Term to match
* @param property Field to search
* @param target Object to use as factory when populating
* collection
* @exception Throws ParameterException if value is not a search
* term for property
* @exception Throws PopulateExecption if result cannot be set to
* target
* @exception throws PropertiesException, ResourceException is SQL, IO, or other
* data access error occurs.
*/
protected final Collection findByProperty(
Object target,
String property,
String value) throws ParameterException, PopulateException,
ResourceException {
return SearchUtils.getCollection(target,
Engine.getHits(
Engine.getQuery(value,property)));
} // end findByProperty
// ======================================================== UD Methods
/**
* [:TODO: Javadoc]
*/
private int resultCode = 0;
/**
* [:TODO: Javadoc]
*/
public int getResultCode() {
return resultCode;
}
/**
* [:TODO: Javadoc]
*/
public void setResultCode(int resultCode) {
this.resultCode = resultCode;
}
/**
* [:TODO: Javadoc]
*/
private Object result = this;
/**
* [:TODO: Javadoc]
*/
public Object getResult() {
return result;
}
/**
* [:TODO: Javadoc]
*/
public void setResult(Object result) {
this.result = result;
}
/**
* [:TODO: Javadoc]
*/
private Object primaryKey = null;
/**
* [:TODO: Javadoc]
*/
public Object getPrimaryKey() {
return this.primaryKey;
}
/**
* [:TODO: Javadoc]
*/
public void setPrimaryKey(Object key) {
this.primaryKey = key;
}
// ------------------------------------------------------------- store
/**
* [:TODO: Javadoc]
*/
public static String KEYS_NEXT = "keys.next";
/**
* [:TODO: Javadoc]
*/
public static String KEYS_INC = "keys.inc";
/**
* Returns next sequential key for given set of keys.
* Expects KEYS_NET nd KEYS_INC commands to be defined.
*
* @return A String representing the allocated key
* @exception ResourceException if data access error occurs
* @param keyName The name of the key set to use to generate the key
*/
protected synchronized final Integer createKey(String keyName)
throws ResourceException {
Object result = null;
try {
result = StatementUtils.createKey(
null,
1,
getCommandRoot(KEYS_NEXT),
getCommand(keyName),
getCommandRoot(KEYS_INC)
);
}
catch (SQLException e) {
throw new ResourceException(e);
}
return (Integer) result;
} // end createKey()
/**
* [:TODO: Javadoc]
*/
public void allocateKey() throws Exception {
setPrimaryKey(createKey(TABLE));
}
/**
* Commit record to storage.
* If create is true, entry is created.
* Otherwise, an existing entry is updated.
* @return 0 if fails
* @exception ResourceException if SQL error occurs
* @param insert True to insert, false to update.
* @insert The name of the insert command
* @update The name of the delete command
@ @parameters The parameters to use with either command
*
*/
public void store() throws Exception {
Object key = getPrimaryKey();
boolean isInsert = (null==key);
if (isInsert) allocateKey();
String command = null;
if (isInsert) {
command = getCommand(INSERT);
}
else {
command = getCommand(UPDATE);
}
int result = 0;
try {
result = StatementUtils.executeUpdate(
null,command,getParameters());
}
catch (SQLException e) {
throw new ResourceException(e);
}
setResultCode(result);
}
/**
* [:TODO: Javadoc]
*/
public Object store(Object parameters) throws Exception {
populate((Map) parameters);
String message = Tokens.DATA_RECORD_UPDATED;
if (null==getPrimaryKey()) {
message = Tokens.DATA_RECORD_INSERTED;
}
store();
ProcessResult result = new ProcessResultBase(getResult());
result.addMessage(message);
result.addMessage(getPrimaryKey());
result.setSingleForm(true);
return result;
}
// ---------------------------------------------------------- retrieve
/**
* [:TODO: Javadoc]
*/
public void retrieve() throws Exception {
boolean found = findElement(this,getPrimaryKey(),RETRIEVE);
if (found) {
setResult(this);
setResultCode(1);
}
else {
setResultCode(0);
}
}
// ------------------------------------------------------------ delete
/**
* Mark entry for deletion.
* Returns copy of entry before update in target parameter.
*
* @return 0 if fails
* @exception ResourceException if SQL or other data-access error occurs
* @exception runtime Null Pointer Exception if either parameter is null
* @param target Bean to hold copy of record being marked
* @param article Primary key of record to mark
*/
public void delete() throws Exception {
retrieve();
int result = getResultCode();
if (0!=result) {
try {
// Mark as deleted
result = StatementUtils.executeUpdate(null,
getCommand(DELETE),getPrimaryKey());
}
catch (SQLException e) {
throw new ResourceException(e);
}
setResultCode(result);
}
}
/**
* [:TODO: Javadoc]
*/
protected Object delete(Object parameters) throws Exception {
populate((Map) parameters);
Object key = getPrimaryKey();
if (null==key) {
throw new ParameterException();
}
delete();
int resultCode = getResultCode();
ProcessResult result = new ProcessResultBase(this);
if (resultCode==0)
result.addMessage(Tokens.DATA_ACCESS_EMPTY);
else
result.addMessage(Tokens.DATA_RECORD_DELETED);
result.addMessage(key);
return (Object) result;
} // end delete
// ---------------------------------------------------------- undelete
/**
* Unmark entry for deletion.
* Returns copy of restored entry in target parameter.
*
* @return 0 if fails
* @exception ResourceException if data access error occurs
* @param target Bean to hold copy of record being unmarked
* @param article Primary key of record to unmark
*/
public void undelete() throws Exception {
int result = 0;
try {
result = StatementUtils.executeUpdate(null,
getCommand(UNDELETE),getPrimaryKey());
}
catch (SQLException e) {
throw new ResourceException(e);
}
setResultCode(result);
} // end undelete
/**
* Update indicated entry in data storage.
* Return confirmation message in a ProcessResult object.
*
* @param parameters The map or other object to use with this
* operation
* @throws ParameterException if article not found in parameters
@ @throws ResourceException if SQLException or other data exception
*/
public Object undelete(Object parameters) throws Exception {
populate((Map) parameters);
Object key = getPrimaryKey();
if (null==key) {
throw new ParameterException();
}
undelete();
int resultCode = getResultCode();
ProcessResult result = new ProcessResultBase(this);
if (0==resultCode)
result.addMessage(Tokens.DATA_ACCESS_EMPTY);
else
result.addMessage(Tokens.DATA_RECORD_RESTORED);
result.addMessage(key);
return (Object) result;
} // end execute
} // end StorageBeanBase
/*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this Collection of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this Collection of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
1.1 jakarta-commons-sandbox/scaffold/src/java/org/apache/commons/scaffold/sql/Storable.java
Index: Storable.java
===================================================================
package org.apache.commons.scaffold.sql;
import java.util.Map;
/**
* Simple interface to describe public methods on a
* data access object.
*
* @author Ted Husted
* @version $Revision: 1.1 $ $Date: 2002/08/14 17:51:42 $
*/
public interface Storable {
/**
*/
public void store() throws Exception;
/**
*/
public void retrieve() throws Exception;
/**
*/
public void delete() throws Exception;
/**
*/
public void undelete() throws Exception;
/**
*/
public Object getPrimaryKey();
/**
*/
public void allocateKey() throws Exception;
/**
*/
public Object getResult();
/**
*/
public int getResultCode();
/**
*/
public void populate(Map parameters) throws Exception;
}
/*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Scaffold", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
1.1 jakarta-commons-sandbox/scaffold/src/java/org/apache/commons/scaffold/sql/StatementUtils.java
Index: StatementUtils.java
===================================================================
package org.apache.commons.scaffold.sql;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.ResultSet;
import java.util.Collection;
/**
* General purpose SQL Statements.
*
* @author Ted Husted
* @version $Revision: 1.1 $ $Date: 2002/08/14 17:51:42 $
*/
public final class StatementUtils {
/**
* Create a new database table in an existing database,
* by sending "CREATE TABLE " and the parameters to
* the DBMS configured with the ConnectionPool.
* <p>
* For safety, does <b>not</b> drop table first.
* <p>
* Returns false if a SQL exception is thrown; exception
* is written to the servlet log.
*
* @param resource The database resource key or null for default
* @param tableName The name of the table to create
* @param tableCreate The SQL command defining the
* fields and indices
* @return Result of statement.execute()
* @exception SQL Exception if SQL error occurs
*/
public static final int createTable(
String resource,
String tableName,
String tableCreate)
throws SQLException {
return executeUpdate(resource,"CREATE TABLE " +
tableName + " " + tableCreate);
} // end createTable
/**
* Returns next sequential key for given table.
* <p>
* This ensures compatibility for DBMS products that do not
* support auto-incrementing a key field.
* <p>
* Intended to generate primary keys, but could be used to
* create other serial numbers based on an unsigned int.
* <p>
* Allocating the key involves reading the current key, and
* then incrementing the key for the next user. The method
* is synchronized so that two threads do not read the
* same key before it is incremented.
* <p>
* This routine is "unrolled" for efficiency, but the same
* effect can be accomplished using <code>getColumn()</code>
* to fetch the next key,
* and <code>executeUpdate</code> to increment the key.
*
* @param resource The database resource key or null for default
* @param column The column to return from the result set.
* @param query The SQL statement to fetch the next key.
* @param key The table name or other replaceable parameter.
* @param query The SQL statement to increment the next key.
* @exception SQLException if SQL error occurs
*/
public static final synchronized Object createKey(
String resource,
int column,
String query,
Object key,
String update)
throws SQLException {
Connection connection = null;
ResultSet resultSet = null;
PreparedStatement preparedStatement = null;
Object result = null;
int resultCode = 0;
try {
connection =
ConnectionAdaptor.getPool().getConnection(resource);
// fetch the next key
// - Object next = getColumn(resource,1,query,key);
preparedStatement = connection.prepareStatement(query);
preparedStatement.setObject(1,key);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
result = resultSet.getObject(column);
}
// increment key
// - int result = executeUpdate(resource,update,key);
preparedStatement = connection.prepareStatement(update);
preparedStatement.setObject(1,key);
resultCode = preparedStatement.executeUpdate();
}
finally {
try {
if (preparedStatement!=null) preparedStatement.close();
if (resultSet!=null) resultSet.close();
if (connection!=null) connection.close();
}
catch (SQLException sqle) {
// do nothing
}
}
return result;
} // end createKey
// ------------------------------------------------------ executeUpdate
/**
* Used to select correct executeUpdate signature.
*/
private static final Object[] nullParams = null;
/**
* Prepares statement using SQL statement and executes
* with DBMS configured with the ConnectionPool.
* <p>
* Command may be an INSERT, UPDATE, or DELETE statement
* or anything that returns nothing, such as a DDL
* statement.
*
* @param connection The database connection or null to acquire
* @param resource The database resource key or null for default
* @param command The SQL statement to execute.
* @param parameters An array of parameter objects
* @exception SQLException if SQL error occurs
*/
public static final int executeUpdate(
Connection connection,
String resource,
String command,
Object[] parameters)
throws SQLException {
boolean acqConnection = (connection==null);
Statement statement = null;
PreparedStatement preparedStatement = null;
int result = 0;
try {
if (acqConnection) {
connection =
ConnectionAdaptor.getPool().getConnection(resource);
}
if ((parameters==null) || (parameters.length==0)) {
statement = connection.createStatement();
result = statement.executeUpdate(command);
}
else {
preparedStatement = connection.prepareStatement(command);
for (int i=0; i<parameters.length; i++) {
preparedStatement.setObject(i+1, parameters[i]);
}
result = preparedStatement.executeUpdate();
}
} // end try
finally {
try {
if (preparedStatement != null) preparedStatement.close();
if (statement != null) statement.close();
if ((acqConnection) && (connection!= null)) connection.close();
}
catch (SQLException sqle) {
// do nothing
}
}
return result;
} // end executeUpdate
/**
* Convenience method for calling
* <code>executeUpdate(String,String,Object[]);</code>
* with a single Object parameter.
*
* @param resource The database resource key or null for default
* @param command The SQL statement to execute.
* @param parameter A single parameter to use with command
* @exception SQLException if SQL error occurs
*/
public static final int executeUpdate(
String resource,
String command,
Object parameter)
throws SQLException {
Object[] parameters = new Object[1];
parameters[0] = parameter;
return executeUpdate(null,resource,command,parameters);
} // end executeUpdate
/**
* Convenience method for calling
* <code>executeUpdate(String,String,Object[]);</code>
* without a parameter list.
*
* @param resource The database resource key or null for default
* @param command The SQL statement to execute.
* @exception SQLException if SQL error occurs
*/
public static final int executeUpdate(
String resource,
String command)
throws SQLException {
return executeUpdate(null,resource,command,nullParams);
} // end executeUpdate
/**
* Prepares statement using SQL statement and executes
* with DBMS configured with the ConnectionPool.
* <p>
* Command may be an INSERT, UPDATE, or DELETE statement
* or anything that returns nothing, such as a DDL
* statement.
*
* @param resource The database resource key or null for default
* @param command The SQL statement to execute.
* @param parameters An array of parameter objects
* @exception SQLException if SQL error occurs
*/
public static final int executeUpdate(
String resource,
String command,
Object[] parameters)
throws SQLException {
return executeUpdate(null,resource,command,parameters);
} // end executeUpdate
/**
* Convenience method for calling
* <code>executeUpdate(String,String,Object[]);</code>
* without a parameter list.
*
* @param resource The database resource key or null for default
* @param command The SQL statement to execute.
* @exception SQLException if SQL error occurs
*/
public static final int executeUpdate(
String command)
throws SQLException {
return executeUpdate(null,null,command,nullParams);
} // end executeUpdate
// ------------------------------------------------------- executeQuery
/**
* Merges a SQL command with an array of parameters.
* Any number or no parameters may be passed.
* The parameters parameter may also be null.
* <p>
* The Statement or PreparedStatement used internally
* are closed, but the Connection is left open so that the
* ResultSet remains valid.
* The caller should close the Connection and ResultSet
* as soon as possible, especially if they are pooled.
*
* @param resource The database resource key or null for default
* @param target The JavaBean object to return in the collection.
* @param command The SQL statement to prepare and execute.
* @param parameters The replaceable parameters to use with command.
* @exception SQLException if SQL error occurs
*/
public static final ResultSet executeQuery(
Connection connection,
String command,
Object[] parameters)
throws SQLException {
Statement statement = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
if ((parameters==null) || (parameters.length==0)) {
statement = connection.createStatement();
resultSet = statement.executeQuery(command);
}
else {
preparedStatement = connection.prepareStatement(command);
for (int i=0; i<parameters.length; i++) {
preparedStatement.setObject(i+1, parameters[i]);
}
resultSet = preparedStatement.executeQuery();
}
}
finally {
try {
if (statement != null) statement.close();
if (preparedStatement != null) preparedStatement.close();
}
catch (SQLException sqle) {}
}
return resultSet;
} // end executeQuery
// ---------------------------------------------------------- getColumn
/**
* Merges a SQL command with an array of parameters
* and returns a column from the first record of the result set as
* an Object.
* If an empty set results, null is returned.
* Any number or no parameters may be passed.
* The parameters parameter may also be null.
* The SQL Statement/ResultSet are handled by
* <code>ExecuteQuery()</code>.
* The ResultSet is converted to a collection using
* <code>ResultSetUtils.getCollection(Object,ResultSet)</code>.
* The ResultSet is released, and the Collection returned.
*
* @param resource The database resource key or null for default
* @param column The column to return from the result set
* @param command The SQL statement to prepare and execute.
* @param parameters The replaceable parameters to use with command.
* @exception SQLException if SQL error occurs
*/
public static final Object getColumn(
String resource,
int column,
String command,
Object[] parameters)
throws SQLException {
Object result = null;
Connection connection = null;
ResultSet resultSet = null;
try {
connection =
ConnectionAdaptor.getPool().getConnection(resource);
resultSet = executeQuery(connection,command,parameters);
if (resultSet.next()) {
result = resultSet.getObject(column);
}
}
finally {
try {
if (resultSet!=null) resultSet.close();
if (connection!=null) connection.close();
}
catch (SQLException sqle) {
// do nothing
}
}
return result;
} // end getColumn
/**
* Convenience method for calling
* <code>getColumn(String,int,String,Object[]);</code>
* with a single object parameter.
*
* @param resource The database resource key or null for default
* @param column The column to return from the result set.
* @param command The SQL statement to prepare and execute.
* @param key The replaceable parameter to use with LIKE.
* @exception SQLException if SQL error occurs
*/
public static final Object getColumn(
String resource,
int column,
String command,
Object key)
throws SQLException {
Object[] parameters = new Object[1];
parameters[0] = key;
return getColumn(resource,column,command,parameters);
} // end getColumn
/**
* Convenience method for calling
* <code>getColumn(String,Object,String,Object[]);</code>
*
* with a single int parameter.
* @param resource The database resource key or null for default
* @param column The column to return from the result set.
* @param command The SQL statement to prepare and execute.
* @param key The replaceable parameter to use with LIKE.
* @exception SQLException if SQL error occurs
*/
public static final Object getColumn(
String resource,
int column,
String command,
int key)
throws SQLException {
Object[] parameters = new Object[1];
parameters[0] = new Integer(key);
return getColumn(resource,column,command,parameters);
} // end getColumn
/**
* Convenience method for calling
* <code>getColumn(String,Object,String,Object[]);</code>
* without a parameter list.
*
* @param resource The database resource key or null for default
* @param column The column to return from the result set.
* @param command The SQL statement to prepare and execute.
* @param key The replaceable parameter to use with LIKE.
* @exception SQLException if SQL error occurs
*/
public static final Object getColumn(
String resource,
int column,
String command)
throws SQLException {
return getColumn(resource,column,command,null);
} // end getColumn
// ------------------------------------------------------ getElement
/**
* Merges a SQL command with an array of parameters.
* Any number or no parameters may be passed.
* The parameters parameter may also be null.
* The SQL Statement/ResultSet are handled by
* <code>ExecuteQuery()</code>.
* The first record of the ResultSet is used to populate
* <code>ResultSetUtils.getElement(Object,ResultSet)</code>.
* The ResultSet is released, and the bean returned.
*
* @param resource The database resource key or null for default
* @param target The JavaBean object to populate.
* @param command The SQL statement to prepare and execute.
* @param parameters The replaceable parameters to use with
* command.
* @exception SQLException if SQL error occurs
* @returns True if element is found
*/
public static final boolean getElement(
String resource,
Object target,
String command,
Object[] parameters)
throws SQLException {
Object collection = null;
Connection connection = null;
ResultSet resultSet = null;
boolean found = false;
try {
connection =
ConnectionAdaptor.getPool().getConnection(resource);
resultSet = executeQuery(connection,command,parameters);
found = ResultSetUtils.getElement(target,resultSet);
}
finally {
try {
if (resultSet!=null) resultSet.close();
if (connection!=null) connection.close();
}
catch (SQLException sqle) {
// do nothing
}
}
return found;
} // end getElement
/**
* Convenience method for calling
* <code>getElement(String,Object,String,Object[]);</code>
* with a single object parameter.
*
* @param resource The database resource key or null for default
* @param target The JavaBean object to populate.
* @param command The SQL statement to prepare and execute.
* @param key The replaceable parameter to use with LIKE.
* @exception SQLException if SQL error occurs
* @returns True if element is found
*/
public static final boolean getElement(
String resource,
Object target,
String command,
Object key)
throws SQLException {
Object[] parameters = new Object[1];
parameters[0] = key;
return getElement(resource,target,command,parameters);
} // end getElement
/**
* Convenience method for calling
* <code>getElement(String,Object,String,Object[]);</code>
* with a single int parameter.
*
* @param resource The database resource key or null for default
* @param target The JavaBean object to populate.
* @param command The SQL statement to prepare and execute.
* @param key The replaceable parameter to use with LIKE.
* @exception SQLException if SQL error occurs
* @returns True if element is found
*/
public static final boolean getElement(
String resource,
Object target,
String command,
int key)
throws SQLException {
Object[] parameters = new Object[1];
parameters[0] = new Integer(key);
return getElement(resource,target,command,parameters);
} // end getElement
/**
* Convenience method for calling
* <code>getElement(String,Object,String,Object[]);</code>
* without a parameter list.
*
* @param resource The database resource key or null for default
* @param target The JavaBean object to populate.
* @param command The SQL statement to prepare and execute.
* @param key The replaceable parameter to use with LIKE.
* @exception SQLException if SQL error occurs
* @returns True if element is found
*/
public static final boolean getElement(
String resource,
Object target,
String command)
throws SQLException {
return getElement(resource,target,command,null);
} // end getElement
// ------------------------------------------------------ getCollection
/**
* Merges a SQL command with an array of parameters.
* Any number or no parameters may be passed.
* The parameters parameter may also be null.
* The SQL Statement/ResultSet are handled by
* <code>ExecuteQuery()</code>.
* The ResultSet is converted to a collection using
* <code>ResultSetUtils.getCollection(Object,ResultSet)</code>.
* The ResultSet is released, and the Collection returned.
*
* @param resource The database resource key or null for default
* @param target The JavaBean object to return in the collection.
* @param command The SQL statement to prepare and execute.
* @param parameters The replaceable parameters to use with command.
* @exception SQLException if SQL error occurs
*/
public static final Collection getCollection(
String resource,
Object target,
String command,
Object[] parameters)
throws SQLException {
Object collection = null;
Connection connection = null;
ResultSet resultSet = null;
try {
connection =
ConnectionAdaptor.getPool().getConnection(resource);
resultSet = executeQuery(connection,command,parameters);
collection = ResultSetUtils.getCollection(target,resultSet);
}
finally {
try {
if (resultSet!=null) resultSet.close();
if (connection!=null) connection.close();
}
catch (SQLException sqle) {
// do nothing
}
}
return (Collection) collection;
} // end getCollection
/**
* Convenience method for calling
* <code>getCollection(String,Object,String,Object[]);</code>
* with a single object parameter.
*
* @param resource The database resource key or null for default
* @param target The JavaBean object to return in the collection.
* @param command The SQL statement to prepare and execute.
* @param key The replaceable parameter to use with LIKE.
* @exception SQLException if SQL error occurs
*/
public static final Collection getCollection(
String resource,
Object target,
String command,
Object key)
throws SQLException {
Object[] parameters = new Object[1];
parameters[0] = key;
return getCollection(resource,target,command,parameters);
} // end getCollection
/**
* Convenience method for calling
* <code>getCollection(String,Object,String,Object[]);</code>
* with a single int parameter.
*
* @param resource The database resource key or null for default
* @param target The JavaBean object to return in the collection.
* @param command The SQL statement to prepare and execute.
* @param key The replaceable parameter to use with LIKE.
* @exception SQLException if SQL error occurs
*/
public static final Collection getCollection(
String resource,
Object target,
String command,
int key)
throws SQLException {
Object[] parameters = new Object[1];
parameters[0] = new Integer(key);
return getCollection(resource,target,command,parameters);
} // end getCollection
/**
* Convenience method for calling
* <code>getCollection(String,Object,String,Object[]);</code>
* without a parameter list.
*
* @param resource The database resource key or null for default
* @param target The JavaBean object to return in the collection.
* @param command The SQL statement to prepare and execute.
* @param key The replaceable parameter to use with LIKE.
* @exception SQLException if SQL error occurs
*/
public static final Collection getCollection(
String resource,
Object target,
String command)
throws SQLException {
return getCollection(resource,target,command,null);
} // end getCollection
/**
* Convenience method to wrap a string for a command that
* uses the <code>LIKE</code> operator.
* Calls <code>getCollection(String,Object,String,Object[]);</code>
*
* @param resource The database resource key or null for default
* @param target The JavaBean object to return in the collection.
* @param command The SQL statement to prepare and execute.
* @param key The replaceable parameter to use with LIKE.
* @exception SQLException if SQL error occurs
*/
public static final Collection getCollectionLike(
String resource,
Object target,
String command,
String key)
throws SQLException {
Object[] parameters = new Object[1];
parameters[0] = new String("%" + key + "%");
return getCollection(resource,target,command,parameters);
} // end getCollectionLike
} // end StatementUtils
/*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
1.1 jakarta-commons-sandbox/scaffold/src/java/org/apache/commons/scaffold/sql/ServletAdaptor.java
Index: ServletAdaptor.java
===================================================================
package org.apache.commons.scaffold.sql;
import java.sql.Connection;
import java.sql.SQLException;
import javax.servlet.http.HttpServlet;
import javax.sql.DataSource;
/**
* Connection adaptor for a connection pool that is exposed
* through the servlet context, like the Struts generic
* connection pool.
* <p>
* The ConnectionServlet will automatically set a reference
* to itself if an instance of this class is specified
* as the ConnectionAdaptor.
*
* @author Ted Husted
* @version $Revision: 1.1 $ $Date: 2002/08/14 17:51:42 $
*/
public class ServletAdaptor extends ConnectionAdaptor {
/**
* Field to store a link to a servlet in the application.
*/
private static HttpServlet servlet = null;
/**
* Set a reference to a servlet in the application
* to allow access to the servlet context.
*/
public void setServlet(HttpServlet servlet) {
this.servlet = servlet;
}
/**
* Return datasource from the servlet context using
* key as the attribute name.
*
* @param key The attribute name for the resource.
* If null is passed, null is returned.
* @returns null or the datasource object related to "key"
*/
protected DataSource getDataSource(String key)
throws SQLException {
if (null==key) return null;
return (DataSource)
servlet.getServletContext().getAttribute(key);
}
// Required
public ServletAdaptor() {
if (null==pool) pool = this;
}
} // end ServletAdaptor
/*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Scaffold", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
1.1 jakarta-commons-sandbox/scaffold/src/java/org/apache/commons/scaffold/sql/RowSetUtils.java.text
Index: RowSetUtils.java.text
===================================================================
// FOR LATER DEVELOPMENT
package org.apache.commons.scaffold.sql;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import javax.naming.NamingException;
import javax.sql.RowSet;
import sun.jdbc.rowset.CachedRowSet;
import java.util.Date;
// import java.sql.Timestamp;
/**
* RowSet utilities.
* These accept any parameters as an array of objects, and can be used
* with any arbitrary SQL command.
* The base RowSet type is used where possible, but the implementation
* uses CachedRowSets throughout.
* To be used as parameters. native types (int, float, ...) must be
* placed in their object wrappers.
* Most of the methods here are convenience signatures that pass the
* parameters along to a key method.
* When a maxRow is not given, the MAX_ROW value of 100 is used.
* The connection is obtained from the ConnectionPool class in this
* package.
* The code could be modified to use a JNDI datasource instead;
* see commented-out portions.
*
* @author Ted Husted
* @version $Revision: 1.1 $ $Date: 2002/08/14 17:51:42 $
*/
public final class RowSetUtils {
/**
* Key if pool exposes datasource.
*/
private static final String JNDI_NAME_KEY = "DATASOURCE";
/**
* Access or JNDI key
*/
public static String getJndiNameKey() {
return JNDI_NAME_KEY;
}
/**
* Maximum numbers to return if not give.
*/
private static final int MAX_ROWS = 100;
/**
* Max rows accessor,
*/
public static int getMaxRows() {
return MAX_ROWS;
}
/**
* Execute command returning a CachedRowSet with up to maxRows.
*/
public static final RowSet getRowSet(int maxRows, String command)
throws SQLException {
CachedRowSet crs = new CachedRowSet();
crs.setCommand(command);
crs.setMaxRows(maxRows);
// crs.setDataSourceName(JNDI_NAME_KEY);
crs.execute(ConnectionPool.getConnection());
return crs;
}
/**
* Execute command returning a CachedRowSet.
* The maximum number of rows is determined by getMaxRows().
*/
public static final RowSet getRowSet(String command)
throws SQLException {
return getRowSet(getMaxRows(),command);
}
/**
* Execute command returning the CachedRowSet with up to maxRows.
*/
public static final RowSet getRowSet(int maxRows,
CachedRowSet crs) throws SQLException {
crs.setMaxRows(maxRows);
// crs.setDataSourceName(JNDI_NAME_KEY);
crs.execute(ConnectionPool.getConnection());
return crs;
}
/**
* Merge parameters, execute command, and return CachedRowSet.
* maxRows is used to limit the maximum rows returned.
*/
public static final RowSet getObjects(int maxRows,
String command, Object[] parameters) throws SQLException {
if (parameters==null) {
return getRowSet(maxRows,command);
}
CachedRowSet crs = new CachedRowSet();
crs.setCommand(command);
for (int i=0; i<parameters.length; i++) {
crs.setObject(i+1, parameters[i]);
}
return getRowSet(maxRows,crs);
}
/**
* Merge parameter, execute command, and return CachedRowSet.
* maxRows is used to limit the maximum rows returned.
*/
public static final RowSet getObject(int maxRows,
String command, Object parameter) throws SQLException {
if (parameter==null) {
return getObjects(maxRows, command, null);
}
Object[] parameters = new Object[1];
parameters[0] = parameter;
return getObjects(maxRows, command, parameters);
}
/**
* Merge parameters, execute commentd, and return CachedRowSet.
* getMaxRows() is used to determine the maximum rows returned.
*/
public static final RowSet getObjects(String command,
Object[] parameters) throws SQLException {
return getObjects(getMaxRows(),command,parameters);
}
/**
* Merge parameter, execute commentd, and return CachedRowSet.
* getMaxRows() is used to determine the maximum rows returned.
*/
public static final RowSet getObject(String command,
Object parameter) throws SQLException {
return getObject(getMaxRows(),command,parameter);
}
// ===== THE BALANCE OF THIS PACKAGE IS EXPERIMENTAL AND MAY NOT WORK =====
/**
* Update database from CachedRowSet.
*/
public static final RowSet setRowSet(CachedRowSet crs)
throws SQLException {
// crs.setDataSourceName(JNDI_NAME_KEY);
crs.updateRow();
crs.acceptChanges(ConnectionPool.getConnection());
return crs;
}
/**
* Merge parameters and update database from RowSet.
*/
public static final RowSet setObjects(String command,
Object[] parameters) throws SQLException {
CachedRowSet crs = new CachedRowSet();
crs.setCommand(command);
for (int i=0; i<parameters.length; i++) {
crs.setObject(i, parameters[i]);
}
return setRowSet(crs);
}
/**
* Merge parameter and update database from RowSet.
*/
public static final RowSet setObject(String command,
Object parameter) throws SQLException {
Object[] parameters = new Object[1];
parameters[0] = parameter;
return setObjects(command, parameters);
}
} // end RowSets
/* -- Doesn't work with MySQL default tables; no transaction support.
public static final CachedRowSet getBidderKey(String lot, String account) throws SQLException {
CachedRowSet crs = new CachedRowSet();
crs.setTransactionIsolation(java.sql.Connection.TRANSACTION_NONE);
crs.setDataSourceName(Commands.JNDI_NAME_KEY);
crs.setCommand(Commands.BIDDER_KEY_ROWSET);
crs.setTableName("gavel_bid");
crs.setString(1,lot);
crs.setString(1,account);
crs.execute();
return crs;
}
CachedRowSet crs = new CachedRowSet();
crs.setDataSourceName("DATASOURCE");
crs.setCommand(getUpdateCommand());
crs.setTableName("contact");
crs.setString(1,"last_name");
crs.setString(2,"first_name");
crs.setString(3,"street");
crs.setString(4,"city");
crs.setString(5,"state");
crs.setString(6,"zip");
crs.setString(7,"phone");
crs.setString(8,"email");
crs.setString(9,"36");
crs.execute();
*/
/*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Scaffold", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
1.1 jakarta-commons-sandbox/scaffold/src/java/org/apache/commons/scaffold/sql/ResultSetUtils.java
Index: ResultSetUtils.java
===================================================================
package org.apache.commons.scaffold.sql;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
// import org.apache.commons.beanutils.BeanUtils; // Struts 1.1
// import org.apache.commons.beanutils.PropertyUtils; // Struts 1.1
import org.apache.struts.util.BeanUtils; // Struts 1.0.x
import org.apache.struts.util.PropertyUtils; // Struts 1.0.x
/**
* General purpose utility methods related to ResultSets
*
* @author Ted Husted
* @version $Revision: 1.1 $ $Date: 2002/08/14 17:51:42 $
*/
public class ResultSetUtils {
/**
* Returns next record of result set as a Map.
* The keys of the map are the column names,
* as returned by the metadata.
* The values are the columns as Objects.
*
* @param resultSet The ResultSet to process.
* @exception SQLException if an error occurs.
*/
public static Map getMap(ResultSet resultSet)
throws SQLException {
// Acquire resultSet MetaData
ResultSetMetaData metaData = resultSet.getMetaData();
int cols = metaData.getColumnCount();
// Create hashmap, sized to number of columns
HashMap row = new HashMap(cols,1);
// Transfer record into hashmap
if (resultSet.next()) {
for (int i=1; i<=cols ; i++) {
row.put(metaData.getColumnName(i),
resultSet.getObject(i));
}
} // end while
return ((Map) row);
} // end getMap
/**
* Return a Collection of Maps, each representing
* a row from the ResultSet.
* The keys of the map are the column names,
* as returned by the metadata.
* The values are the columns as Objects.
*
* @param resultSet The ResultSet to process.
* @exception SQLException if an error occurs.
*/
public static Collection getMaps(ResultSet resultSet)
throws SQLException {
// Acquire resultSet MetaData
ResultSetMetaData metaData = resultSet.getMetaData();
int cols = metaData.getColumnCount();
// Use ArrayList to maintain ResultSet sequence
ArrayList list = new ArrayList();
// Scroll to each record, make map of row, add to list
while (resultSet.next()) {
HashMap row = new HashMap(cols,1);
for (int i=1; i<=cols ; i++) {
row.put(metaData.getColumnName(i),
resultSet.getString(i));
}
list.add(row);
} // end while
return ((Collection) list);
} // end getMaps
/**
* Populate the JavaBean properties of the specified bean, based on
* the specified name/value pairs. This method uses Java reflection APIs
* to identify corresponding "property setter" method names. The type of
* the value in the Map must match the setter type. The setter must
* expect a single arguement (the one on the Map).
* <p>
* The particular setter method to be called for each property is
* determined using the usual JavaBeans introspection mechanisms. Thus,
* you may identify custom setter methods using a BeanInfo class that is
* associated with the class of the bean itself. If no such BeanInfo
* class is available, the standard method name conversion ("set" plus
* the capitalized name of the property in question) is used.
* <p>
* <strong>NOTE</strong>: It is contrary to the JavaBeans Specification
* to have more than one setter method (with different argument
* signatures) for the same property.
* <p>
* This method adopted from the Jakarta Commons BeanUtils.populate.
*
* @author Craig R. McClanahan
* @author Ralph Schaer
* @author Chris Audley
* @author Rey Fran�ois
* @author Gregor Ra�man
* @author Ted Husted
*
* @param bean JavaBean whose properties are being populated
* @param properties Map keyed by property name, with the
* corresponding value to be set
*
* @exception IllegalAccessException if the caller does not have
* access to the property accessor method
* @exception InvocationTargetException if the property accessor method
* throws an exception
*/
public static void setProperties(Object bean, Map properties)
throws IllegalAccessException, InvocationTargetException {
if ((bean == null) || (properties == null))
return;
/*
if (debug >= 1)
System.out.println("BeanUtils.populate(" + bean + ", " +
properties + ")");
*/
// Loop through the property name/value pairs to be set
Iterator names = properties.keySet().iterator();
while (names.hasNext()) {
// Identify the property name and value(s) to be assigned
String name = (String) names.next();
if (name == null)
continue;
// Get the property descriptor of the requested property (if any)
PropertyDescriptor descriptor = null;
try {
descriptor = PropertyUtils.getPropertyDescriptor(bean, name);
} catch (Throwable t) {
/*
if (debug >= 1)
System.out.println(" getPropertyDescriptor: " + t);
*/
descriptor = null;
}
if (descriptor == null) {
/*
if (debug >= 1)
System.out.println(" No such property, skipping");
*/
continue;
}
/*
if (debug >= 1)
System.out.println(" Property descriptor is '" +
descriptor + "'");
*/
// Identify the relevant setter method (if there is one)
Method setter = descriptor.getWriteMethod();
if (setter == null) {
/*
if (debug >= 1)
System.out.println(" No setter method, skipping");
*/
continue;
}
// Obtain value to be set
Object[] args = new Object[1];
args[0] = properties.get(name); // This MUST match setter type
/*
if (debug >= 1)
System.out.println(" name='" + name + "', value.class='" +
(value == null ? "NONE" :
value.getClass().getName()) + "'");
*/
/*
if (debug >= 1)
System.out.println(" Setting to " +
(parameters[0] == null ? "NULL" :
"'" + parameters[0] + "'"));
*/
// Invoke the setter method
setter.invoke(bean,args);
}
/*
if (debug >= 1)
System.out.println("============================================");
*/
} // end setProperties
/**
* Map JDBC objects to Java equivalents.
* Used by getBean() and getBeans().
* <p>
* Some types not supported.
* Many not work with all drivers.
* <p>
* Makes binary conversions of BIGINT, DATE, DECIMAL, DOUBLE, FLOAT, INTEGER,
* REAL, SMALLINT, TIME, TIMESTAMP, TINYINT.
* Makes Sting conversions of CHAR, CLOB, VARCHAR, LONGVARCHAR, BLOB, LONGVARBINARY,
* VARBINARY.
* <p>
* DECIMAL, INTEGER, SMALLINT, TIMESTAMP, CHAR, VARCHAR tested with MySQL and Poolman.
* Others not guaranteed.
*/
public static void putEntry(
Map properties,
ResultSetMetaData metaData,
ResultSet resultSet,
int i)
throws SQLException {
/*
In a perfect universe, this would be enough
properties.put(
metaData.getColumnName(i),
resultSet.getObject(i));
But only String, Timestamp, and Integer seem to get through that way.
*/
String columnName = metaData.getColumnName(i);
switch (metaData.getColumnType(i)) {
// http://java.sun.com/j2se/1.3.0/docs/api/java/sql/Types.html
case Types.BIGINT:
properties.put(columnName,
new Long(resultSet.getLong(i)));
break;
case Types.DATE:
properties.put(columnName,
resultSet.getDate(i));
break;
case Types.DECIMAL:
case Types.DOUBLE:
properties.put(columnName,
new Double(resultSet.getDouble(i)));
break;
case Types.FLOAT:
properties.put(columnName,
new Float(resultSet.getFloat(i)));
break;
case Types.INTEGER:
properties.put(columnName,
new Integer(resultSet.getInt(i)));
break;
case Types.REAL:
properties.put(columnName,
new Double(resultSet.getString(i)));
break;
case Types.SMALLINT:
properties.put(columnName,
new Short(resultSet.getShort(i)));
break;
case Types.TIME:
properties.put(columnName,
resultSet.getTime(i));
break;
case Types.TIMESTAMP:
properties.put(columnName,
resultSet.getTimestamp(i));
break;
// :FIXME: Throws java.lang.ClassCastException: java.lang.Integer
// :FIXME: with Poolman and MySQL unless use getString.
case Types.TINYINT:
properties.put(columnName,
new Byte(resultSet.getString(i)));
break;
case Types.CHAR:
case Types.CLOB:
case Types.VARCHAR:
case Types.LONGVARCHAR:
// :FIXME: Handle binaries differently?
case Types.BLOB:
case Types.LONGVARBINARY:
case Types.VARBINARY:
properties.put(columnName,
resultSet.getString(i));
break;
/*
:FIXME: Add handlers for
ARRAY
BINARY
BIT
DISTINCT
JAVA_OBJECT
NULL
NUMERIC
OTHER
REF
STRUCT
*/
// Otherwise, pass as *String property to be converted
default:
properties.put(columnName + "String",
resultSet.getString(i));
break;
} // end switch
} // end putEntry
/**
* Populate target bean with the first record from a ResultSet.
*
* @param resultSet The ResultSet whose parameters are to be used
* to populate bean properties
* @param target An instance of the bean to populate
* @exception SQLException if an exception is thrown while setting
* property values, populating the bean, or accessing the ResultSet
* @returns True if resultSet contained a next element
*/
public static boolean getElement(Object target, ResultSet resultSet)
throws SQLException {
// Check prerequisites
if ((target==null) || (resultSet==null))
throw new SQLException("getElement: Null parameter");
// Acquire resultSet MetaData
ResultSetMetaData metaData = resultSet.getMetaData();
int cols = metaData.getColumnCount();
// Create hashmap, sized to number of columns
HashMap properties = new HashMap(cols,1);
// Scroll to next record and pump into hashmap
boolean found = false;
if (resultSet.next()) {
found = true;
for (int i=1; i<=cols ; i++) {
putEntry(properties,metaData,resultSet,i);
}
try {
setProperties(target,properties);
}
catch (Exception e) {
throw new SQLException("ResultSetUtils.getElement: " +
e.getMessage() + properties.toString());
}
} // end if
return found;
} // end getElement
/**
* Return a ArrayList of beans populated from a ResultSet.
*
* @param resultSet The ResultSet whose parameters are to be used
* to populate bean properties
* @param target An instance of the bean to populate
* @exception SQLException if an exception is thrown while setting
* property values, populating the bean, or accessing the ResultSet
*/
public static Collection getCollection(Object target, ResultSet resultSet)
throws SQLException {
// Check prerequisites
if ((target==null) || (resultSet==null))
throw new SQLException("getCollection: Null parameter");
// Acquire resultSet MetaData
ResultSetMetaData metaData = resultSet.getMetaData();
int cols = metaData.getColumnCount();
// Create hashmap, sized to number of columns
HashMap properties = new HashMap(cols,1);
// Use ArrayList to maintain ResultSet sequence
ArrayList list = new ArrayList();
// Acquire target class
Class factory = target.getClass();
// Scroll to next record and pump into hashmap
while (resultSet.next()) {
for (int i=1; i<=cols ; i++) {
putEntry(properties,metaData,resultSet,i);
}
try {
Object bean = factory.newInstance();
setProperties(bean,properties);
list.add(bean);
}
catch (Exception e) {
throw new SQLException("RequestUtils.getCollection: " +
e.getMessage());
}
properties.clear();
} // end while
return ((Collection) list);
} // end getCollection
} // end ResultSetUtils
/*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Scaffold", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
1.1 jakarta-commons-sandbox/scaffold/src/java/org/apache/commons/scaffold/sql/PoolmanAdaptor.java
Index: PoolmanAdaptor.java
===================================================================
package org.apache.commons.scaffold.sql;
/**
* ConnectionAdaptor for Poolman.
* <p>
* When an application initializes it should create an instance
* of this class to use Poolman for SQL connections.
*
* @author Ted Husted
* @version $Revision: 1.1 $ $Date: 2002/08/14 17:51:42 $
*/
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.codestudio.sql.PoolMan;
public class PoolmanAdaptor extends ConnectionAdaptor {
/**
* An exception message to throw if poolman returns null.
*/
private static final String POOLMAN_MESSAGE = "Connection pool " +
"not available. Check your poolman.xml config, and be sure " +
"you are using a valid dbname parameter (use dbname, not jndiName)";
// Inherits JavaDoc
protected DataSource getDataSource(String key)
throws SQLException {
if (null==key) return null;
return PoolMan.findDataSource(key);
}
// Required
public PoolmanAdaptor() {
setMessage(POOLMAN_MESSAGE);
if (null==pool) pool = this;
}
} // end PoolmanAdaptor
/*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Scaffold", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
1.1 jakarta-commons-sandbox/scaffold/src/java/org/apache/commons/scaffold/sql/ConnectionAdaptor.java
Index: ConnectionAdaptor.java
===================================================================
package org.apache.commons.scaffold.sql;
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
/**
* Base class for SQL connection adaptors. May be used as-is or subclassed.
* <p>
* This object does not provide any type of connection pooling.
* It simply provides a standard means for obtaining a connection
* whatever connection pool your application needs.
* Scaffold classes in the SQL package call this object internally.
* <p>
* To use as-is, a DataSource compliant connection pool must be
* available as "DATA_SOURCE" via JNDI. A subclass can
* locate the pool under any name by any means necessary.
*<p>
* A <code>ConnectionAdaptor</code> can be instantiated once at
* start-up, either from main() or via a servlet, like the
* Scaffold ConnectionServlet.
* Objects needing a connection can then call the static
* method
* <code>ConnectionAdaptor.getPool().getConnection()</code>.
* <p>
* Most implementations will expect callers to use and
* close the connections promptly, since they would
* usually be part of a pool.
* <p>
* Subclasses can provide their own resource name or
* getConnection() method, and a new constructor to
* set the protected pool field to their own
* instance. See <code>PoolmanAdaptor</code> for an example.
*
* @see org.apache.commons.scaffold.http.ConnectionServlet
* @see org.apache.commons.scaffold.sql.PoolmanAdaptor
* @author Ted Husted
* @version $Revision: 1.1 $ $Date: 2002/08/14 17:51:42 $
*/
public class ConnectionAdaptor {
// ------------------------------------------------------------ message
/**
* A message for an exception if pool returns null.
*/
private String message = "Connection pool " +
"not available. Check your configuration.";
/**
* Return a message for an exception if pool returns null.
*
* @return Message for an exception if pool returns null
*/
protected String getMessage() {
return this.message;
}
/**
* Set a message for an exception if pool returns null.
* Adaptor subclasses can call this from their constructor.
*
* @param Message The message for an exception if pool returns null
*/
protected void setMessage(String message) {
this.message = message;
}
// ---------------------------------------------------------------- key
/**
* The default DataSource name.
*/
public static final String DATA_SOURCE_KEY = "DATA_SOURCE";
/**
* The default JNDI context for applications.
*/
public static final String JNDI_CONTEXT_KEY = "java:comp/env";
/**
* The attribute under which our DataSource is stored
* [DATA_SOURCE_KEY].
*/
private String key = DATA_SOURCE_KEY;
/**
* Return the attribute under which our datasource is stored.
* Subclasses may override this method to provide a different key,
* or set a new key at construction.
*/
public String getKey() {
return this.key;
}
/**
* The attribute under which our datasource is stored.
* Adaptor subclasses can call this method from a constructor
* to change the default resource name.
*/
public void setKey(String key) {
this.key = key;
}
// --------------------------------------------------------- datasource
/**
* Field to store singleton reference to default datasource.
*
* @todo Add Map to store reference to other datasoruces.
*/
protected static DataSource datasource;
/**
* Return datasource using JNDI lookup. Subclasses may
* override this method to provide other means of obtaining
* a datasource reference.
*
* @param key The attribute name for the resource.
* If null is passed, null is returned.
* @returns null or the datasource object related to "key"
*
* @todo Add cache to store references to the datasources by key.
*/
protected DataSource getDataSource(String key)
throws SQLException {
if (null==key) return null;
try {
Context env = (Context) new
InitialContext().lookup(JNDI_CONTEXT_KEY);
return (DataSource) env.lookup(key);
}
catch (NamingException ne) {
// Recast naming exception,
// since that is what other routines only except
// and because another implementation may not generate this.
// Should only be an issue during initial setup
throw new SQLException(ne.getMessage());
}
} // end getDataSource
// --------------------------------------------------------- connection
/**
* Returns a JDBC connection from the default resource.
* Calls <code>getDatasource</code> to return the resource
* associated with the default attribute name [getKey()].
* <p>
* The default datasource object is cached and reused in subsequent
* calls.
*
* @returns JDBC connection from resource layer.
* @exception SQLException on SQL or other errors. May wrap other
* exceptions depending on implementation. Will not return null.
*/
public Connection getConnection() throws SQLException {
if (null==datasource) {
datasource = getDataSource(getKey());
if (null==datasource)
throw new SQLException(getMessage());
}
return (datasource.getConnection());
} // end getConnection
/**
* Returns a JDBC connection from a connection pool or other
* named resource, to be used and closed promptly.
* <p>
* Default implementation uses JNDI to lookup the resource named by
* getResource() ["DATASOURCE"].
* Will not return null.
*
* @returns JDBC connection from resource layer.
* @exception SQLException on SQL or other errors. May wrap
* other exceptions depending on implementation.
* @param resource An attribute name for the resource to use for
* this connection or null to call getResource()
* @return A working connection; will not return null
* @exception SQLException On any SQL error or if pool returns null
*/
public Connection getConnection(String key)
throws SQLException {
if (null==key) return getConnection();
DataSource ds = getDataSource(key);
if (null==ds)
throw new SQLException(getMessage());
return (ds.getConnection());
} // end getConnection
// --------------------------------------------------------------- pool
/**
* Field to store singleton reference to adaptor pool.
* This would usually be private for a singleton,
* but adaptor subclasses may set the pool upon initialization.
* <p>
* <code>if (null==pool) set pool = this</code>.
*/
protected static ConnectionAdaptor pool;
/**
* Return adaptor instance to use in acquiring connection.
* <p>
* This is the main entry method to the object.
* Client's should call:<br>
* <code>Adaptor.getPool().getConnection()</code>
* to acquire a connection from the default pool.
*/
public static ConnectionAdaptor getPool() {
if (null==pool) pool = new ConnectionAdaptor();
return pool;
} // end getPool
} // end ConnectionAdaptor
/*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Scaffold", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
1.1 jakarta-commons-sandbox/scaffold/src/java/org/apache/commons/scaffold/sql/CommandStore.java
Index: CommandStore.java
===================================================================
package org.apache.commons.scaffold.util;
import java.util.Properties;
import org.apache.commons.scaffold.lang.PropertiesException;
/**
* @author Ted Husted
* @author OK State DEQ
* @version $Revision: 1.1 $ $Date: 2002/08/14 17:51:42 $
*/
public class CommandStore {
/**
* The path to a default properties file if not given in the constructor
* ["resources/command.properties"].
*/
private static String COMMAND_STORE_PATH = "resources/command.properties";
private static String DOT = ".";
/**
* Our Properties field.
* :TODO: refactor to use Collection based on preface.
*/
protected static Properties properties;
public static Properties getProperties(String preface) {
if (null==properties) {
try {
properties = ResourceUtils.loadProperties(COMMAND_STORE_PATH);
}
catch (Exception e) {
throw new IllegalArgumentException();
}
}
if (null==properties) throw new IllegalArgumentException();
return properties;
}
/**
* Retrieve command from Properties store for <code>preface</code>
* and <code>key</code>.
*
* @fixme Could use a merge feature to reuse common substrings,
* like table names ["SELECT ${searchFields} FROM ${articleTable}"]
*/
public static String getProperty(String preface, String key)
throws PropertiesException {
if (null==properties) properties = getProperties(preface);
// :TODO: refactor to make appending preface.key optional
StringBuffer sb = new StringBuffer(preface);
sb.append(DOT);
sb.append(key);
return properties.getProperty(sb.toString());
}
/**
* Constructor to pass a properties file.
* Store instance in application scope.
*/
public CommandStore(Properties properties) {
this.properties = properties;
}
}
1.1 jakarta-commons-sandbox/scaffold/src/java/org/apache/commons/scaffold/sql/AccessBase.java
Index: AccessBase.java
===================================================================
package org.apache.commons.scaffold.sql;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Properties;
import org.apache.commons.scaffold.lang.ParameterException;
import org.apache.commons.scaffold.lang.PopulateException;
import org.apache.commons.scaffold.lang.PropertiesException;
import org.apache.commons.scaffold.lang.ResourceException;
import org.apache.commons.scaffold.lucene.SearchUtils;
import org.apache.commons.scaffold.lucene.Engine;
import org.apache.commons.scaffold.sql.StatementUtils;
/**
* Common data access methods.
*
* @author Ted Husted
* @author OK State DEQ
* @version $Revision: 1.1 $ $Date: 2002/08/14 17:51:42 $
*/
public class AccessBase {
/**
* [:TODO: Javadoc]
*/
public static String KEYS_NEXT = "keys.next";
/**
* [:TODO: Javadoc]
*/
public static String KEYS_INC = "keys.inc";
// ----------------------------------------------------------- Commands
/**
* Our command string properties.
* Can be loaded from an external properties file at startup.
*/
private static Properties commands;
/**
* Retrieve command from <code>commands</code> Properties for
* <code>key</code>.
*
* @fixme Could use a merge feature to reuse common substrings,
* like table names ["SELECT ${searchFields} FROM ${articleTable}"]
*/
public static final String getCommand(String key)
throws PropertiesException {
// MissingResourceException ?
if (null==commands) throw new PropertiesException();
return commands.getProperty(key);
}
/**
* Configure the data access system.
* <p>
* This method sets up the SQL connection pool adaptor.
* A new adaptor can be used by changing this method.
* This can be called once by main or servlet.init at startup.
*/
public static final void init(Properties _commands) {
if (null==commands) commands = _commands;
}
// ================================================================ API
// ----------------------------------------------------- Create Methods
/**
* Lookup command and execute "update" query to create a table,
* seed it with data, et cetera.
* <p>
* @param command Name of command to execute
* @exception Resource exception if data access error occurs
* @author Ted Husted
* @version $Revision: 1.1 $ $Date: 2002/08/14 17:51:42 $
*/
public static final void executeUpdate(String command)
throws ResourceException {
try {
int result = StatementUtils.executeUpdate(
null,getCommand(command));
}
catch (SQLException e) {
throw new ResourceException(e);
}
} // end createTables()
/**
* Returns next sequential key for given set of keys.
* Expects KEYS_NET nd KEYS_INC commands to be defined.
*
* @return A String representing the allocated key
* @exception ResourceException if data access error occurs
* @param keyName The name of the key set to use to generate the key
*/
public synchronized static final Integer createKey(String keyName)
throws ResourceException {
Object result = null;
try {
result = StatementUtils.createKey(
null,
1,
getCommand(KEYS_NEXT),
getCommand(keyName),
getCommand(KEYS_INC)
);
}
catch (SQLException e) {
throw new ResourceException(e);
}
return (Integer) result;
} // end createKey()
// -------------------------------------------------- Retrieval Methods
/**
* Retrieve entry from data storage.
* <p>
* @return Collection with record or empty collection
* @exception ResourceException if SQL error occurs
* @param key The primary key of the entry
* @param target Bean to hold copy of entry being retrieved
* @param command The name of the data access command
* collection
*/
public static boolean findElement(
Object target,
Object key,
String command) throws ResourceException {
boolean found = false;
try {
found = StatementUtils.getElement(null,target,
getCommand(command),key);
}
catch (SQLException e) {
throw new ResourceException(e);
}
return found;
} // end findElement
/**
* Retrieve a collection of beans from data stoarge.
* <p>
* @return Collection with entry or empty collection
* @exception throws PropertiesException, ResourceException
* if data access error occurs
* @param target Object to use as factory when populating
* @param command Name of the data access command
* collection
*/
public static final Collection findCollection(Object target,
String command) throws ResourceException {
try {
return StatementUtils.getCollection(null,
target,getCommand(command));
}
catch (SQLException e) {
throw new ResourceException(e);
}
} // end findCollection
/**
* Retrieve a collection of beans from data stoarge.
* <p>
* @return Collection with entry or empty collection
* @exception throws PropertiesException, ResourceException
* if data access error occurs
* @param target Object to use as factory when populating
* @param command Name of the data access command
* collection
* @param parameters An array of parameters to be used with command
*/
public static final Collection findCollection(Object target,
String command, Object[] parameters) throws ResourceException {
try {
return StatementUtils.getCollection(null,
target,getCommand(command),parameters);
}
catch (SQLException e) {
throw new ResourceException(e);
}
} // end findCollection
/**
* Retrieve a collection of beans from data stoarge.
* <p>
* @return Collection with entry or empty collection
* @exception throws PropertiesException, ResourceException
* if data access error occurs
* @param target Object to use as factory when populating
* @param command Name of the data access command
* collection
* @param parameter A String parameter to be used with command
*/
public static final Collection findCollection(Object target,
String command, Object parameter) throws ResourceException {
try {
return StatementUtils.getCollection(null,
target,getCommand(command),parameter);
}
catch (SQLException e) {
throw new ResourceException(e);
}
} // end findCollection
/**
* Retrieve a collection of beans from data stoarge.
* <p>
* @return Collection with entry or empty collection
* @exception throws PropertiesException, ResourceException
* if data access error occurs
* @param target Object to use as factory when populating
* @param command Name of the data access command
* collection
* @param parameter An int parameter to be used with command
*/
public static final Collection findCollection(Object target,
String command, int parameter) throws ResourceException {
return findCollection(target,command,new Integer(parameter));
} // end findCollection
/**
* Retrieve a collection of beans from data stoarge.
* <p>
* @return Collection with entry or empty collection
* @exception throws PropertiesException, ResourceException
* if data access error occurs
* @param target Object to use as factory when populating
* @param command Name of the data access command
* collection
* @param parameter A String parameter to be used with command
*/
public static final Collection findCollectionLike(Object target,
String command, String parameter) throws ResourceException {
try {
return StatementUtils.getCollectionLike(null,
target,getCommand(command),parameter);
}
catch (SQLException e) {
throw new ResourceException(e);
}
} // end findCollectionLike
/**
* Select entries from data storage by indexed property..
* <p>
* @return Collection with record or empty Collection
* @param value Term to match
* @param property Field to search
* @param target Object to use as factory when populating
* collection
* @exception Throws ParameterException if value is not a search
* term for property
* @exception Throws PopulateExecption if result cannot be set to
* target
* @exception throws PropertiesException, ResourceException is SQL, IO, or other
* data access error occurs.
*/
public static final Collection findByProperty(
Object target,
String property,
String value) throws ParameterException, PopulateException,
ResourceException {
return SearchUtils.getCollection(target,
Engine.getHits(
Engine.getQuery(value,property)));
} // end findByProperty
// -------------------------------------------------------- UD Methods
/**
* Commit record to storage.
* If create is true, entry is created.
* Otherwise, an existing entry is updated.
* @return 0 if fails
* @exception ResourceException if SQL error occurs
* @param insert True to insert, false to update.
* @insert The name of the insert command
* @update The name of the delete command
@ @parameters The parameters to use with either command
*
*/
public static final int store (
boolean isInsert,
String insert,
String update,
Object[] parameters) throws ResourceException {
String command = null;
if (isInsert) {
command = getCommand(insert);
}
else {
command = getCommand(update);
}
int result = 0;
try {
result = StatementUtils.executeUpdate(null,command,parameters);
}
catch (SQLException e) {
throw new ResourceException(e);
}
return result;
} // end store
/**
* Mark entry for deletion.
* Returns copy of entry before update in target parameter.
*
* @return 0 if fails
* @exception ResourceException if SQL or other data-access error occurs
* @exception runtime Null Pointer Exception if either parameter is null
* @param target Bean to hold copy of record being marked
* @param article Primary key of record to mark
*/
public static final int delete(Object target, Integer key, String command)
throws ResourceException {
int result = 0;
try {
// Mark as deleted
result = StatementUtils.executeUpdate(null,
getCommand(command),key);
}
catch (SQLException e) {
throw new ResourceException(e);
}
return result;
} // end delete
/**
* Unmark entry for deletion.
* Returns copy of restored entry in target parameter.
*
* @return 0 if fails
* @exception ResourceException if data access error occurs
* @param target Bean to hold copy of record being unmarked
* @param article Primary key of record to unmark
*/
public static final int restore(Object target, Integer key, String command)
throws ResourceException {
int result = 0;
try {
result = StatementUtils.executeUpdate(null,
getCommand(command),key);
}
catch (SQLException e) {
throw new ResourceException(e);
}
return result;
} // end restore
} // end Access
/*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this Collection of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this Collection of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
--
To unsubscribe, e-mail: <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>