Search in sources :

Example 21 with DataAccessException

use of org.springframework.dao.DataAccessException in project otter by alibaba.

the class DdlUtils method findTables.

@SuppressWarnings("unchecked")
public static List<Table> findTables(final JdbcTemplate jdbcTemplate, final String catalogName, final String schemaName, final String tableNamePattern, final DdlUtilsFilter filter, final DdlTableNameFilter tableNameFilter) throws Exception {
    return (List<Table>) jdbcTemplate.execute(new ConnectionCallback() {

        public Object doInConnection(Connection con) throws SQLException, DataAccessException {
            List<Table> tables = new ArrayList<Table>();
            DatabaseMetaDataWrapper metaData = new DatabaseMetaDataWrapper();
            boolean isDRDS = false;
            try {
                if (filter != null) {
                    con = filter.filterConnection(con);
                    Assert.notNull(con);
                }
                DatabaseMetaData databaseMetaData = con.getMetaData();
                if (filter != null) {
                    databaseMetaData = filter.filterDataBaseMetaData(jdbcTemplate, con, databaseMetaData);
                    Assert.notNull(databaseMetaData);
                }
                String databaseName = databaseMetaData.getDatabaseProductName();
                String version = databaseMetaData.getDatabaseProductVersion();
                if (StringUtils.startsWithIgnoreCase(databaseName, "mysql") && StringUtils.contains(version, "-TDDL-")) {
                    isDRDS = true;
                }
                metaData.setMetaData(databaseMetaData);
                metaData.setTableTypes(TableType.toStrings(SUPPORTED_TABLE_TYPES));
                metaData.setCatalog(catalogName);
                metaData.setSchemaPattern(schemaName);
                String convertTableName = tableNamePattern;
                if (databaseMetaData.storesUpperCaseIdentifiers()) {
                    metaData.setCatalog(catalogName.toUpperCase());
                    metaData.setSchemaPattern(schemaName.toUpperCase());
                    convertTableName = tableNamePattern.toUpperCase();
                }
                if (databaseMetaData.storesLowerCaseIdentifiers()) {
                    metaData.setCatalog(catalogName.toLowerCase());
                    metaData.setSchemaPattern(schemaName.toLowerCase());
                    convertTableName = tableNamePattern.toLowerCase();
                }
                ResultSet tableData = null;
                try {
                    tableData = metaData.getTables(convertTableName);
                    while ((tableData != null) && tableData.next()) {
                        Map<String, Object> values = readColumns(tableData, initColumnsForTable());
                        Table table = readTable(metaData, values);
                        if ((tableNameFilter == null) || tableNameFilter.accept(catalogName, schemaName, table.getName())) {
                            tables.add(table);
                        }
                    }
                } finally {
                    JdbcUtils.closeResultSet(tableData);
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
            for (Table table : tables) {
                makeAllColumnsPrimaryKeysIfNoPrimaryKeysFound(table);
                if (isDRDS) {
                    makeDRDSShardColumnsAsPrimaryKeys(table, jdbcTemplate, catalogName, schemaName, table.getName());
                }
            }
            return tables;
        }
    });
}
Also used : Table(org.apache.ddlutils.model.Table) Connection(java.sql.Connection) ArrayList(java.util.ArrayList) DatabaseMetaData(java.sql.DatabaseMetaData) DataAccessException(org.springframework.dao.DataAccessException) SQLException(java.sql.SQLException) DatabaseMetaDataWrapper(org.apache.ddlutils.platform.DatabaseMetaDataWrapper) ResultSet(java.sql.ResultSet) ArrayList(java.util.ArrayList) List(java.util.List) ConnectionCallback(org.springframework.jdbc.core.ConnectionCallback)

Example 22 with DataAccessException

use of org.springframework.dao.DataAccessException in project otter by alibaba.

the class DbLoadAction method doDdl.

/**
     * 执行ddl的调用,处理逻辑比较简单: 串行调用
     * 
     * @param context
     * @param eventDatas
     */
private void doDdl(DbLoadContext context, List<EventData> eventDatas) {
    for (final EventData data : eventDatas) {
        DataMedia dataMedia = ConfigHelper.findDataMedia(context.getPipeline(), data.getTableId());
        final DbDialect dbDialect = dbDialectFactory.getDbDialect(context.getIdentity().getPipelineId(), (DbMediaSource) dataMedia.getSource());
        Boolean skipDdlException = context.getPipeline().getParameters().getSkipDdlException();
        try {
            Boolean result = dbDialect.getJdbcTemplate().execute(new StatementCallback<Boolean>() {

                public Boolean doInStatement(Statement stmt) throws SQLException, DataAccessException {
                    Boolean result = false;
                    if (dbDialect instanceof MysqlDialect && StringUtils.isNotEmpty(data.getDdlSchemaName())) {
                        // 如果mysql,执行ddl时,切换到在源库执行的schema上
                        // result &= stmt.execute("use " + data.getDdlSchemaName());
                        // 解决当数据库名称为关键字如"Order"的时候,会报错,无法同步
                        result &= stmt.execute("use `" + data.getDdlSchemaName() + "`");
                    }
                    result &= stmt.execute(data.getSql());
                    return result;
                }
            });
            if (result) {
                // 记录为成功处理的sql
                context.getProcessedDatas().add(data);
            } else {
                context.getFailedDatas().add(data);
            }
        } catch (Throwable e) {
            if (skipDdlException) {
                // do skip
                logger.warn("skip exception for ddl : {} , caused by {}", data, ExceptionUtils.getFullStackTrace(e));
            } else {
                throw new LoadException(e);
            }
        }
    }
}
Also used : MysqlDialect(com.alibaba.otter.node.etl.common.db.dialect.mysql.MysqlDialect) SQLException(java.sql.SQLException) DbDialect(com.alibaba.otter.node.etl.common.db.dialect.DbDialect) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) EventData(com.alibaba.otter.shared.etl.model.EventData) DataMedia(com.alibaba.otter.shared.common.model.config.data.DataMedia) DataAccessException(org.springframework.dao.DataAccessException) DeadlockLoserDataAccessException(org.springframework.dao.DeadlockLoserDataAccessException) LoadException(com.alibaba.otter.node.etl.load.exception.LoadException)

Example 23 with DataAccessException

use of org.springframework.dao.DataAccessException in project camel by apache.

the class SqlConsumer method poll.

@Override
protected int poll() throws Exception {
    // must reset for each poll
    shutdownRunningTask = null;
    pendingExchanges = 0;
    final String preparedQuery = sqlPrepareStatementStrategy.prepareQuery(resolvedQuery, getEndpoint().isAllowNamedParameters(), null);
    log.trace("poll: {}", preparedQuery);
    final PreparedStatementCallback<Integer> callback = new PreparedStatementCallback<Integer>() {

        @Override
        public Integer doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
            Queue<DataHolder> answer = new LinkedList<DataHolder>();
            log.debug("Executing query: {}", preparedQuery);
            ResultSet rs = ps.executeQuery();
            SqlOutputType outputType = getEndpoint().getOutputType();
            boolean closeEager = true;
            try {
                log.trace("Got result list from query: {}, outputType={}", rs, outputType);
                if (outputType == SqlOutputType.StreamList) {
                    ResultSetIterator data = getEndpoint().queryForStreamList(ps.getConnection(), ps, rs);
                    // only process if we have data
                    if (data.hasNext()) {
                        addListToQueue(data, answer);
                        closeEager = false;
                    }
                } else if (outputType == SqlOutputType.SelectList) {
                    List<?> data = getEndpoint().queryForList(rs, true);
                    addListToQueue(data, answer);
                } else if (outputType == SqlOutputType.SelectOne) {
                    Object data = getEndpoint().queryForObject(rs);
                    if (data != null) {
                        addListToQueue(data, answer);
                    }
                } else {
                    throw new IllegalArgumentException("Invalid outputType=" + outputType);
                }
            } finally {
                if (closeEager) {
                    closeResultSet(rs);
                }
            }
            // process all the exchanges in this batch
            try {
                if (answer.isEmpty()) {
                    // no data
                    return 0;
                } else {
                    int rows = processBatch(CastUtils.cast(answer));
                    return rows;
                }
            } catch (Exception e) {
                throw ObjectHelper.wrapRuntimeCamelException(e);
            } finally {
                closeResultSet(rs);
            }
        }
    };
    Integer messagePolled;
    if (namedJdbcTemplate != null) {
        messagePolled = namedJdbcTemplate.execute(preparedQuery, parameterSource, callback);
    } else {
        messagePolled = jdbcTemplate.execute(preparedQuery, callback);
    }
    return messagePolled;
}
Also used : PreparedStatementCallback(org.springframework.jdbc.core.PreparedStatementCallback) PreparedStatement(java.sql.PreparedStatement) LinkedList(java.util.LinkedList) DataAccessException(org.springframework.dao.DataAccessException) RollbackExchangeException(org.apache.camel.RollbackExchangeException) SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) JdbcUtils.closeResultSet(org.springframework.jdbc.support.JdbcUtils.closeResultSet) List(java.util.List) LinkedList(java.util.LinkedList)

