Example usage for java.sql SQLException initCause

List of usage examples for java.sql SQLException initCause

Introduction

In this page you can find the example usage for java.sql SQLException initCause.

Prototype

public synchronized Throwable initCause(Throwable cause) 

Source Link

Document

Initializes the cause of this throwable to the specified value.

Usage

From source file:com.ts.db.connector.ConnectorDriverManager.java

static Driver getDriver(String url, String driverClassName, String classpath) throws SQLException {
    assert !StringUtils.isBlank(url);
    final boolean hasClasspath = !StringUtils.isBlank(classpath);
    if (!hasClasspath) {
        for (Driver driver : new ArrayList<Driver>(drivers)) {
            if (driver.acceptsURL(url)) {
                return driver;
            }/* www  .j a va 2 s  . com*/
        }
    }
    List<File> jars = new ArrayList<File>();
    ClassLoader cl;
    if (hasClasspath) {
        List<URL> urls = new ArrayList<URL>();
        for (String path : classpath.split(pathSeparator)) {
            final File file = new File(path);
            if (isJarFile(file)) {
                jars.add(file);
            }
            try {
                urls.add(file.toURI().toURL());
            } catch (MalformedURLException ex) {
                log.warn(ex.toString());
            }
        }
        cl = new URLClassLoader(urls.toArray(new URL[urls.size()]));
    } else {
        jars.addAll(getJarFiles("."));
        jars.addAll(driverFiles);
        List<URL> urls = new ArrayList<URL>();
        for (File file : jars) {
            try {
                urls.add(file.toURI().toURL());
            } catch (MalformedURLException ex) {
                log.warn(ex.toString());
            }
        }
        cl = new URLClassLoader(urls.toArray(new URL[urls.size()]), ClassLoader.getSystemClassLoader());
    }
    driverFiles.addAll(jars);
    final boolean hasDriverClassName = !StringUtils.isBlank(driverClassName);
    if (hasDriverClassName) {
        try {
            Driver driver = DynamicLoader.newInstance(driverClassName, cl);
            assert driver != null;
            return driver;
        } catch (DynamicLoadingException ex) {
            Throwable cause = (ex.getCause() != ex) ? ex.getCause() : ex;
            SQLException exception = new SQLException(cause.toString());
            exception.initCause(cause);
            throw exception;
        }
    }
    final String jdbcDrivers = System.getProperty("jdbc.drivers");
    if (!StringUtils.isBlank(jdbcDrivers)) {
        for (String jdbcDriver : jdbcDrivers.split(":")) {
            try {
                Driver driver = DynamicLoader.newInstance(jdbcDriver, cl);
                if (driver != null) {
                    if (!hasClasspath) {
                        drivers.add(driver);
                    }
                    return driver;
                }
            } catch (DynamicLoadingException ex) {
                log.warn(ex.toString());
            }
        }
    }
    for (File jar : jars) {
        try {
            Driver driver = getDriver(jar, url, cl);
            if (driver != null) {
                if (!hasClasspath) {
                    drivers.add(driver);
                }
                return driver;
            }
        } catch (IOException ex) {
            log.warn(ex.toString());
        }
    }
    for (String path : System.getProperty("java.class.path", "").split(pathSeparator)) {
        if (isJarFile(path)) {
            Driver driver;
            try {
                driver = getDriver(new File(path), url, cl);
                if (driver != null) {
                    drivers.add(driver);
                    return driver;
                }
            } catch (IOException ex) {
                log.warn(ex.toString());
            }
        }
    }
    throw new SQLException("driver not found");
}

From source file:com.google.gerrit.server.schema.H2AccountPatchReviewStore.java

public static OrmException convertError(String op, SQLException err) {
    switch (getSQLStateInt(err)) {
    case 23001: // UNIQUE CONSTRAINT VIOLATION
    case 23505: // DUPLICATE_KEY_1
        return new OrmDuplicateKeyException("ACCOUNT_PATCH_REVIEWS", err);

    default://from  w  w  w.j  a  va 2s  .c  o m
        if (err.getCause() == null && err.getNextException() != null) {
            err.initCause(err.getNextException());
        }
        return new OrmException(op + " failure on ACCOUNT_PATCH_REVIEWS", err);
    }
}

From source file:biz.wolschon.finance.jgnucash.mysql.impl.TransactionRowMapper.java

/**
 * @param aResultSet the result-set whos current result to map
 * @param aRowNumber the current row-number in the result-set
 * @return the result mapped to a bean/*  w w w.j  a v a  2 s  .  c o  m*/
 * @throws SQLException on problems with the database
 * @see org.springframework.jdbc.core.simple.ParameterizedRowMapper#mapRow(java.sql.ResultSet, int)
 */
