Search in sources :

Example 16 with DbException

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

the class MssqlEnvironmentHandler method restore.

/**
     * @see com.axway.ats.environment.database.model.RestoreHandler#restore(java.lang.String)
     */
public void restore(String backupFileName) throws DatabaseEnvironmentCleanupException {
    BufferedReader backupReader = null;
    Connection connection = null;
    //we need to preserve the auto commit option, as the connections are pooled
    boolean isAutoCommit = true;
    try {
        log.debug("Starting restoring db backup from file '" + backupFileName + "'");
        backupReader = new BufferedReader(new FileReader(new File(backupFileName)));
        connection = ConnectionPool.getConnection(dbConnection);
        isAutoCommit = connection.getAutoCommit();
        connection.setAutoCommit(false);
        StringBuilder sql = new StringBuilder();
        String line = backupReader.readLine();
        while (line != null) {
            sql.append(line);
            if (line.endsWith(EOL_MARKER)) {
                // remove the EOL marker
                sql.delete(sql.length() - EOL_MARKER.length(), sql.length());
                PreparedStatement updateStatement = connection.prepareStatement(sql.toString());
                //catch the exception and rollback, otherwise we are locked
                try {
                    updateStatement.execute();
                } catch (SQLException sqle) {
                    log.error("Error invoking restore satement: " + sql.toString());
                    //we have to roll back the transaction and re-throw the exception
                    connection.rollback();
                    throw sqle;
                } finally {
                    try {
                        updateStatement.close();
                    } catch (SQLException sqle) {
                        log.error("Unable to close prepared statement", sqle);
                    }
                }
                sql = new StringBuilder();
            } else {
                //add a new line
                //FIXME: this code will add the system line ending - it
                //is not guaranteed that this was the actual line ending
                sql.append(AtsSystemProperties.SYSTEM_LINE_SEPARATOR);
            }
            line = backupReader.readLine();
        }
        try {
            //commit the transaction
            connection.commit();
        } catch (SQLException sqle) {
            //we have to roll back the transaction and re-throw the exception
            connection.rollback();
            throw sqle;
        }
        log.debug("Finished restoring db backup from file '" + backupFileName + "'");
    } catch (IOException ioe) {
        throw new DatabaseEnvironmentCleanupException(ERROR_RESTORING_BACKUP + backupFileName, ioe);
    } catch (SQLException sqle) {
        throw new DatabaseEnvironmentCleanupException(ERROR_RESTORING_BACKUP + backupFileName, sqle);
    } catch (DbException dbe) {
        throw new DatabaseEnvironmentCleanupException(ERROR_RESTORING_BACKUP + backupFileName, dbe);
    } finally {
        try {
            IoUtils.closeStream(backupReader, "Could not close reader for backup file " + backupFileName);
            if (connection != null) {
                connection.setAutoCommit(isAutoCommit);
                connection.close();
            }
        } catch (SQLException sqle) {
            log.error(ERROR_RESTORING_BACKUP + backupFileName, sqle);
        }
    }
}
Also used : DatabaseEnvironmentCleanupException(com.axway.ats.environment.database.exceptions.DatabaseEnvironmentCleanupException) SQLException(java.sql.SQLException) BufferedReader(java.io.BufferedReader) Connection(java.sql.Connection) FileReader(java.io.FileReader) PreparedStatement(java.sql.PreparedStatement) IOException(java.io.IOException) File(java.io.File) DbException(com.axway.ats.core.dbaccess.exceptions.DbException)

Example 17 with DbException

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

the class MssqlEnvironmentHandler method getColumnsToSelect.

