Search in sources :

Example 81 with DataAccessException

use of org.springframework.dao.DataAccessException in project uPortal by Jasig.

the class HibernateDbLoader method process.

@Override
public void process(DbLoaderConfig configuration) throws ParserConfigurationException, SAXException, IOException {
    final String scriptFile = configuration.getScriptFile();
    final List<String> script;
    if (scriptFile == null) {
        script = null;
    } else {
        script = new LinkedList<String>();
    }
    final ITableDataProvider tableData = this.loadTables(configuration, dialect);
    // Handle table drop/create
    if (configuration.isDropTables() || configuration.isCreateTables()) {
        // Load Table object model
        final Map<String, Table> tables = tableData.getTables();
        final Mapping mapping = this.configuration.buildMapping();
        final String defaultCatalog = this.configuration.getProperty(Environment.DEFAULT_CATALOG);
        final String defaultSchema = this.configuration.getProperty(Environment.DEFAULT_SCHEMA);
        final Map<String, DataAccessException> failedSql = new LinkedHashMap<String, DataAccessException>();
        // Generate and execute drop table scripts
        if (configuration.isDropTables()) {
            final List<String> dropScript = this.dropScript(tables.values(), dialect, defaultCatalog, defaultSchema);
            if (script == null) {
                this.logger.info("Dropping existing tables");
                for (final String sql : dropScript) {
                    this.logger.info(sql);
                    try {
                        jdbcOperations.update(sql);
                    } catch (NonTransientDataAccessResourceException dae) {
                        throw dae;
                    } catch (DataAccessException dae) {
                        failedSql.put(sql, dae);
                    }
                }
            } else {
                script.addAll(dropScript);
            }
        }
        // Log any drop/create statements that failed
        for (final Map.Entry<String, DataAccessException> failedSqlEntry : failedSql.entrySet()) {
            this.logger.warn("'" + failedSqlEntry.getKey() + "' failed to execute due to " + failedSqlEntry.getValue());
        }
        // Generate and execute create table scripts
        if (configuration.isCreateTables()) {
            final List<String> createScript = this.createScript(tables.values(), dialect, mapping, defaultCatalog, defaultSchema);
            if (script == null) {
                this.logger.info("Creating tables");
                for (final String sql : createScript) {
                    this.logger.info(sql);
                    jdbcOperations.update(sql);
                }
            } else {
                script.addAll(createScript);
            }
        }
    }
    // Perform database population
    if (script == null && configuration.isPopulateTables()) {
        this.logger.info("Populating database");
        final Map<String, Map<String, Integer>> tableColumnTypes = tableData.getTableColumnTypes();
        this.populateTables(configuration, tableColumnTypes);
    }
    // Write out the script file
    if (script != null) {
        for (final ListIterator<String> iterator = script.listIterator(); iterator.hasNext(); ) {
            final String sql = iterator.next();
            iterator.set(sql + ";");
        }
        final File outputFile = new File(scriptFile);
        FileUtils.writeLines(outputFile, script);
        this.logger.info("Saved DDL to: " + outputFile.getAbsolutePath());
    }
}
Also used : Table(org.hibernate.mapping.Table) Mapping(org.hibernate.engine.spi.Mapping) LinkedHashMap(java.util.LinkedHashMap) NonTransientDataAccessResourceException(org.springframework.dao.NonTransientDataAccessResourceException) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) File(java.io.File) DataAccessException(org.springframework.dao.DataAccessException)

Example 82 with DataAccessException

use of org.springframework.dao.DataAccessException in project uPortal by Jasig.

the class JdbcAuthDao method createToken.

protected void createToken(final String serviceName) {
    try {
        this.jdbcOperations.execute(new ConnectionCallback<Object>() {

            @Override
            public Object doInConnection(Connection con) throws SQLException, DataAccessException {
                // This is horribly hacky but we can't rely on the main uPortal TM
                // directly or we get
                // into a circular dependency loop from JPA to Ehcache to jGroups and
                // back to JPA
                final DataSource ds = new SingleConnectionDataSource(con, true);
                final PlatformTransactionManager ptm = new DataSourceTransactionManager(ds);
                final TransactionOperations to = new TransactionTemplate(ptm);
                to.execute(new TransactionCallbackWithoutResult() {

                    @Override
                    protected void doInTransactionWithoutResult(TransactionStatus status) {
                        logger.info("Creating jGroups auth token");
                        final String authToken = RandomTokenGenerator.INSTANCE.generateRandomToken(authTokenLength);
                        final ImmutableMap<String, String> params = ImmutableMap.of(PRM_SERVICE_NAME, serviceName, PRM_RANDOM_TOKEN, authToken);
                        namedParameterJdbcOperations.update(INSERT_SQL, params);
                    }
                });
                return null;
            }
        });
    } catch (ConstraintViolationException e) {
    // Ignore, just means a concurrent token creation
    } catch (DataIntegrityViolationException e) {
    // Ignore, just means a concurrent token creation
    }
}
Also used : SingleConnectionDataSource(org.springframework.jdbc.datasource.SingleConnectionDataSource) TransactionOperations(org.springframework.transaction.support.TransactionOperations) SQLException(java.sql.SQLException) Connection(java.sql.Connection) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) TransactionStatus(org.springframework.transaction.TransactionStatus) PlatformTransactionManager(org.springframework.transaction.PlatformTransactionManager) SingleConnectionDataSource(org.springframework.jdbc.datasource.SingleConnectionDataSource) DataSource(javax.sql.DataSource) DataIntegrityViolationException(org.springframework.dao.DataIntegrityViolationException) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) DataAccessException(org.springframework.dao.DataAccessException) DataSourceTransactionManager(org.springframework.jdbc.datasource.DataSourceTransactionManager) TransactionCallbackWithoutResult(org.springframework.transaction.support.TransactionCallbackWithoutResult)

