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());
}
}
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
}
}
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);
}
}
}
});
}
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;
}
});
}
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;
}
Aggregations