@Override
protected List<ColumnDescription> getColumnsToSelect(DbTable table, String userName) throws DbException, ColumnHasNoDefaultValueException {
    String selectColumnsInfo = "SELECT COLUMN_NAME, DATA_TYPE, COLUMN_DEFAULT, CHARACTER_MAXIMUM_LENGTH, IS_NULLABLE, " + "columnproperty(object_id('" + table.getTableName() + "'), COLUMN_NAME,'IsIdentity') as isIdentity " + "FROM information_schema.COLUMNS WHERE table_name LIKE '" + table.getTableName() + "'";
    ArrayList<ColumnDescription> columnsToSelect = new ArrayList<ColumnDescription>();
    DbRecordValuesList[] columnsMetaData = null;
    try {
        columnsMetaData = this.dbProvider.select(selectColumnsInfo);
    } catch (DbException e) {
        log.error("Could not get columns for table " + table.getTableName() + ". Check if the table is existing and that the user has permissions. See more details in the trace.");
        throw e;
    }
    // the Identity column can be skipped(excluded)
    table.setIdentityColumnPresent(false);
    for (DbRecordValuesList columnMetaData : columnsMetaData) {
        String columnName = (String) columnMetaData.get("COLUMN_NAME");
        //check if the column should be skipped in the backup
        if (!table.getColumnsToExclude().contains(columnName)) {
            ColumnDescription colDescription = new MssqlColumnDescription(columnName, (String) columnMetaData.get("DATA_TYPE"));
            columnsToSelect.add(colDescription);
            if ((Integer) columnMetaData.get("isIdentity") == 1) {
                table.setIdentityColumnPresent(true);
            }
        } else {
            //if this column has no default value, we cannot skip it in the backup
            if (columnMetaData.get("COLUMN_DEFAULT") == null) {
                log.error("Cannot skip columns with no default values while creating backup");
                throw new ColumnHasNoDefaultValueException(table.getTableName(), columnName);
            }
        }
    }
    return columnsToSelect;
}
Also used : DbRecordValuesList(com.axway.ats.core.dbaccess.DbRecordValuesList) ColumnHasNoDefaultValueException(com.axway.ats.environment.database.exceptions.ColumnHasNoDefaultValueException) MssqlColumnDescription(com.axway.ats.core.dbaccess.MssqlColumnDescription) ColumnDescription(com.axway.ats.core.dbaccess.ColumnDescription) ArrayList(java.util.ArrayList) MssqlColumnDescription(com.axway.ats.core.dbaccess.MssqlColumnDescription) DbException(com.axway.ats.core.dbaccess.exceptions.DbException)

Example 18 with DbException

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

the class MysqlEnvironmentHandler method restore.

public void restore(String backupFileName) throws DatabaseEnvironmentCleanupException {
    BufferedReader backupReader = null;
    Connection connection = null;
    //we need to preserve the auto commit option, as
    //the connections are pooled
    boolean isAutoCommit = true;
    try {
        log.debug("Starting restoring db backup from file '" + backupFileName + "'");
        backupReader = new BufferedReader(new FileReader(new File(backupFileName)));
        connection = ConnectionPool.getConnection(dbConnection);
        isAutoCommit = connection.getAutoCommit();
        connection.setAutoCommit(false);
        StringBuilder sql = new StringBuilder();
        String line = backupReader.readLine();
        while (line != null) {
            sql.append(line);
            if (line.endsWith(EOL_MARKER)) {
                // remove the OEL marker
                sql.delete(sql.length() - EOL_MARKER.length(), sql.length());
                PreparedStatement updateStatement = connection.prepareStatement(sql.toString());
                //catch the exception and roll back, otherwise we are locked
                try {
                    updateStatement.execute();
                } catch (SQLException sqle) {
                    log.error("Error invoking restore satement: " + sql.toString());
                    //we have to roll back the transaction and re throw the exception
                    connection.rollback();
                    throw sqle;
                } finally {
                    try {
                        updateStatement.close();
                    } catch (SQLException sqle) {
                        log.error("Unable to close prepared statement", sqle);
                    }
                }
                sql.delete(0, sql.length());
            } else {
                //add a new line
                //FIXME: this code will add the system line ending - it
                //is not guaranteed that this was the actual line ending
                sql.append(AtsSystemProperties.SYSTEM_LINE_SEPARATOR);
            }
            line = backupReader.readLine();
        }
        try {
            //commit the transaction
            connection.commit();
        } catch (SQLException sqle) {
            //we have to roll back the transaction and re throw the exception
            connection.rollback();
            throw sqle;
        }
        log.debug("Finished restoring db backup from file '" + backupFileName + "'");
    } catch (IOException ioe) {
        throw new DatabaseEnvironmentCleanupException("Could not restore backup from file " + backupFileName, ioe);
    } catch (SQLException sqle) {
        throw new DatabaseEnvironmentCleanupException("Could not restore backup from file " + backupFileName, sqle);
    } catch (DbException dbe) {
        throw new DatabaseEnvironmentCleanupException("Could not restore backup from file " + backupFileName, dbe);
    } finally {
        try {
            IoUtils.closeStream(backupReader, "Could not close reader for backup file " + backupFileName);
            if (connection != null) {
                connection.setAutoCommit(isAutoCommit);
                connection.close();
            }
        } catch (SQLException sqle) {
            log.error("Could close DB connection");
        }
    }
}
Also used : DatabaseEnvironmentCleanupException(com.axway.ats.environment.database.exceptions.DatabaseEnvironmentCleanupException) SQLException(java.sql.SQLException) BufferedReader(java.io.BufferedReader) Connection(java.sql.Connection) FileReader(java.io.FileReader) PreparedStatement(java.sql.PreparedStatement) IOException(java.io.IOException) File(java.io.File) DbException(com.axway.ats.core.dbaccess.exceptions.DbException)

Example 19 with DbException

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

the class DbFolder method refresh.

