Search in sources :

Example 21 with SQLException

use of java.sql.SQLException in project tomcat by apache.

the class JDBCRealm method open.

/**
     * Open (if necessary) and return a database connection for use by
     * this Realm.
     * @return the opened connection
     * @exception SQLException if a database error occurs
     */
protected Connection open() throws SQLException {
    // Do nothing if there is a database connection already open
    if (dbConnection != null)
        return (dbConnection);
    // Instantiate our database driver if necessary
    if (driver == null) {
        try {
            Class<?> clazz = Class.forName(driverName);
            driver = (Driver) clazz.newInstance();
        } catch (Throwable e) {
            ExceptionUtils.handleThrowable(e);
            throw new SQLException(e.getMessage(), e);
        }
    }
    // Open a new connection
    Properties props = new Properties();
    if (connectionName != null)
        props.put("user", connectionName);
    if (connectionPassword != null)
        props.put("password", connectionPassword);
    dbConnection = driver.connect(connectionURL, props);
    if (dbConnection == null) {
        throw new SQLException(sm.getString("jdbcRealm.open.invalidurl", driverName, connectionURL));
    }
    dbConnection.setAutoCommit(false);
    return (dbConnection);
}
Also used : SQLException(java.sql.SQLException) Properties(java.util.Properties)

Example 22 with SQLException

use of java.sql.SQLException in project tomcat by apache.

the class PoolableConnection method validate.

/**
     * Validates the connection, using the following algorithm:
     * <ol>
     *   <li>If {@code fastFailValidation} (constructor argument) is {@code true} and
     *       this connection has previously thrown a fatal disconnection exception,
     *       a {@code SQLException} is thrown. </li>
     *   <li>If {@code sql} is null, the driver's
     *       #{@link Connection#isValid(int) isValid(timeout)} is called.
     *       If it returns {@code false}, {@code SQLException} is thrown;
     *       otherwise, this method returns successfully.</li>
     *   <li>If {@code sql} is not null, it is executed as a query and if the resulting
     *       {@code ResultSet} contains at least one row, this method returns
     *       successfully.  If not, {@code SQLException} is thrown.</li>
     * </ol>
     * @param sql validation query
     * @param timeout validation timeout
     * @throws SQLException if validation fails or an SQLException occurs during validation
     */
public void validate(final String sql, int timeout) throws SQLException {
    if (_fastFailValidation && _fatalSqlExceptionThrown) {
        throw new SQLException(Utils.getMessage("poolableConnection.validate.fastFail"));
    }
    if (sql == null || sql.length() == 0) {
        if (timeout < 0) {
            timeout = 0;
        }
        if (!isValid(timeout)) {
            throw new SQLException("isValid() returned false");
        }
        return;
    }
    if (!sql.equals(lastValidationSql)) {
        lastValidationSql = sql;
        // Has to be the innermost delegate else the prepared statement will
        // be closed when the pooled connection is passivated.
        validationPreparedStatement = getInnermostDelegateInternal().prepareStatement(sql);
    }
    if (timeout > 0) {
        validationPreparedStatement.setQueryTimeout(timeout);
    }
    try (ResultSet rs = validationPreparedStatement.executeQuery()) {
        if (!rs.next()) {
            throw new SQLException("validationQuery didn't return a row");
        }
    } catch (final SQLException sqle) {
        throw sqle;
    }
}
Also used : SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet)

Example 23 with SQLException

use of java.sql.SQLException in project tomcat by apache.

the class PooledConnection method connect.

/**
     * Connects the underlying connection to the database.
     * @throws SQLException if the method {@link #release()} has been called.
     * @throws SQLException if driver instantiation fails
     * @throws SQLException if a call to {@link java.sql.Driver#connect(String, java.util.Properties)} fails.
     * @throws SQLException if default properties are configured and a call to
     * {@link java.sql.Connection#setAutoCommit(boolean)}, {@link java.sql.Connection#setCatalog(String)},
     * {@link java.sql.Connection#setTransactionIsolation(int)} or {@link java.sql.Connection#setReadOnly(boolean)} fails.
     */
