Example usage for org.springframework.transaction.support TransactionCallback TransactionCallback

List of usage examples for org.springframework.transaction.support TransactionCallback TransactionCallback

Introduction

In this page you can find the example usage for org.springframework.transaction.support TransactionCallback TransactionCallback.

Prototype

TransactionCallback

Source Link

Usage

From source file:org.kuali.kpme.core.util.ClearDatabaseLifecycle.java

protected void clearTables(final PlatformTransactionManager transactionManager, final DataSource dataSource,
        final String schemaName) {
    LOG.info("Clearing tables for schema " + schemaName);
    Assert.assertNotNull("DataSource could not be located.", dataSource);

    if (schemaName == null || schemaName.equals("")) {
        Assert.fail("Empty schema name given");
    }//from  w ww.ja  v  a 2  s  .c  om
    new TransactionTemplate(transactionManager).execute(new TransactionCallback<Object>() {
        public Object doInTransaction(final TransactionStatus status) {
            verifyTestEnvironment(dataSource);
            return new JdbcTemplate(dataSource).execute(new StatementCallback<Object>() {
                public Object doInStatement(Statement statement) throws SQLException {
                    final List<String> reEnableConstraints = new ArrayList<String>();
                    List<List<String>> tableLists = new ArrayList<List<String>>(2);
                    tableLists.add(TABLES_TO_CLEAR);
                    tableLists.add(alternativeTablesToClear);
                    for (List<String> list : tableLists) {
                        for (String tableName : list) {
                            //if there is an id name that doesnt follow convention check and limit accordingly
                            String idName = TABLE_TO_ID_MAP.get(tableName);
                            String deleteStatement = null;
                            Integer clearId = TABLE_START_CLEAR_ID.get(tableName) != null
                                    ? TABLE_START_CLEAR_ID.get(tableName)
                                    : START_CLEAR_ID;
                            if (idName == null) {
                                deleteStatement = "DELETE FROM " + tableName + " WHERE "
                                        + StringUtils.removeEnd(tableName, "_T") + "_ID" + " >= " + clearId;
                            } else {
                                deleteStatement = "DELETE FROM " + tableName + " WHERE " + idName + " >= "
                                        + clearId;
                            }

                            LOG.debug("Clearing contents using statement ->" + deleteStatement + "<-");
                            statement.addBatch(deleteStatement);
                        }
                    }

                    for (final String constraint : reEnableConstraints) {
                        LOG.debug("Enabling constraints using statement ->" + constraint + "<-");
                        statement.addBatch(constraint);
                    }
                    statement.executeBatch();
                    return null;
                }
            });
        }
    });
    LOG.info("Tables successfully cleared for schema " + schemaName);
}

From source file:org.kuali.kpme.core.util.DatabaseCleanupDataLifecycle.java

public void loadData(final PlatformTransactionManager transactionManager, final DataSource dataSource,
        final String schemaName) {
    Assert.assertNotNull("DataSource could not be located.", dataSource);

    if (schemaName == null || schemaName.equals("")) {
        Assert.fail("Empty schema name given");
    }/*ww  w .j  av  a2 s  .c o  m*/
    new TransactionTemplate(transactionManager).execute(new TransactionCallback() {
        public Object doInTransaction(final TransactionStatus status) {
            verifyTestEnvironment(dataSource);
            return new JdbcTemplate(dataSource).execute(new StatementCallback() {
                public Object doInStatement(Statement statement) throws SQLException {
                    List<String> sqlStatements = new ArrayList<String>();
                    //
                    // djunk - add a per-class special test data loader,
                    // loads <testclassname>.sql from the same directory
                    // as the other SQL loaded.
                    if (callingTestClass != null) {
                        sqlStatements.addAll(getTestDataSQLStatements(
                                "src/test/config/sql/" + callingTestClass.getSimpleName() + "-cleanup.sql"));
                    }
                    for (String sql : sqlStatements) {
                        if (!sql.startsWith("#") && !sql.startsWith("//") && !StringUtils.isEmpty(sql.trim())) {
                            // ignore comment lines in our sql reader.
                            statement.addBatch(sql);
                        }
                    }
                    statement.executeBatch();
                    return null;
                }
            });
        }
    });
}

From source file:org.kuali.kpme.core.util.LoadDatabaseDataLifeCycle.java