private void refresh() throws RbvException {
    newMetaDataMap = new HashMap<String, MetaData>();
    //store the current meta data map and clear the map holding all meta data
    //this way we will be able to detect any changes including added and removed
    //meta data
    HashMap<String, MetaData> oldMetaDataMap = allMetaDataMap;
    allMetaDataMap = new HashMap<String, MetaData>();
    log.debug("Run DB query '" + this.searchQuery.getQuery() + "'");
    DbRecordValuesList[] queryResults;
    try {
        queryResults = dbProvider.select(this.searchQuery);
    } catch (DbException dbe) {
        throw new RbvException(dbe);
    }
    if (queryResults != null) {
        for (DbRecordValuesList queryResult : queryResults) {
            DbMetaData currentData = new DbMetaData();
            StringBuffer metaDataHash = new StringBuffer();
            for (DbRecordValue recordValue : queryResult) {
                DbMetaDataKey key = new DbMetaDataKey(recordValue.getDbColumn());
                Object value = recordValue.getValue();
                currentData.putProperty(key.toString(), value);
                //calculate the hash
                metaDataHash.append(key.toString());
                metaDataHash.append(recordValue.getValueAsString());
            }
            try {
                //compute MD5 so we don't keep the whole StringBuffer in memory
                MessageDigest metaDataHashDigest = MessageDigest.getInstance("MD5");
                String metaDataSum = new String(metaDataHashDigest.digest(metaDataHash.toString().getBytes()));
                if (!oldMetaDataMap.containsKey(metaDataSum)) {
                    newMetaDataMap.put(metaDataSum, currentData);
                }
                //always put the record in the map holding all meta data
                allMetaDataMap.put(metaDataSum, currentData);
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException(e);
            }
        }
        didPollingOccured = true;
    }
}
Also used : RbvException(com.axway.ats.rbv.model.RbvException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) DbException(com.axway.ats.core.dbaccess.exceptions.DbException) DbRecordValuesList(com.axway.ats.core.dbaccess.DbRecordValuesList) DbRecordValue(com.axway.ats.core.dbaccess.DbRecordValue) MetaData(com.axway.ats.rbv.MetaData) MessageDigest(java.security.MessageDigest)

Example 20 with DbException

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

the class DatabaseOperations method getDatabaseDataAsStrings.

/**
     * <p>
     * Gets data from a database table. All values as returned as String representations as needed.<br>
     * For example:
     * <ul>
     *  <li>TIMESTAMPs are retuned as java.sql.Timestamp.toString() format
     *  (yyyy-MM-dd HH:mm:ss.SSS and millis instead of nanos as documented in JavaSE Doc)</li>
     *  <li>BLOBs bytes are represented in hex format. Beware not to select too big data cells.</li>
     * </ul>
     * </p>
     * @param sqlQuery the SQL SELECT query to run. Client is resposible for any
     *      possible escaping needed so thread this as not security-safe method
     * @return the found database data
     */
@PublicAtsApi
public DatabaseRow[] getDatabaseDataAsStrings(String sqlQuery) {
    List<DatabaseRow> dbRows = new LinkedList<DatabaseRow>();
    try {
        log.debug("Executing query: " + sqlQuery);
        DbRecordValuesList[] rsList = dbProvider.select(new DbQuery(sqlQuery), DbReturnModes.STRING);
        if (rsList != null) {
            for (DbRecordValuesList rs : rsList) {
                Iterator<DbRecordValue> it = rs.iterator();
                if (it.hasNext()) {
                    DatabaseRow dbRow = new DatabaseRow();
                    while (it.hasNext()) {
                        DbRecordValue dbRecordValue = it.next();
                        dbRow.addCell(new DatabaseCell(dbRecordValue.getDbColumn().getColumnName(), dbRecordValue.getValueAsString()));
                    }
                    dbRows.add(dbRow);
                }
            }
        }
        return dbRows.toArray(new DatabaseRow[dbRows.size()]);
    } catch (DbException e) {
        throw new DatabaseOperationsException("Error getting data from DB with query '" + sqlQuery + "'", e);
    }
}
Also used : DbQuery(com.axway.ats.common.dbaccess.DbQuery) DbRecordValuesList(com.axway.ats.core.dbaccess.DbRecordValuesList) DatabaseCell(com.axway.ats.action.dbaccess.model.DatabaseCell) DbRecordValue(com.axway.ats.core.dbaccess.DbRecordValue) DatabaseOperationsException(com.axway.ats.action.exceptions.DatabaseOperationsException) DatabaseRow(com.axway.ats.action.dbaccess.model.DatabaseRow) LinkedList(java.util.LinkedList) DbException(com.axway.ats.core.dbaccess.exceptions.DbException) PublicAtsApi(com.axway.ats.common.PublicAtsApi)

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