Search in sources :

Example 21 with DbException

use of com.axway.ats.core.dbaccess.exceptions.DbException in project ats-framework by Axway.

the class DatabaseOperations method getValue.

/**
     * Gets a single value from a database. </br>
     * It returns the first value of the first returned row.
     *
     * <p><strong>Note</strong>: If the selected DB object is array - BLOB, LONG BLOB ... we return it this way:
     *  <code>[ 10, 24, -35]</code>
     *  </p>
     *
     * @param sqlQuery the SQL query to run
     * @return
     */
@PublicAtsApi
public String getValue(String sqlQuery) {
    try {
        log.debug("Executing query: " + sqlQuery);
        DbRecordValuesList[] rsList = dbProvider.select(sqlQuery);
        if (rsList != null && rsList.length > 0) {
            if (rsList.length > 1) {
                log.warn("SQL query '" + sqlQuery + "' returned " + rsList.length + " rows of results");
            }
            if (rsList[0].size() > 1) {
                log.warn("SQL query '" + sqlQuery + "' returned " + rsList[0].size() + " values per row");
            }
            return rsList[0].get(0).getValueAsString();
        }
    } catch (DbException e) {
        throw new DatabaseOperationsException("Error getting value from DB with query '" + sqlQuery + "'", e);
    }
    return null;
}
Also used : DbRecordValuesList(com.axway.ats.core.dbaccess.DbRecordValuesList) DatabaseOperationsException(com.axway.ats.action.exceptions.DatabaseOperationsException) DbException(com.axway.ats.core.dbaccess.exceptions.DbException) PublicAtsApi(com.axway.ats.common.PublicAtsApi)

Example 22 with DbException

use of com.axway.ats.core.dbaccess.exceptions.DbException in project ats-framework by Axway.

the class AbstractDbProvider method executeUpdate.

/**
     * Executes a given SQL update statement and returns number of updated rows
     * @param query the SQL query to execute
     * <br/><b>Note: </b>The SQL query must content inside any needed parameter escaping.
     * @return the number of rows affected
     * @throws DbException
     */
@Override
public int executeUpdate(String query) throws DbException {
    log.debug("Run SQL query: '" + query + "'");
    connection = ConnectionPool.getConnection(dbConnection);
    int rowsUpdated = 0;
    PreparedStatement stmnt = null;
    try {
        stmnt = connection.prepareStatement(query);
        rowsUpdated = stmnt.executeUpdate();
    } catch (SQLException e) {
        log.error("SQL errorCode=" + e.getErrorCode() + " sqlState=" + e.getSQLState() + " " + e.getMessage(), e);
        throw new DbException(e);
    } finally {
        DbUtils.close(connection, stmnt);
    }
    return rowsUpdated;
}
Also used : SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) DbException(com.axway.ats.core.dbaccess.exceptions.DbException)

Example 23 with DbException

use of com.axway.ats.core.dbaccess.exceptions.DbException in project ats-framework by Axway.

the class AbstractDbProvider method select.

public DbRecordValuesList[] select(com.axway.ats.common.dbaccess.DbQuery dbQuery, DbReturnModes dbReturnMode) throws DbException {
    connection = ConnectionPool.getConnection(dbConnection);
    final String errMsg = "Error running or parsing result of sql query '" + dbQuery.getQuery() + "'";
    ArrayList<DbRecordValuesList> dbRecords = new ArrayList<DbRecordValuesList>();
    // debug current query
    log.debug(dbQuery.getQuery());
    try (PreparedStatement st = prepareStatement(connection, dbQuery.getQuery(), dbQuery.getArguments());
        ResultSet res = st.executeQuery()) {
        ResultSetMetaData rsmd = res.getMetaData();
        int numberOfColumns = rsmd.getColumnCount();
        int currentRow = 0;
        while (res.next()) {
            currentRow++;
            DbRecordValuesList recordList = new DbRecordValuesList();
            for (int i = 1; i <= numberOfColumns; i++) {
                String tableName = rsmd.getTableName(i);
                String columnName = rsmd.getColumnName(i);
                DbColumn dbColumn = new DbColumn(tableName, columnName);
                dbColumn.setColumnType(rsmd.getColumnTypeName(i));
                DbRecordValue recordValue = null;
                //get the columns in the appropriate type
                try {
                    //get the columns in the appropriate type
                    switch(dbReturnMode) {
                        case OBJECT:
                            recordValue = parseDbRecordAsObject(dbColumn, res, i);
                            break;
                        case INPUT_STREAM:
                            recordValue = parseDbRecordAsInputStream(dbColumn, res, i);
                            break;
                        case STRING:
                        case ESCAPED_STRING:
                            recordValue = parseDbRecordAsString(dbColumn, res, i);
                            break;
                        default:
                            throw new DbException("Getting the values as " + dbReturnMode.name() + " is not supported. Table '" + dbColumn.getTableName() + "', column '" + dbColumn.getColumnName() + "'");
                    }
                } finally {
                    if (recordValue == null) {
                        // help locate error case when we have exception from the underlying calls in try block
                        log.error("Error getting value for table '" + tableName + "', row number " + currentRow + ",column " + i + ",named '" + columnName + "'");
                    } else {
                        // Trace. This could produce huge data so using lowest possible severity.
                        if (log.isTraceEnabled()) {
                            log.trace("Value for column " + i + ",named '" + columnName + "' is '" + recordValue.getValue() + "'");
                        }
                    }
                }
                recordList.add(recordValue);
            }
            dbRecords.add(recordList);
        }
        if (log.isDebugEnabled()) {
            log.debug("Select statement returned " + currentRow + " rows");
        }
    } catch (SQLException e) {
        throw new DbException(errMsg, e);
    } catch (IOException ioe) {
        throw new DbException(errMsg, ioe);
    } finally {
        DbUtils.closeConnection(connection);
    }
    return dbRecords.toArray(new DbRecordValuesList[] {});
}
Also used : SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) PreparedStatement(java.sql.PreparedStatement) IOException(java.io.IOException) DbException(com.axway.ats.core.dbaccess.exceptions.DbException) ResultSetMetaData(java.sql.ResultSetMetaData) ResultSet(java.sql.ResultSet)