public void loadData(final PlatformTransactionManager transactionManager, final DataSource dataSource,
        final String schemaName) {
    LOG.info("Populating tables for schema " + schemaName);
    Assert.assertNotNull("DataSource could not be located.", dataSource);

    if (schemaName == null || schemaName.equals("")) {
        Assert.fail("Empty schema name given");
    }/* w ww . j av  a  2s.c o m*/
    new TransactionTemplate(transactionManager).execute(new TransactionCallback<Object>() {
        public Object doInTransaction(final TransactionStatus status) {
            verifyTestEnvironment(dataSource);
            return new JdbcTemplate(dataSource).execute(new StatementCallback<Object>() {
                public Object doInStatement(Statement statement) throws SQLException {
                    if (callingTestClass != null) {
                        List<String> sqlStatements = getTestDataSQLStatements(
                                "src/test/config/sql/" + callingTestClass.getSimpleName() + ".sql");

                        for (String sql : sqlStatements) {
                            if (!sql.startsWith("#") && !sql.startsWith("//")
                                    && !StringUtils.isEmpty(sql.trim())) {
                                // ignore comment lines in our sql reader.
                                statement.addBatch(sql);
                            }
                        }
                    }
                    statement.executeBatch();
                    return null;
                }
            });
        }
    });
}

From source file:org.kuali.kpme.core.util.SQLDataLifeCycle.java

public void loadData(final PlatformTransactionManager transactionManager, final DataSource dataSource,
        final String schemaName) {
    LOG.info("Clearing tables for schema " + schemaName);
    Assert.assertNotNull("DataSource could not be located.", dataSource);

    if (schemaName == null || schemaName.equals("")) {
        Assert.fail("Empty schema name given");
    }//from   w ww  .j  av  a  2s  .  co m
    new TransactionTemplate(transactionManager).execute(new TransactionCallback<Object>() {
        public Object doInTransaction(final TransactionStatus status) {
            verifyTestEnvironment(dataSource);
            return new JdbcTemplate(dataSource).execute(new StatementCallback<Object>() {
                public Object doInStatement(Statement statement) throws SQLException {
                    if (callingTestClass != null) {
                        List<String> sqlStatements = getTestDataSQLStatements(
                                "src/test/config/sql/" + callingTestClass.getSimpleName() + ".sql");

                        for (String sql : sqlStatements) {
                            if (!sql.startsWith("#") && !sql.startsWith("//")
                                    && !StringUtils.isEmpty(sql.trim())) {
                                // ignore comment lines in our sql reader.
                                statement.addBatch(sql);
                            }
                        }
                    }
                    statement.executeBatch();
                    return null;
                }
            });
        }
    });
}

From source file:org.kuali.kra.award.awardhierarchy.sync.service.AwardSyncServiceImpl.java

/**
 * Save or delete object in a separate thread using {@link #SaveBo}.
 * @param object/*from  w ww .  j  a v  a  2s .c om*/
 * @param delete
 * @param runnables
 */
protected void saveInTransaction(final Object object) {
    TransactionTemplate template = new TransactionTemplate(
            (PlatformTransactionManager) KcServiceLocator.getService("transactionManager"));
    template.setPropagationBehavior(Propagation.REQUIRES_NEW.value());
    template.execute(new TransactionCallback() {
        @SuppressWarnings("unchecked")
        public Object doInTransaction(TransactionStatus status) {
            if (object instanceof PersistableBusinessObject) {
                getBusinessObjectService().save((PersistableBusinessObject) object);
            } else if (object instanceof List) {
                getBusinessObjectService().save((List) object);
            }
            return null;
        }
    });
}

From source file:org.kuali.kra.award.awardhierarchy.sync.service.AwardSyncServiceImpl.java

/**
 * Run the runnable in a separate transaction, commiting when finished or rolling back
 * if an exception is generated./*from   ww w.j  a va 2s  . co  m*/
 * @param runnable
 */
protected void runInTransaction(final TransactionRunnable runnable) {
    final UserSession session = GlobalVariables.getUserSession();
    syncExecutor.execute(new SyncRunnable() {
        public void run() {
            GlobalVariables.setUserSession(session);
            TransactionTemplate template = new TransactionTemplate(
                    (PlatformTransactionManager) KcServiceLocator.getService("transactionManager"));
            template.setPropagationBehavior(Propagation.REQUIRES_NEW.value());
            template.execute(new TransactionCallback() {
                public Object doInTransaction(TransactionStatus status) {
                    runnable.run();
                    return null;
                }
            });
        }
    });
}

