FileDocCategorySizeDatePackage
JDBCTask.javaAPI DocApache Ant 1.7013311Wed Dec 13 06:16:24 GMT 2006org.apache.tools.ant.taskdefs

JDBCTask

public abstract class JDBCTask extends org.apache.tools.ant.Task
Handles JDBC configuration needed by SQL type tasks.

The following example class prints the contents of the first column of each row in TableName.

package examples;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.taskdefs.JDBCTask;

public class SQLExampleTask extends JDBCTask {

private String tableName;

public void execute() throws BuildException {
Connection conn = getConnection();
Statement stmt=null;
try {
if (tableName == null) {
throw new BuildException("TableName must be specified",location);
}
String sql = "SELECT * FROM "+tableName;
stmt= conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
log(rs.getObject(1).toString());
}
} catch (SQLException e) {

} finally {
if (stmt != null) {
try {stmt.close();}catch (SQLException ingore) {}
}
if (conn != null) {
try {conn.close();}catch (SQLException ingore) {}
}
}
}
public void setTableName(String tableName) {
this.tableName = tableName;
}

}


since
Ant 1.5

Fields Summary
private static Hashtable
loaderMap
Used for caching loaders / driver. This is to avoid getting an OutOfMemoryError when calling this task multiple times in a row.
private boolean
caching
private org.apache.tools.ant.types.Path
classpath
private org.apache.tools.ant.AntClassLoader
loader
private boolean
autocommit
Autocommit flag. Default value is false
private String
driver
DB driver.
private String
url
DB url.
private String
userId
User name.
private String
password
Password
private String
rdbms
RDBMS Product needed for this SQL.
private String
version
RDBMS Version needed for this SQL.
Constructors Summary
Methods Summary
public org.apache.tools.ant.types.PathcreateClasspath()
Add a path to the classpath for loading the driver.

return
a path to be configured

        if (this.classpath == null) {
            this.classpath = new Path(getProject());
        }
        return this.classpath.createPath();
    
public org.apache.tools.ant.types.PathgetClasspath()
Gets the classpath.

return
Returns a Path

        return classpath;
    
protected java.sql.ConnectiongetConnection()
Creates a new Connection as using the driver, url, userid and password specified. The calling method is responsible for closing the connection.

return
Connection the newly created connection.
throws
BuildException if the UserId/Password/Url is not set or there is no suitable driver or the driver fails to load.

        if (userId == null) {
            throw new BuildException("UserId attribute must be set!", getLocation());
        }
        if (password == null) {
            throw new BuildException("Password attribute must be set!", getLocation());
        }
        if (url == null) {
            throw new BuildException("Url attribute must be set!", getLocation());
        }
        try {

            log("connecting to " + getUrl(), Project.MSG_VERBOSE);
            Properties info = new Properties();
            info.put("user", getUserId());
            info.put("password", getPassword());
            Connection conn = getDriver().connect(getUrl(), info);

            if (conn == null) {
                // Driver doesn't understand the URL
                throw new SQLException("No suitable Driver for " + url);
            }

            conn.setAutoCommit(autocommit);
            return conn;
        } catch (SQLException e) {
            throw new BuildException(e, getLocation());
        }

    
private java.sql.DrivergetDriver()
Gets an instance of the required driver. Uses the ant class loader and the optionally the provided classpath.

return
Driver
throws
BuildException

        if (driver == null) {
            throw new BuildException("Driver attribute must be set!", getLocation());
        }

        Driver driverInstance = null;
        try {
            Class dc;
            if (classpath != null) {
                // check first that it is not already loaded otherwise
                // consecutive runs seems to end into an OutOfMemoryError
                // or it fails when there is a native library to load
                // several times.
                // this is far from being perfect but should work
                // in most cases.
                synchronized (loaderMap) {
                    if (caching) {
                        loader = (AntClassLoader) loaderMap.get(driver);
                    }
                    if (loader == null) {
                        log("Loading " + driver
                            + " using AntClassLoader with classpath "
                            + classpath, Project.MSG_VERBOSE);
                        loader = getProject().createClassLoader(classpath);
                        if (caching) {
                            loaderMap.put(driver, loader);
                        }
                    } else {
                        log("Loading " + driver
                            + " using a cached AntClassLoader.",
                                Project.MSG_VERBOSE);
                    }
                }
                dc = loader.loadClass(driver);
            } else {
                log("Loading " + driver + " using system loader.",
                    Project.MSG_VERBOSE);
                dc = Class.forName(driver);
            }
            driverInstance = (Driver) dc.newInstance();
        } catch (ClassNotFoundException e) {
            throw new BuildException(
                    "Class Not Found: JDBC driver " + driver + " could not be loaded",
                    e,
                    getLocation());
        } catch (IllegalAccessException e) {
            throw new BuildException(
                    "Illegal Access: JDBC driver " + driver + " could not be loaded",
                    e,
                    getLocation());
        } catch (InstantiationException e) {
            throw new BuildException(
                    "Instantiation Exception: JDBC driver " + driver + " could not be loaded",
                    e,
                    getLocation());
        }
        return driverInstance;
    