Example 24 with DbException

use of com.axway.ats.core.dbaccess.exceptions.DbException in project ats-framework by Axway.

the class DbConnOracle method getDataSource.

@Override
public DataSource getDataSource() {
    try {
        dataSource = new OracleDataSource();
        dataSource.setServerName(this.host);
        dataSource.setUser(this.user);
        dataSource.setPassword(this.password);
        if (db != null && !"".equals(db)) {
            // case when SID or serviceName is not used
            dataSource.setDatabaseName(this.db);
        }
        dataSource.setURL(this.url);
        //enable connection caching - we'll have pooled connections this way
        dataSource.setConnectionCachingEnabled(true);
        if (useEncryption && this.customProperties != null) {
            if (this.customProperties.containsKey(OracleKeys.KEY_STORE_FULL_PATH) && this.customProperties.containsKey(OracleKeys.KEY_STORE_TYPE) && this.customProperties.containsKey(OracleKeys.KEY_STORE_PASSWORD)) {
                Properties sslConnectionProperties = new Properties();
                sslConnectionProperties.setProperty(OracleKeys.KEY_STORE_FULL_PATH, this.customProperties.get(OracleKeys.KEY_STORE_FULL_PATH).toString());
                sslConnectionProperties.setProperty(OracleKeys.KEY_STORE_TYPE, this.customProperties.get(OracleKeys.KEY_STORE_TYPE).toString());
                sslConnectionProperties.setProperty(OracleKeys.KEY_STORE_PASSWORD, this.customProperties.get(OracleKeys.KEY_STORE_PASSWORD).toString());
                // this property is set just in case, later we should remove it
                sslConnectionProperties.setProperty("javax.net.ssl.trustAnchors", this.customProperties.get(OracleKeys.KEY_STORE_PASSWORD).toString());
                dataSource.setConnectionProperties(sslConnectionProperties);
            } else {
                log.warn("Could not prepare secure connection to Oracle DB " + "because not all custom properties starting as DbConnection.KEY_STORE_XXX are set!");
                Certificate[] certs = SslUtils.getCertificatesFromSocket(host, String.valueOf(port));
                dataSource.setConnectionProperties(SslUtils.createKeyStore(certs[0], this.host, this.db, "", "", ""));
            }
        }
        return dataSource;
    } catch (SQLException e) {
        throw new DbException("Unable to create database source", e);
    }
}
Also used : SQLException(java.sql.SQLException) OracleDataSource(oracle.jdbc.pool.OracleDataSource) Properties(java.util.Properties) Certificate(java.security.cert.Certificate) DbException(com.axway.ats.core.dbaccess.exceptions.DbException)

Example 25 with DbException

use of com.axway.ats.core.dbaccess.exceptions.DbException in project ats-framework by Axway.

the class AbstractDbProvider method disconnect.

/**
     *  Closes and releases all idle connections that are currently stored
     *  in the connection pool associated with this data source.
     */
public void disconnect() {
    try {
        if (connection != null) {
            connection.close();
        }
    } catch (SQLException sqle) {
        throw new DbException(sqle);
    }
    ConnectionPool.removeConnection(dbConnection);
    dbConnection.disconnect();
}
Also used : SQLException(java.sql.SQLException) DbException(com.axway.ats.core.dbaccess.exceptions.DbException)

Aggregations

DbException (com.axway.ats.core.dbaccess.exceptions.DbException)31 SQLException (java.sql.SQLException)11 DbRecordValuesList (com.axway.ats.core.dbaccess.DbRecordValuesList)8 DatabaseOperationsException (com.axway.ats.action.exceptions.DatabaseOperationsException)7 PublicAtsApi (com.axway.ats.common.PublicAtsApi)7 Connection (java.sql.Connection)6 ArrayList (java.util.ArrayList)6 IOException (java.io.IOException)5 PreparedStatement (java.sql.PreparedStatement)5 DbRecordValue (com.axway.ats.core.dbaccess.DbRecordValue)4 DatabaseEnvironmentCleanupException (com.axway.ats.environment.database.exceptions.DatabaseEnvironmentCleanupException)4 BufferedReader (java.io.BufferedReader)4 File (java.io.File)4 FileReader (java.io.FileReader)4 ColumnDescription (com.axway.ats.core.dbaccess.ColumnDescription)3 CassandraDbProvider (com.axway.ats.core.dbaccess.cassandra.CassandraDbProvider)3 ColumnHasNoDefaultValueException (com.axway.ats.environment.database.exceptions.ColumnHasNoDefaultValueException)3 ResultSet (java.sql.ResultSet)3 HashMap (java.util.HashMap)3 DatabaseCell (com.axway.ats.action.dbaccess.model.DatabaseCell)2