@Override
public GnucashDBTransaction mapRow(final ResultSet aResultSet, final int aRowNumber) throws SQLException {
    GnucashDBTransaction retval;
    try {
        retval = new GnucashDBTransaction(myGnucashFile, aResultSet.getString("guid"),
                aResultSet.getString("currency_guid"), aResultSet.getString("num"),
                aResultSet.getString("description"), MYDATEFORMAT.parse(aResultSet.getString("post_date")),
                MYDATEFORMAT.parse(aResultSet.getString("enter_date")));
    } catch (ParseException e) {
        SQLException ex = new SQLException("invalid date");
        ex.initCause(e);
        throw ex;
    }
    return retval;
}

From source file:fedora.server.storage.ConnectionPool.java

/**
 * <p>//www  .  ja  va  2s . co  m
 * Constructs a ConnectionPool based on the calling arguments.
 * </p>
 *
 * @param driver
 *        The JDBC driver class name.
 * @param url
 *        The JDBC connection URL.
 * @param username
 *        The database user name.
 * @param password
 *        The database password.
 * @param maxActive
 *        Maximum number of active instances in pool.
 * @param maxIdle
 *        Maximum number of idle instances in pool.
 * @param maxWait
 *        Maximum amount of time in milliseconds the borrowObject() method
 *        should wait when whenExhaustedAction is set to
 *        WHEN_EXHAUSTED_BLOCK.
 * @param minIdle
 *        Minimum of idle instances in pool.
 * @param minEvictableIdleTimeMillis
 *        Minimum amount of time in milliseconds an object can be idle in
 *        pool before eligible for eviction (if applicable).
 * @param numTestsPerEvictionRun
 *        Number of objects to be examined on each run of idle evictor
 *        thread (if applicable).
 * @param timeBetweenEvictionRunsMillis
 *        Time in milliseconds to sleep between runs of the idle object
 *        evictor thread.
 * @param validationQuery
 *        Query to run when validation connections, e.g. SELECT 1.
 * @param testOnBorrow
 *        When true objects are validated before borrowed from the pool.
 * @param testOnReturn
 *        When true, objects are validated before returned to hte pool.
 * @param testWhileIdle
 *        When true, objects are validated by the idle object evictor
 *        thread.
 * @param whenExhaustedAction
 *        Action to take when a new object is requested and the the pool has
 *        reached maximum number of active objects.
 * @throws SQLException
 *         If the connection pool cannot be established for any reason.
 */
public ConnectionPool(String driver, String url, String username, String password, int maxActive, int maxIdle,
        long maxWait, int minIdle, long minEvictableIdleTimeMillis, int numTestsPerEvictionRun,
        long timeBetweenEvictionRunsMillis, String validationQuery, boolean testOnBorrow, boolean testOnReturn,
        boolean testWhileIdle, byte whenExhaustedAction) throws SQLException {

    try {
        Class.forName(driver);
    } catch (ClassNotFoundException e) {
        throw new SQLException(
                "JDBC class not found: " + driver + "; make sure " + "the JDBC driver is in the classpath");
    }

    // // http://jakarta.apache.org/commons/dbcp/configuration.html
    Properties props = new Properties();
    props.setProperty("url", url);
    props.setProperty("username", username);
    props.setProperty("password", password);
    props.setProperty("maxActive", "" + maxActive);
    props.setProperty("maxIdle", "" + maxIdle);
    props.setProperty("maxWait", "" + maxWait);
    props.setProperty("minIdle", "" + minIdle);
    props.setProperty("minEvictableIdleTimeMillis", "" + minEvictableIdleTimeMillis);
    props.setProperty("numTestsPerEvictionRun", "" + numTestsPerEvictionRun);
    props.setProperty("timeBetweenEvictionRunsMillis", "" + timeBetweenEvictionRunsMillis);
    if (validationQuery != null && validationQuery.length() > 0) {
        props.setProperty("validationQuery", validationQuery);
    }
    props.setProperty("testOnBorrow", "" + testOnBorrow);
    props.setProperty("testOnReturn", "" + testOnReturn);
    props.setProperty("testWhileIdle", "" + testWhileIdle);

    if (whenExhaustedAction == 0) {
        // fail (don't wait, just fail)
        props.setProperty("maxWait", "0");
    } else if (whenExhaustedAction == 1) {
        // block (wait indefinitely)
        props.setProperty("maxWait", "-1");
    } else if (whenExhaustedAction == 2) {
        // grow (override the maxActive value with -1, unlimited)
        props.setProperty("maxActive", "-1");
    }

    try {
        dataSource = (BasicDataSource) BasicDataSourceFactory.createDataSource(props);
        dataSource.setDriverClassName(driver);
    } catch (Exception e) {
        SQLException se = new SQLException("Error initializing connection pool");
        se.initCause(se);
        throw se;
    }
}