From source file:org.kuali.kra.infrastructure.TestUtilities.java

License:asdf

public static void clearTables(final PlatformTransactionManager transactionManager, final DataSource dataSource,
        final String edenSchemaName, final List<String> dontClear) {
    LOG.info("Clearing tables for schema " + edenSchemaName);
    if (dataSource == null) {
        Assert.fail("Null data source given");
    }/*from  w w  w. j a va  2s. co m*/
    if (edenSchemaName == null || edenSchemaName.equals("")) {
        Assert.fail("Empty eden schema name given");
    }
    new TransactionTemplate(transactionManager).execute(new TransactionCallback() {
        public Object doInTransaction(TransactionStatus status) {
            verifyTestEnvironment(dataSource);
            JdbcTemplate template = new JdbcTemplate(dataSource);
            return template.execute(new StatementCallback() {
                public Object doInStatement(Statement statement) throws SQLException {
                    List<String> reEnableConstraints = new ArrayList<String>();
                    ResultSet resultSet = statement.getConnection().getMetaData().getTables(null,
                            edenSchemaName, null, new String[] { "TABLE" });
                    while (resultSet.next()) {
                        String tableName = resultSet.getString("TABLE_NAME");
                        if (tableName.startsWith("EN_") && !dontClear.contains(tableName)) {
                            ResultSet keyResultSet = statement.getConnection().getMetaData()
                                    .getExportedKeys(null, edenSchemaName, tableName);
                            while (keyResultSet.next()) {
                                String fkName = keyResultSet.getString("FK_NAME");
                                String fkTableName = keyResultSet.getString("FKTABLE_NAME");
                                statement.addBatch(
                                        "ALTER TABLE " + fkTableName + " DISABLE CONSTRAINT " + fkName);
                                reEnableConstraints
                                        .add("ALTER TABLE " + fkTableName + " ENABLE CONSTRAINT " + fkName);
                            }
                            keyResultSet.close();
                            statement.addBatch("DELETE FROM " + tableName.toUpperCase());
                        }
                    }
                    for (String constraint : reEnableConstraints) {
                        statement.addBatch(constraint);
                    }
                    statement.executeBatch();
                    resultSet.close();
                    return null;
                }
            });
        }
    });
    LOG.info("Tables successfully cleared for schema " + edenSchemaName);
}

From source file:org.kuali.ole.module.purap.util.PurApRelatedViews.java

public List updateRelatedView(final Class<?> clazz, List<? extends AbstractRelatedView> relatedList,
        final boolean removeCurrentDocument) {
    if (relatedList == null) {
        TransactionTemplate template = new TransactionTemplate(getTransactionManager());
        relatedList = template.execute(new TransactionCallback<List<? extends AbstractRelatedView>>() {
            @Override/* ww  w  .  j ava  2 s  .  c om*/
            public List<? extends AbstractRelatedView> doInTransaction(TransactionStatus status) {
                List<? extends AbstractRelatedView> relatedList = SpringContext.getBean(PurapService.class)
                        .getRelatedViews(clazz, accountsPayablePurchasingDocumentLinkIdentifier);
                if (removeCurrentDocument) {
                    for (AbstractRelatedView view : relatedList) {
                        //KFSMI-4576 Mask/Unmask purapDocumentIdentifier field value
                        maskPONumberIfUnapproved(view);
                        if (documentNumber.equals(view.getDocumentNumber())) {
                            relatedList.remove(view);
                            break;
                        }
                    }
                }
                return relatedList;
            }
        });
    }

    return relatedList;
}

From source file:org.kuali.rice.ken.service.impl.ConcurrentJob.java

/**
 * Main processing method which invokes subclass implementations of template methods
 * to obtain available work items, and process them concurrently
 * @return a ProcessingResult object containing the results of processing
 *///from   w  w  w  .  j  a v  a 2 s . c o  m