Example 83 with DataAccessException

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

the class MongoTemplate method doUpdate.

protected UpdateResult doUpdate(final String collectionName, final Query query, final Update update, @Nullable final Class<?> entityClass, final boolean upsert, final boolean multi) {
    Assert.notNull(collectionName, "CollectionName must not be null!");
    Assert.notNull(query, "Query must not be null!");
    Assert.notNull(update, "Update must not be null!");
    return execute(collectionName, new CollectionCallback<UpdateResult>() {

        public UpdateResult doInCollection(MongoCollection<Document> collection) throws MongoException, DataAccessException {
            MongoPersistentEntity<?> entity = entityClass == null ? null : getPersistentEntity(entityClass);
            increaseVersionForUpdateIfNecessary(entity, update);
            UpdateOptions opts = new UpdateOptions();
            opts.upsert(upsert);
            Document queryObj = new Document();
            if (query != null) {
                queryObj.putAll(queryMapper.getMappedObject(query.getQueryObject(), entity));
                query.getCollation().map(Collation::toMongoCollation).ifPresent(opts::collation);
            }
            Document updateObj = update == null ? new Document() : updateMapper.getMappedObject(update.getUpdateObject(), entity);
            if (multi && update.isIsolated() && !queryObj.containsKey("$isolated")) {
                queryObj.put("$isolated", 1);
            }
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Calling update using query: {} and update: {} in collection: {}", serializeToJsonSafely(queryObj), serializeToJsonSafely(updateObj), collectionName);
            }
            MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.UPDATE, collectionName, entityClass, updateObj, queryObj);
            WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction);
            collection = writeConcernToUse != null ? collection.withWriteConcern(writeConcernToUse) : collection;
            if (!UpdateMapper.isUpdateObject(updateObj)) {
                return collection.replaceOne(queryObj, updateObj, opts);
            } else {
                if (multi) {
                    return collection.updateMany(queryObj, updateObj, opts);
                } else {
                    return collection.updateOne(queryObj, updateObj, opts);
                }
            }
        }
    });
}
Also used : MongoException(com.mongodb.MongoException) MongoPersistentEntity(org.springframework.data.mongodb.core.mapping.MongoPersistentEntity) WriteConcern(com.mongodb.WriteConcern) Document(org.bson.Document) Collation(org.springframework.data.mongodb.core.query.Collation) UpdateResult(com.mongodb.client.result.UpdateResult) DataAccessException(org.springframework.dao.DataAccessException)

Example 84 with DataAccessException

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

the class MongoChangeSetPersister method getPersistentState.

/*
	 * (non-Javadoc)
	 * @see org.springframework.data.crossstore.ChangeSetPersister#getPersistentState(java.lang.Class, java.lang.Object, org.springframework.data.crossstore.ChangeSet)
	 */
public void getPersistentState(Class<? extends ChangeSetBacked> entityClass, Object id, final ChangeSet changeSet) throws DataAccessException, NotFoundException {
    if (id == null) {
        log.debug("Unable to load MongoDB data for null id");
        return;
    }
    String collName = getCollectionNameForEntity(entityClass);
    final Document dbk = new Document();
    dbk.put(ENTITY_ID, id);
    dbk.put(ENTITY_CLASS, entityClass.getName());
    if (log.isDebugEnabled()) {
        log.debug("Loading MongoDB data for {}", dbk);
    }
    mongoTemplate.execute(collName, new CollectionCallback<Object>() {

        public Object doInCollection(MongoCollection<Document> collection) throws MongoException, DataAccessException {
            for (Document dbo : collection.find(dbk)) {
                String key = (String) dbo.get(ENTITY_FIELD_NAME);
                if (log.isDebugEnabled()) {
                    log.debug("Processing key: {}", key);
                }
                if (!changeSet.getValues().containsKey(key)) {
                    String className = (String) dbo.get(ENTITY_FIELD_CLASS);
                    if (className == null) {
                        throw new DataIntegrityViolationException("Unble to convert property " + key + ": Invalid metadata, " + ENTITY_FIELD_CLASS + " not available");
                    }
                    Class<?> clazz = ClassUtils.resolveClassName(className, ClassUtils.getDefaultClassLoader());
                    Object value = mongoTemplate.getConverter().read(clazz, dbo);
                    if (log.isDebugEnabled()) {
                        log.debug("Adding to ChangeSet: {}", key);
                    }
                    changeSet.set(key, value);
                }
            }
            return null;
        }
    });
}
Also used : MongoException(com.mongodb.MongoException) Document(org.bson.Document) DataAccessException(org.springframework.dao.DataAccessException) DataIntegrityViolationException(org.springframework.dao.DataIntegrityViolationException)