public void connect() throws SQLException {
    if (released.get())
        throw new SQLException("A connection once released, can't be reestablished.");
    if (connection != null) {
        try {
            this.disconnect(false);
        } catch (Exception x) {
            log.debug("Unable to disconnect previous connection.", x);
        }
    //catch
    }
    //end if
    if (poolProperties.getDataSource() == null && poolProperties.getDataSourceJNDI() != null) {
    //TODO lookup JNDI name
    }
    if (poolProperties.getDataSource() != null) {
        connectUsingDataSource();
    } else {
        connectUsingDriver();
    }
    //set up the default state, unless we expect the interceptor to do it
    if (poolProperties.getJdbcInterceptors() == null || poolProperties.getJdbcInterceptors().indexOf(ConnectionState.class.getName()) < 0 || poolProperties.getJdbcInterceptors().indexOf(ConnectionState.class.getSimpleName()) < 0) {
        if (poolProperties.getDefaultTransactionIsolation() != DataSourceFactory.UNKNOWN_TRANSACTIONISOLATION)
            connection.setTransactionIsolation(poolProperties.getDefaultTransactionIsolation());
        if (poolProperties.getDefaultReadOnly() != null)
            connection.setReadOnly(poolProperties.getDefaultReadOnly().booleanValue());
        if (poolProperties.getDefaultAutoCommit() != null)
            connection.setAutoCommit(poolProperties.getDefaultAutoCommit().booleanValue());
        if (poolProperties.getDefaultCatalog() != null)
            connection.setCatalog(poolProperties.getDefaultCatalog());
    }
    this.discarded = false;
    this.lastConnected = System.currentTimeMillis();
}
Also used : SQLException(java.sql.SQLException) ConnectionState(org.apache.tomcat.jdbc.pool.interceptor.ConnectionState) SQLException(java.sql.SQLException)

Example 24 with SQLException

use of java.sql.SQLException in project tomcat by apache.

the class ProxyConnection method invoke.

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if (compare(ISCLOSED_VAL, method)) {
        return Boolean.valueOf(isClosed());
    }
    if (compare(CLOSE_VAL, method)) {
        //noop for already closed.
        if (connection == null)
            return null;
        PooledConnection poolc = this.connection;
        this.connection = null;
        pool.returnConnection(poolc);
        return null;
    } else if (compare(TOSTRING_VAL, method)) {
        return this.toString();
    } else if (compare(GETCONNECTION_VAL, method) && connection != null) {
        return connection.getConnection();
    } else if (method.getDeclaringClass().equals(XAConnection.class)) {
        try {
            return method.invoke(connection.getXAConnection(), args);
        } catch (Throwable t) {
            if (t instanceof InvocationTargetException) {
                throw t.getCause() != null ? t.getCause() : t;
            } else {
                throw t;
            }
        }
    }
    if (isClosed())
        throw new SQLException("Connection has already been closed.");
    if (compare(UNWRAP_VAL, method)) {
        return unwrap((Class<?>) args[0]);
    } else if (compare(ISWRAPPERFOR_VAL, method)) {
        return Boolean.valueOf(this.isWrapperFor((Class<?>) args[0]));
    }
    try {
        PooledConnection poolc = connection;
        if (poolc != null) {
            return method.invoke(poolc.getConnection(), args);
        } else {
            throw new SQLException("Connection has already been closed.");
        }
    } catch (Throwable t) {
        if (t instanceof InvocationTargetException) {
            throw t.getCause() != null ? t.getCause() : t;
        } else {
            throw t;
        }
    }
}
Also used : SQLException(java.sql.SQLException) InvocationTargetException(java.lang.reflect.InvocationTargetException) XAConnection(javax.sql.XAConnection)

Example 25 with SQLException

use of java.sql.SQLException in project tomcat by apache.

the class JDBCStore method clear.

/**
     * Remove all of the Sessions in this Store.
     *
     * @exception IOException if an input/output error occurs
     */
@Override
public void clear() throws IOException {
    synchronized (this) {
        int numberOfTries = 2;
        while (numberOfTries > 0) {
            Connection _conn = getConnection();
            if (_conn == null) {
                return;
            }
            try {
                if (preparedClearSql == null) {
                    String clearSql = "DELETE FROM " + sessionTable + " WHERE " + sessionAppCol + " = ?";
                    preparedClearSql = _conn.prepareStatement(clearSql);
                }
                preparedClearSql.setString(1, getName());
                preparedClearSql.execute();
                // Break out after the finally block
                numberOfTries = 0;
            } catch (SQLException e) {
                manager.getContext().getLogger().error(sm.getString(getStoreName() + ".SQLException", e));
                if (dbConnection != null)
                    close(dbConnection);
            } finally {
                release(_conn);
            }
            numberOfTries--;
        }
    }
}
Also used : SQLException(java.sql.SQLException) Connection(java.sql.Connection)

Aggregations

SQLException (java.sql.SQLException)17708 PreparedStatement (java.sql.PreparedStatement)7646 ResultSet (java.sql.ResultSet)6472 Connection (java.sql.Connection)6226 Statement (java.sql.Statement)3089 ArrayList (java.util.ArrayList)2495 Test (org.junit.Test)1525 IOException (java.io.IOException)1220 List (java.util.List)760 HashMap (java.util.HashMap)633 CallableStatement (java.sql.CallableStatement)506 Map (java.util.Map)471 Properties (java.util.Properties)426 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)387 Timestamp (java.sql.Timestamp)363 JDBCSession (org.jkiss.dbeaver.model.exec.jdbc.JDBCSession)328 DatabaseMetaData (java.sql.DatabaseMetaData)326 ResultSetMetaData (java.sql.ResultSetMetaData)301 DataSource (javax.sql.DataSource)295 File (java.io.File)280