@SuppressWarnings("unchecked")
public ProcessingResult run() {
    if (LOG.isDebugEnabled()) {
        LOG.debug("[" + new Timestamp(System.currentTimeMillis()).toString() + "] STARTING RUN");
    }

    final ProcessingResult result = new ProcessingResult();

    // retrieve list of available work items in a transaction
    Collection<T> items = null;
    try {
        items = (Collection<T>) createNewTransaction().execute(new TransactionCallback() {
            public Object doInTransaction(TransactionStatus txStatus) {
                return takeAvailableWorkItems();
            }
        });
    } catch (DataAccessException dae) {
        if (dae instanceof OptimisticLockingFailureException
                || dae.contains(OptimisticLockingFailureException.class)
                || dae.contains(OptimisticLockException.class)) {
            // anticipated in the case that another thread is trying to grab items
            LOG.info("Contention while taking work items: " + dae.getMessage());
        } else {
            // in addition to logging a message, should we throw an exception or log a failure here?
            LOG.error("Error taking work items", dae);
            Throwable t = dae.getMostSpecificCause();
            if (t != null && t instanceof SQLException) {
                SQLException sqle = (SQLException) t;
                if (sqle.getErrorCode() == ORACLE_00054
                        && StringUtils.contains(sqle.getMessage(), "resource busy")) {
                    // this is expected and non-fatal given that these jobs will run again
                    LOG.warn("Select for update lock contention encountered: " + sqle.getMessage());
                } else if (sqle.getErrorCode() == ORACLE_00060
                        && StringUtils.contains(sqle.getMessage(), "deadlock detected")) {
                    // this is bad...two parties are waiting forever somewhere...
                    // database is probably wedged now :(
                    LOG.error("Select for update deadlock encountered! " + sqle.getMessage());
                }
            }
        }
        return result;
    } catch (UnexpectedRollbackException ure) {
        LOG.error("UnexpectedRollbackException", ure);
        return result;
    } catch (TransactionException te) {
        LOG.error("Error occurred obtaining available work items", te);
        result.addFailure("Error occurred obtaining available work items: " + te);
        return result;
    }

    Collection<Collection<T>> groupedWorkItems = groupWorkItems(items, result);

    // now iterate over all work groups and process each
    Iterator<Collection<T>> i = groupedWorkItems.iterator();
    List<Future> futures = new ArrayList<Future>();
    while (i.hasNext()) {
        final Collection<T> workUnit = i.next();

        LOG.info("Processing work unit: " + workUnit);
        /* performed within transaction */
        /* executor manages threads to run work items... */
        futures.add(executor.submit(new Callable() {
            public Object call() throws Exception {
                ProcessingResult result = new ProcessingResult();
                try {
                    Collection<?> successes = (Collection<Object>) createNewTransaction()
                            .execute(new TransactionCallback() {
                                public Object doInTransaction(TransactionStatus txStatus) {
                                    return processWorkItems(workUnit);
                                }
                            });
                    result.addAllSuccesses(successes);
                } catch (Exception e) {
                    LOG.error("Error occurred processing work unit " + workUnit, e);
                    for (final T workItem : workUnit) {
                        LOG.error("Error occurred processing work item " + workItem, e);
                        result.addFailure("Error occurred processing work item " + workItem + ": " + e);
                        unlockWorkItemAtomically(workItem);
                    }
                }
                return result;
            }
        }));
    }

    // wait for workers to finish
    for (Future f : futures) {
        try {
            ProcessingResult workResult = (ProcessingResult) f.get();
            result.add(workResult);
        } catch (Exception e) {
            String message = "Error obtaining work result: " + e;
            LOG.error(message, e);
            result.addFailure(message);
        }
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("[" + new Timestamp(System.currentTimeMillis()).toString() + "] FINISHED RUN - " + result);
    }

    return result;
}

From source file:org.kuali.rice.ken.service.impl.ConcurrentJob.java

protected void unlockWorkItemAtomically(final T workItem) {
    try {//from   www.j  av  a 2 s.  co m
        createNewTransaction().execute(new TransactionCallback() {
            public Object doInTransaction(TransactionStatus txStatus) {
                LOG.info("Unlocking failed work item: " + workItem);
                unlockWorkItem(workItem);
                return null;
            }
        });
    } catch (Exception e2) {
        LOG.error("Error unlocking failed work item " + workItem, e2);
    }
}