Example 85 with DataAccessException

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

the class MongoChangeSetPersister method persistState.

/*
	 * (non-Javadoc)
	 * @see org.springframework.data.crossstore.ChangeSetPersister#persistState(org.springframework.data.crossstore.ChangeSetBacked, org.springframework.data.crossstore.ChangeSet)
	 */
public Object persistState(ChangeSetBacked entity, ChangeSet cs) throws DataAccessException {
    if (cs == null) {
        log.debug("Flush: changeset was null, nothing to flush.");
        return 0L;
    }
    if (log.isDebugEnabled()) {
        log.debug("Flush: changeset: {}", cs.getValues());
    }
    String collName = getCollectionNameForEntity(entity.getClass());
    if (mongoTemplate.getCollection(collName) == null) {
        mongoTemplate.createCollection(collName);
    }
    for (String key : cs.getValues().keySet()) {
        if (key != null && !key.startsWith("_") && !key.equals(ChangeSetPersister.ID_KEY)) {
            Object value = cs.getValues().get(key);
            final Document dbQuery = new Document();
            dbQuery.put(ENTITY_ID, getPersistentId(entity, cs));
            dbQuery.put(ENTITY_CLASS, entity.getClass().getName());
            dbQuery.put(ENTITY_FIELD_NAME, key);
            final Document dbId = mongoTemplate.execute(collName, new CollectionCallback<Document>() {

                public Document doInCollection(MongoCollection<Document> collection) throws MongoException, DataAccessException {
                    Document id = collection.find(dbQuery).first();
                    return id;
                }
            });
            if (value == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Flush: removing: {}", dbQuery);
                }
                mongoTemplate.execute(collName, new CollectionCallback<Object>() {

                    public Object doInCollection(MongoCollection<Document> collection) throws MongoException, DataAccessException {
                        DeleteResult dr = collection.deleteMany(dbQuery);
                        return null;
                    }
                });
            } else {
                final Document dbDoc = new Document();
                dbDoc.putAll(dbQuery);
                if (log.isDebugEnabled()) {
                    log.debug("Flush: saving: {}", dbQuery);
                }
                mongoTemplate.getConverter().write(value, dbDoc);
                dbDoc.put(ENTITY_FIELD_CLASS, value.getClass().getName());
                if (dbId != null) {
                    dbDoc.put("_id", dbId.get("_id"));
                }
                mongoTemplate.execute(collName, new CollectionCallback<Object>() {

                    public Object doInCollection(MongoCollection<Document> collection) throws MongoException, DataAccessException {
                        if (dbId != null) {
                            collection.replaceOne(Filters.eq("_id", dbId.get("_id")), dbDoc);
                        } else {
                            if (dbDoc.containsKey("_id") && dbDoc.get("_id") == null) {
                                dbDoc.remove("_id");
                            }
                            collection.insertOne(dbDoc);
                        }
                        return null;
                    }
                });
            }
        }
    }
    return 0L;
}
Also used : MongoException(com.mongodb.MongoException) Document(org.bson.Document) DataAccessException(org.springframework.dao.DataAccessException) DeleteResult(com.mongodb.client.result.DeleteResult)

Aggregations

DataAccessException (org.springframework.dao.DataAccessException)89 SQLException (java.sql.SQLException)40 Test (org.junit.Test)26 Connection (java.sql.Connection)17 ResultSet (java.sql.ResultSet)16 PreparedStatement (java.sql.PreparedStatement)14 MongoException (com.mongodb.MongoException)13 Document (org.bson.Document)8 TransactionStatus (org.springframework.transaction.TransactionStatus)7 HashMap (java.util.HashMap)6 DataIntegrityViolationException (org.springframework.dao.DataIntegrityViolationException)5 DeadlockLoserDataAccessException (org.springframework.dao.DeadlockLoserDataAccessException)5 IOException (java.io.IOException)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