From source file:jp.co.acroquest.endosnipe.data.db.ConnectionManager.java

private void initialize(final String dbname, final boolean initialize, Connection conn) throws SQLException {
    try {//from   ww  w  . j  a v a  2s  .  c om
        // ???????
        boolean isInitialized = DBInitializer.isInitialized(conn);
        if (isInitialized) {
            this.initializedDatabaseSet_.add(dbname);
        } else if (initialize == true && isInitialized == false) {
            DBInitializer.initialize(conn);
            LOGGER.log(DB_INITIALIZED, dbname);
            this.initializedDatabaseSet_.add(dbname);
        }

        DBInitializer.reinitialize(conn);
    } catch (Exception ex) {
        LOGGER.log(EXCEPTION_OCCURED, ex, ex.getMessage());
        SQLException sqlex = new SQLException();
        sqlex.initCause(ex);
        throw sqlex;
    }
}

From source file:com.silverwrist.dynamo.unistore.BinaryPartImpl.java

public Blob getBlob() throws SQLException {
    if (m_ops == null) { // we've been deleted!
        SQLException se = new SQLException("Part has been deleted");
        se.initCause(new DatabaseException(BinaryPartImpl.class, "UniStoreMessages", "part.deleted"));
        throw se;

    } // end if// w  w w.j  a v  a2 s. c o m

    try { // load the data from the database and create the Blob around it
        byte[] data = new byte[m_size];
        m_ops.getData(m_parent.getMessageID(), m_part, data);
        return new ReturnBlob(data);

    } // end try
    catch (DatabaseException e) { // create a SQLException and chain this one onto it
        SQLException se = new SQLException("Database error retrieving data stream");
        se.initCause(e);
        throw se;

    } // end catch
    catch (IOException e) { // create a SQLException and chain this one onto it
        SQLException se = new SQLException("I/O error retrieving data stream");
        se.initCause(e);
        throw se;

    } // end catch

}

From source file:com.funambol.server.db.RoutingDataSource.java

/**
 * Returns a routed connection based on the given partitioniningKey.
 * <br>//from w w  w .  j a v a2  s  . c  o m
 * The defaultDataSource is used if:
 * <ui>
 *   <li>the partitioning criteria is null</li>
 *   <li>the partition returned by the partitioning criteria is null</li>
 *   <li>the partition returned by the partitioning criteria is unknown</li>
 *   <li>the partitioning criteria is null</li>
 * </ui>
 * If the used partitioning criteria throws a PartitioningCriteriaException
 * (see also LockedPartitionException) a SQLException is thrown to the caller.
 *
 * @param partitioningKey the partition key
 * @return a connection to the partition to use
 * @throws java.sql.SQLException if an error occurs
 */
public Connection getRoutedConnection(String partitioningKey) throws SQLException {
    if (lock.isLocked()) {
        //
        // If the datasource is locked, we try to acquire the lock with 20 seconds
        // as timeout. If we are able to get the lock, it means the datasource 
        // has been unlocked in the meantime. See configure method to see 
        // where the lock is acquired.
        // If we are not able to acquire the lock in 20 seconds an exception is
        // thrown. This means the configure() method requires more than 20 seconds
        // ...really bad case.
        //
        try {
            if (!lock.tryLock(20, TimeUnit.SECONDS)) {
                //
                // we don't have the lock !
                //
                throw new SQLException("Timeout expired waiting for a locked datasource");
            }
            lock.unlock();
        } catch (SQLException e) {
            throw e;
        } catch (Throwable e) {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
            SQLException sqlEx = new SQLException("Error waiting for unlocking event");
            sqlEx.initCause(e);
            throw sqlEx;
        }
    }

    if (!configured) {
        if (!initialized) {
            try {
                init();
            } catch (Exception e) {
                SQLException sqlEx = new SQLException("Error in initialization");
                sqlEx.initCause(e);
                throw sqlEx;
            }
        }
        try {
            configure();
        } catch (Exception e) {
            SQLException sqlEx = new SQLException("Error in configuration");
            sqlEx.initCause(e);
            throw sqlEx;
        }
    }

    if (partitioningCriteria == null) {
        return defaultDataSource.getConnection();
    }

    Partition partition = null;
    try {
        partition = partitioningCriteria.getPartition(partitioningKey);
        if (partition != null) {
            if (!partition.isActive()) {
                throw new SQLException("The partition for '" + partitioningKey + "' is locked");
            }
        }
    } catch (LockedPartitionException e) {
        SQLException sqlException = new SQLException("The partition for '" + partitioningKey + "' is locked");
        sqlException.initCause(e);
        throw sqlException;
    } catch (PartitioningCriteriaException e) {
        SQLException sqlException = new SQLException(
                "Unable to identify the target partition for '" + partitioningKey + "'");
        sqlException.initCause(e);
        throw sqlException;
    }

    if (partition == null) {
        return defaultDataSource.getConnection();
    }
    String partitionName = partition.getName();
    DataSource ds = dataSources.get(partitionName);

    if (ds == null) {
        return defaultDataSource.getConnection();
    }

    return ds.getConnection();
}