protected org.apache.tools.ant.AntClassLoadergetLoader()
Get the classloader used to create a driver.

return
the classloader

        return loader;
    
protected static java.util.HashtablegetLoaderMap()
Get the cache of loaders and drivers.

return
a hashtable

        return loaderMap;
    
public java.lang.StringgetPassword()
Gets the password.

return
Returns a String

        return password;
    
public java.lang.StringgetRdbms()
Gets the rdbms.

return
Returns a String

        return rdbms;
    
public java.lang.StringgetUrl()
Gets the url.

return
Returns a String

        return url;
    
public java.lang.StringgetUserId()
Gets the userId.

return
Returns a String

        return userId;
    
public java.lang.StringgetVersion()
Gets the version.

return
Returns a String

        return version;
    
public booleanisAutocommit()
Gets the autocommit.

return
Returns a boolean

        return autocommit;
    
public voidisCaching(boolean value)
Set the caching attribute.

param
value a boolean value

        caching = value;
    
protected booleanisValidRdbms(java.sql.Connection conn)
Verify we are connected to the correct RDBMS

param
conn the jdbc connection
return
true if we are connected to the correct RDBMS

        if (rdbms == null && version == null) {
            return true;
        }

        try {
            DatabaseMetaData dmd = conn.getMetaData();

            if (rdbms != null) {
                String theVendor = dmd.getDatabaseProductName().toLowerCase();

                log("RDBMS = " + theVendor, Project.MSG_VERBOSE);
                if (theVendor == null || theVendor.indexOf(rdbms) < 0) {
                    log("Not the required RDBMS: " + rdbms, Project.MSG_VERBOSE);
                    return false;
                }
            }

            if (version != null) {
                String theVersion = dmd.getDatabaseProductVersion().toLowerCase(Locale.ENGLISH);

                log("Version = " + theVersion, Project.MSG_VERBOSE);
                if (theVersion == null
                        || !(theVersion.startsWith(version)
                        || theVersion.indexOf(" " + version) >= 0)) {
                    log("Not the required version: \"" + version + "\"", Project.MSG_VERBOSE);
                    return false;
                }
            }
        } catch (SQLException e) {
            // Could not get the required information
            log("Failed to obtain required RDBMS information", Project.MSG_ERR);
            return false;
        }

        return true;
    
public voidsetAutocommit(boolean autocommit)
Auto commit flag for database connection; optional, default false.

param
autocommit The autocommit to set

        this.autocommit = autocommit;
    
public voidsetCaching(boolean enable)
Caching loaders / driver. This is to avoid getting an OutOfMemoryError when calling this task multiple times in a row; default: true

param
enable a boolean value

        caching = enable;
    
public voidsetClasspath(org.apache.tools.ant.types.Path classpath)
Sets the classpath for loading the driver.

param
classpath The classpath to set


                      
        
        this.classpath = classpath;
    
public voidsetClasspathRef(org.apache.tools.ant.types.Reference r)
Set the classpath for loading the driver using the classpath reference.

param
r a reference to a classpath

        createClasspath().setRefid(r);
    
public voidsetDriver(java.lang.String driver)
Class name of the JDBC driver; required.

param
driver The driver to set

        this.driver = driver.trim();
    
public voidsetPassword(java.lang.String password)
Sets the password; required.

param
password The password to set

        this.password = password;
    
public voidsetRdbms(java.lang.String rdbms)
Execute task only if the lower case product name of the DB matches this

param
rdbms The rdbms to set

        this.rdbms = rdbms;
    
public voidsetUrl(java.lang.String url)
Sets the database connection URL; required.

param
url The url to set

        this.url = url;
    
public voidsetUserid(java.lang.String userId)
Set the user name for the connection; required.

param
userId The userId to set

        this.userId = userId;
    
public voidsetVersion(java.lang.String version)
Sets the version string, execute task only if rdbms version match; optional.

param
version The version to set

        this.version = version;