Example 24 with DataAccessException

use of org.springframework.dao.DataAccessException in project spring-security by spring-projects.

the class AdminPermissionController method addPermission.

/**
	 * Handles submission of the "add permission" form.
	 */
@RequestMapping(value = "/secure/addPermission.htm", method = RequestMethod.POST)
public String addPermission(AddPermission addPermission, BindingResult result, ModelMap model) {
    addPermissionValidator.validate(addPermission, result);
    if (result.hasErrors()) {
        model.put("recipients", listRecipients());
        model.put("permissions", listPermissions());
        return "addPermission";
    }
    PrincipalSid sid = new PrincipalSid(addPermission.getRecipient());
    Permission permission = permissionFactory.buildFromMask(addPermission.getPermission());
    try {
        contactManager.addPermission(addPermission.getContact(), sid, permission);
    } catch (DataAccessException existingPermission) {
        existingPermission.printStackTrace();
        result.rejectValue("recipient", "err.recipientExistsForContact", "Addition failure.");
        model.put("recipients", listRecipients());
        model.put("permissions", listPermissions());
        return "addPermission";
    }
    return "redirect:/secure/index.htm";
}
Also used : Permission(org.springframework.security.acls.model.Permission) BasePermission(org.springframework.security.acls.domain.BasePermission) PrincipalSid(org.springframework.security.acls.domain.PrincipalSid) DataAccessException(org.springframework.dao.DataAccessException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 25 with DataAccessException

use of org.springframework.dao.DataAccessException in project musiccabinet by hakko.

the class JdbcDatabaseAdministrationDao method forcePasswordUpdate.

@Override
public void forcePasswordUpdate(String password) throws ApplicationException {
    // we know it's ComboPooledDataSource, as we define it in applicationContext.xml
    // this is the primary reason for using C3P0 rather than Apache DBCP, since it
    // doesn't support password updates.
    ComboPooledDataSource dataSource = getDataSource();
    ComboPooledDataSource initialDataSource = (ComboPooledDataSource) initialJdbcTemplate.getDataSource();
    dataSource.setPassword(password);
    initialDataSource.setPassword(password);
    try {
        dataSource.softResetDefaultUser();
        initialDataSource.softResetDefaultUser();
    } catch (SQLException e) {
        throw new ApplicationException("Password update failed!", e);
    }
    try {
        initialJdbcTemplate.execute("select 1");
    } catch (DataAccessException e) {
        throw new ApplicationException("Password update failed!", e);
    }
}
Also used : ComboPooledDataSource(com.mchange.v2.c3p0.ComboPooledDataSource) ApplicationException(com.github.hakko.musiccabinet.exception.ApplicationException) SQLException(java.sql.SQLException) DataAccessException(org.springframework.dao.DataAccessException)

Aggregations

DataAccessException (org.springframework.dao.DataAccessException)73 SQLException (java.sql.SQLException)40 Test (org.junit.Test)20 Connection (java.sql.Connection)17 ResultSet (java.sql.ResultSet)16 PreparedStatement (java.sql.PreparedStatement)14 TransactionStatus (org.springframework.transaction.TransactionStatus)7 HashMap (java.util.HashMap)6 DeadlockLoserDataAccessException (org.springframework.dao.DeadlockLoserDataAccessException)5 IncorrectResultSizeDataAccessException (org.springframework.dao.IncorrectResultSizeDataAccessException)5 IOException (java.io.IOException)4 EmptyResultDataAccessException (org.springframework.dao.EmptyResultDataAccessException)4 ConnectionCallback (org.springframework.jdbc.core.ConnectionCallback)4 SpringSqlParams (com.opengamma.elsql.SpringSqlParams)3 DatabaseMetaData (java.sql.DatabaseMetaData)3 Statement (java.sql.Statement)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 IJoinQueryString (org.apereo.portal.jdbc.IJoinQueryString)3 DataIntegrityViolationException (org.springframework.dao.DataIntegrityViolationException)3