From source file:mondrian.olap.Util.java

/**
 * Closes a JDBC result set, statement, and connection, ignoring any errors.
 * If any of them are null, that's fine.
 *
 * <p>If any of them throws a {@link SQLException}, returns the first
 * such exception, but always executes all closes.</p>
 *
 * @param resultSet Result set/*from  w  w w.  jav  a2  s .  c o m*/
 * @param statement Statement
 * @param connection Connection
 */
public static SQLException close(ResultSet resultSet, Statement statement, Connection connection) {
    SQLException firstException = null;
    if (resultSet != null) {
        try {
            if (statement == null) {
                statement = resultSet.getStatement();
            }
            resultSet.close();
        } catch (Throwable t) {
            firstException = new SQLException();
            firstException.initCause(t);
        }
    }
    if (statement != null) {
        try {
            statement.close();
        } catch (Throwable t) {
            if (firstException == null) {
                firstException = new SQLException();
                firstException.initCause(t);
            }
        }
    }
    if (connection != null) {
        try {
            connection.close();
        } catch (Throwable t) {
            if (firstException == null) {
                firstException = new SQLException();
                firstException.initCause(t);
            }
        }
    }
    return firstException;
}

From source file:org.apache.jackrabbit.core.persistence.bundle.BundleDbPersistenceManager.java

/**
 * Checks if the required schema objects exist and creates them if they
 * don't exist yet./*from  w w  w  . j  ava 2 s  .co  m*/
 *
 * @throws SQLException if an SQL error occurs.
 * @throws RepositoryException if an error occurs.
 */
protected void checkSchema() throws SQLException, RepositoryException {
    if (!checkTablesExist()) {
        // read ddl from resources
        InputStream in = BundleDbPersistenceManager.class.getResourceAsStream(databaseType + ".ddl");
        if (in == null) {
            String msg = "Configuration error: The resource '" + databaseType + ".ddl' could not be found";
            log.debug(msg);
            throw new RepositoryException(msg);
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        Statement stmt = connectionManager.getConnection().createStatement();
        String sql = null;
        try {
            sql = reader.readLine();
            while (sql != null) {
                if (!sql.startsWith("#") && sql.length() > 0
                        && (sql.indexOf("BINVAL") < 0 || useDbBlobStore())) {
                    // only create blob related tables of db blob store configured
                    // execute sql stmt
                    sql = createSchemaSQL(sql);
                    stmt.executeUpdate(sql);
                }
                // read next sql stmt
                sql = reader.readLine();
            }
        } catch (IOException e) {
            String msg = "Configuration error: unable to read the resource '" + databaseType + ".ddl': " + e;
            log.debug(msg);
            throw new RepositoryException(msg, e);
        } catch (SQLException e) {
            String msg = "Schema generation error: Issuing statement: " + sql;
            SQLException se = new SQLException(msg);
            se.initCause(e);
            throw se;
        } finally {
            IOUtils.closeQuietly(in);
            stmt.close();
        }
    }
}

From source file:org.apache.jackrabbit.core.persistence.pool.BundleDbPersistenceManager.java

/**
 * Reads and parses a bundle from the BLOB in the given column of the
 * current row of the given result set. This is a helper method to
 * circumvent issues JCR-1039 and JCR-1474.
 *
 * @param id bundle identifier/*from  w w w.  j a va 2 s. c o m*/
 * @param rs result set
 * @param column BLOB column
 * @return parsed bundle
 * @throws SQLException if the bundle can not be read or parsed
 */
private NodePropBundle readBundle(NodeId id, ResultSet rs, int column) throws SQLException {
    try {
        InputStream in;
        if (rs.getMetaData().getColumnType(column) == Types.BLOB) {
            in = rs.getBlob(column).getBinaryStream();
        } else {
            in = rs.getBinaryStream(column);
        }
        try {
            return binding.readBundle(in, id);
        } finally {
            in.close();
        }
    } catch (IOException e) {
        SQLException exception = new SQLException("Failed to parse bundle " + id);
        exception.initCause(e);
        throw exception;
    }
}